diff --git a/.agents/skills/bundle-size-optimization b/.agents/skills/bundle-size-optimization deleted file mode 120000 index 692e634b24..0000000000 --- a/.agents/skills/bundle-size-optimization +++ /dev/null @@ -1 +0,0 @@ -../../skills/bundle-size-optimization \ No newline at end of file diff --git a/.changeset/brave-pans-create.md b/.changeset/brave-pans-create.md new file mode 100644 index 0000000000..0411cdfa59 --- /dev/null +++ b/.changeset/brave-pans-create.md @@ -0,0 +1,10 @@ +--- +'@tanstack/solid-router-ssr-query': patch +'@tanstack/solid-router-devtools': patch +'@tanstack/solid-start-client': patch +'@tanstack/solid-start-server': patch +'@tanstack/solid-router': patch +'@tanstack/solid-start': patch +--- + +Update to beta.4 diff --git a/.changeset/clever-vans-yawn.md b/.changeset/clever-vans-yawn.md new file mode 100644 index 0000000000..2f2ad97772 --- /dev/null +++ b/.changeset/clever-vans-yawn.md @@ -0,0 +1,10 @@ +--- +'@tanstack/solid-router-ssr-query': patch +'@tanstack/solid-router-devtools': patch +'@tanstack/solid-start-client': patch +'@tanstack/solid-start-server': patch +'@tanstack/solid-router': patch +'@tanstack/solid-start': patch +--- + +build: bundle packages with rolldown diff --git a/.changeset/config.json b/.changeset/config.json index 9815b19762..78e849b433 100644 --- a/.changeset/config.json +++ b/.changeset/config.json @@ -1,8 +1,8 @@ { "$schema": "https://unpkg.com/@changesets/config@3.1.2/schema.json", "changelog": [ - "@changesets/changelog-github", - { "repo": "TanStack/router", "disableThanks": true } + "@svitejs/changesets-changelog-github-compact", + { "repo": "TanStack/router" } ], "commit": false, "access": "public", diff --git a/.changeset/evil-parrots-end.md b/.changeset/evil-parrots-end.md new file mode 100644 index 0000000000..6f7116a6c4 --- /dev/null +++ b/.changeset/evil-parrots-end.md @@ -0,0 +1,6 @@ +--- +'@tanstack/solid-router': patch +'@tanstack/solid-start': patch +--- + +Bump to solid js 2.0.0-beta.3 diff --git a/.changeset/pre.json b/.changeset/pre.json new file mode 100644 index 0000000000..5ebfab4992 --- /dev/null +++ b/.changeset/pre.json @@ -0,0 +1,58 @@ +{ + "mode": "pre", + "tag": "alpha", + "initialVersions": { + "@tanstack/arktype-adapter": "1.166.7", + "@tanstack/eslint-plugin-router": "1.161.4", + "@tanstack/history": "1.161.4", + "@tanstack/nitro-v2-vite-plugin": "1.154.7", + "@tanstack/react-router": "1.166.7", + "@tanstack/react-router-devtools": "1.166.7", + "@tanstack/react-router-ssr-query": "1.166.7", + "@tanstack/react-start": "1.166.8", + "@tanstack/react-start-client": "1.166.7", + "@tanstack/react-start-server": "1.166.7", + "@tanstack/router-cli": "1.166.7", + "@tanstack/router-core": "1.166.7", + "@tanstack/router-devtools": "1.166.7", + "@tanstack/router-devtools-core": "1.166.7", + "@tanstack/router-generator": "1.166.7", + "@tanstack/router-plugin": "1.166.7", + "@tanstack/router-ssr-query-core": "1.166.7", + "@tanstack/router-utils": "1.161.4", + "@tanstack/router-vite-plugin": "1.166.7", + "@tanstack/solid-router": "1.166.7", + "@tanstack/solid-router-devtools": "1.166.7", + "@tanstack/solid-router-ssr-query": "1.166.7", + "@tanstack/solid-start": "1.166.8", + "@tanstack/solid-start-client": "1.166.7", + "@tanstack/solid-start-server": "1.166.7", + "@tanstack/start-client-core": "1.166.7", + "@tanstack/start-fn-stubs": "1.161.4", + "@tanstack/start-plugin-core": "1.166.8", + "@tanstack/start-server-core": "1.166.7", + "@tanstack/start-static-server-functions": "1.166.8", + "@tanstack/start-storage-context": "1.166.7", + "@tanstack/valibot-adapter": "1.166.7", + "@tanstack/virtual-file-routes": "1.161.4", + "@tanstack/vue-router": "1.166.7", + "@tanstack/vue-router-devtools": "1.166.7", + "@tanstack/vue-router-ssr-query": "1.166.7", + "@tanstack/vue-start": "1.166.8", + "@tanstack/vue-start-client": "1.166.7", + "@tanstack/vue-start-server": "1.166.7", + "@tanstack/zod-adapter": "1.166.7" + }, + "changesets": [ + "brave-pans-create", + "clever-vans-yawn", + "evil-parrots-end", + "quiet-shrimps-jam", + "smooth-swans-ask", + "social-mails-sort", + "solid-kings-help", + "three-carrots-return", + "tired-pants-eat", + "wicked-olives-poke" + ] +} diff --git a/.changeset/quiet-shrimps-jam.md b/.changeset/quiet-shrimps-jam.md new file mode 100644 index 0000000000..240815ab5c --- /dev/null +++ b/.changeset/quiet-shrimps-jam.md @@ -0,0 +1,5 @@ +--- +'@tanstack/solid-router-ssr-query': patch +--- + +fix: use solid v2 compatible solid-query diff --git a/.changeset/rsbuild-manifest-module-chunks-once.md b/.changeset/rsbuild-manifest-module-chunks-once.md deleted file mode 100644 index 02febd9d84..0000000000 --- a/.changeset/rsbuild-manifest-module-chunks-once.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@tanstack/start-plugin-core': patch ---- - -Rsbuild: the Start manifest pass that runs after every client compilation (builds and each dev update) reads an imported module's chunks once per compilation and counts the module once per importing chunk, instead of once per import connection. The manifest is unchanged; the pass takes about 40 % less time (on a 333-route app, tens of milliseconds less per HMR update). diff --git a/.changeset/rsbuild-manifest-own-chunks.md b/.changeset/rsbuild-manifest-own-chunks.md deleted file mode 100644 index 04e8e29928..0000000000 --- a/.changeset/rsbuild-manifest-own-chunks.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@tanstack/start-plugin-core': patch ---- - -Rsbuild: a route's client manifest entry lists only its own chunks and CSS. When two routes shared a module in a chunk of its own, each route's entry also listed the other route's chunk as a preload and its stylesheet. diff --git a/.changeset/rsbuild-rule-use-falsy-loaders.md b/.changeset/rsbuild-rule-use-falsy-loaders.md deleted file mode 100644 index a84a054fbd..0000000000 --- a/.changeset/rsbuild-rule-use-falsy-loaders.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@tanstack/start-plugin-core': patch ---- - -fix: the Rsbuild RSC integration skips falsy entries in a rule's `use` array (Rspack's conditionally disabled loaders) instead of treating them as loaders. diff --git a/.changeset/rsbuild-virtual-modules-build.md b/.changeset/rsbuild-virtual-modules-build.md deleted file mode 100644 index 01a0c5ee6e..0000000000 --- a/.changeset/rsbuild-virtual-modules-build.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@tanstack/start-plugin-core': patch ---- - -Rsbuild: fix the Rsbuild plugin build after two changes to its virtual modules crossed. Without this fix the package does not build, so no release could ship it. The Rsbuild dev manifest is written to its virtual module under the app's root. diff --git a/.changeset/rsbuild-virtual-modules-root.md b/.changeset/rsbuild-virtual-modules-root.md deleted file mode 100644 index 427043a712..0000000000 --- a/.changeset/rsbuild-virtual-modules-root.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@tanstack/start-plugin-core': patch ---- - -Rsbuild: Start writes its virtual modules under the app's root, not the working directory. An app built or served from another directory (`rsbuild build --root ` from a monorepo root) no longer fails with "Module not found" on the packages they import, such as RSC's serialization adapters. diff --git a/.changeset/rsc-security-floor.md b/.changeset/rsc-security-floor.md deleted file mode 100644 index 9c828f13b3..0000000000 --- a/.changeset/rsc-security-floor.md +++ /dev/null @@ -1,8 +0,0 @@ ---- -'@tanstack/react-start-rsc': patch ---- - -Raise the minimum RSC bundler peer dependencies to versions with the React Server Components fixes for GHSA-xqc2-xf4c-x3h3 (CVE-2026-126187, unauthenticated RCE) and GHSA-h3gv-c5rc-p453 (server function DoS): - -- `@vitejs/plugin-rsc` to `>=0.5.38` (GHSA-59pf-q495-3c99), which vendors a fixed `react-server-dom-webpack`. -- `react-server-dom-rspack` to `>=0.1.1`, the first release built from React sources that include the fix. diff --git a/.changeset/smooth-swans-ask.md b/.changeset/smooth-swans-ask.md new file mode 100644 index 0000000000..bf7ecda35a --- /dev/null +++ b/.changeset/smooth-swans-ask.md @@ -0,0 +1,10 @@ +--- +'@tanstack/solid-router-ssr-query': patch +'@tanstack/solid-router-devtools': patch +'@tanstack/solid-start-client': patch +'@tanstack/solid-start-server': patch +'@tanstack/solid-router': patch +'@tanstack/solid-start': patch +--- + +fix: add vite 8 compat diff --git a/.changeset/social-mails-sort.md b/.changeset/social-mails-sort.md new file mode 100644 index 0000000000..77309d35a0 --- /dev/null +++ b/.changeset/social-mails-sort.md @@ -0,0 +1,10 @@ +--- +'@tanstack/solid-router-ssr-query': major +'@tanstack/solid-router-devtools': major +'@tanstack/solid-start-client': major +'@tanstack/solid-start-server': major +'@tanstack/solid-router': major +'@tanstack/solid-start': major +--- + +solid v2 pre-release for solid-router and start diff --git a/.changeset/solid-kings-help.md b/.changeset/solid-kings-help.md new file mode 100644 index 0000000000..b638658e9b --- /dev/null +++ b/.changeset/solid-kings-help.md @@ -0,0 +1,5 @@ +--- +'@tanstack/solid-router': patch +--- + +Upgrade solid refresh, fix deep equal for promises diff --git a/.changeset/start-server-fn-custom-id-check.md b/.changeset/start-server-fn-custom-id-check.md deleted file mode 100644 index 384f0ade06..0000000000 --- a/.changeset/start-server-fn-custom-id-check.md +++ /dev/null @@ -1,7 +0,0 @@ ---- -'@tanstack/start-plugin-core': minor ---- - -A server function id that a custom `serverFns.generateFunctionId` returns and that never worked over HTTP now fails the build, with an error naming the file, the function and the id: whitespace, a control or non-ASCII character, any of `"`, `#`, `/`, `<`, `>`, `?`, `\`, `^`, `` ` ``, `{`, `}`, the ids `.` and `..`, and a percent-encoding the server reads as another id (`%41`, lowercase hex, `%2E`) or rejects. The client puts the id in the URL unencoded, so a `#` or `?` ended the path and a `/` cut the id short (the call silently ran another server function of the file or none), and the other characters reached the server percent-encoded and matched no function. An id embedding a non-ASCII `functionName` is one of these. One case did work and now fails the build: such an id on a server function only SSR code called. - -Ids with `%` or the other characters URLs allow (such as `:`, `@`, `+`, `=`, `,`, `;`, `!`, `*`, `(`, `)`, `&`, `'`, `|`, `[`, `]`) still build and reach their handler, with a deprecation warning (from the Vite plugin; the Rsbuild plugin does not print compiler warnings yet): the next major version rejects them, since proxies and servers may decode or rewrite them (hash the inputs instead, as the documented example does). An id with `'` no longer breaks the server bundle. diff --git a/.changeset/start-vite-root-library-discovery.md b/.changeset/start-vite-root-library-discovery.md deleted file mode 100644 index d4e8221c59..0000000000 --- a/.changeset/start-vite-root-library-discovery.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@tanstack/start-plugin-core': patch ---- - -Vite: Start finds the Start libraries it bundles in the SSR build from Vite's root, not the working directory. A `vite build ` run from another directory (a monorepo root, a script) no longer leaves them external and uncompiled, where their server fns returned `undefined`. diff --git a/.changeset/three-carrots-return.md b/.changeset/three-carrots-return.md new file mode 100644 index 0000000000..bd8daa172e --- /dev/null +++ b/.changeset/three-carrots-return.md @@ -0,0 +1,10 @@ +--- +'@tanstack/solid-router-ssr-query': patch +'@tanstack/solid-router-devtools': patch +'@tanstack/solid-start-client': patch +'@tanstack/solid-start-server': patch +'@tanstack/solid-router': patch +'@tanstack/solid-start': patch +--- + +bump to alpha.1 diff --git a/.changeset/tired-pants-eat.md b/.changeset/tired-pants-eat.md new file mode 100644 index 0000000000..d4a071c298 --- /dev/null +++ b/.changeset/tired-pants-eat.md @@ -0,0 +1,5 @@ +--- +'@tanstack/solid-start': patch +--- + +fix: better rollupOptions/rolldownOptions handling diff --git a/.changeset/wicked-olives-poke.md b/.changeset/wicked-olives-poke.md new file mode 100644 index 0000000000..479ea10d53 --- /dev/null +++ b/.changeset/wicked-olives-poke.md @@ -0,0 +1,5 @@ +--- +'@tanstack/solid-router-ssr-query': patch +--- + +fix: use solid-query 6.0.0-alpha.0 diff --git a/.coderabbit.yaml b/.coderabbit.yaml deleted file mode 100644 index 21d884dbeb..0000000000 --- a/.coderabbit.yaml +++ /dev/null @@ -1,12 +0,0 @@ -# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json - -reviews: - request_changes_workflow: false - slop_detection: - enabled: true - -knowledge_base: - code_guidelines: - enabled: true - filePatterns: - - 'CONTRIBUTING.md' diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS deleted file mode 100644 index a4c1d62013..0000000000 --- a/.github/CODEOWNERS +++ /dev/null @@ -1,7 +0,0 @@ -.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 9dd0def7bd..206560136b 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -4,24 +4,16 @@ body: - type: markdown attributes: value: | - - Thank you for reporting an issue :pray:. - This issue tracker is for reporting bugs found in TanStack Router and/or Start. + This issue tracker is for reporting bugs found in `router` (https://github.com/tanstack/router). 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: - - 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 + - `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 The more information you fill in, the better the community can help you. - type: dropdown @@ -44,22 +36,21 @@ body: - type: input id: link attributes: - label: Complete minimal reproducer + label: Your Example Website or App description: | - 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. + 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. placeholder: reproduction URL validations: required: true - type: textarea id: steps attributes: - label: Steps to Reproduce the Bug + label: Steps to Reproduce the Bug or Issue 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 deleted file mode 100644 index a5ef10f1ff..0000000000 --- a/.github/pull_request_template.md +++ /dev/null @@ -1,22 +0,0 @@ -## 🎯 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 6fd5aa1c86..03cea18d0e 100644 --- a/.github/renovate.json +++ b/.github/renovate.json @@ -3,7 +3,6 @@ "configMigration": true, "extends": [ "config:recommended", - "helpers:pinGitHubActionDigests", "group:allNonMajor", "schedule:weekly", ":approveMajorUpdates", @@ -21,6 +20,7 @@ "@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 78aea28c12..b0176c636e 100644 --- a/.github/workflows/autofix.yml +++ b/.github/workflows/autofix.yml @@ -2,6 +2,8 @@ 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 }} @@ -17,16 +19,14 @@ jobs: if: ${{ github.event_name == 'push' || !github.event.pull_request.draft }} steps: - name: Checkout - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - with: - persist-credentials: false + uses: actions/checkout@v6.0.2 - name: Setup Tools - uses: TanStack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 # main + uses: TanStack/config/.github/setup@main - name: Fix formatting run: pnpm format - name: Generate labeler config run: pnpm labeler-generate - name: Apply fixes - uses: autofix-ci/action@c5b2d67aa2274e7b5a18224e8171550871fc7e4a # v1.3.4 + uses: autofix-ci/action@635ffb0c9798bd160680f18fd73371e355b85f27 with: commit-message: 'ci: apply automated fixes' diff --git a/.github/workflows/benchmarks.yml b/.github/workflows/benchmarks.yml deleted file mode 100644 index bbc3a1fa24..0000000000 --- a/.github/workflows/benchmarks.yml +++ /dev/null @@ -1,92 +0,0 @@ -# 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 index 51ffa28e4c..f0819e0a89 100644 --- a/.github/workflows/bundle-size.yml +++ b/.github/workflows/bundle-size.yml @@ -1,26 +1,18 @@ name: Bundle Size on: - # We use `pull_request` to split trust boundaries across jobs: + # We use `pull_request_target` 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: + pull_request_target: 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: @@ -35,23 +27,23 @@ env: jobs: benchmark-pr: name: Benchmark PR - if: github.event_name == 'pull_request' + if: github.event_name == 'pull_request_target' runs-on: ubuntu-latest outputs: current_json_b64: ${{ steps.capture.outputs.current_json_b64 }} steps: - name: Checkout - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@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 + uses: TanStack/config/.github/setup@main - name: Measure Bundle Size - run: pnpm benchmark:bundle-size --outputStyle=stream --skipRemoteCache + run: pnpm nx run @benchmarks/bundle-size:build --outputStyle=stream --skipRemoteCache - name: Capture Benchmark Outputs id: capture @@ -62,7 +54,7 @@ jobs: comment-pr: name: Upsert PR Comment - if: github.event_name == 'pull_request' + if: github.event_name == 'pull_request_target' runs-on: ubuntu-latest needs: benchmark-pr permissions: @@ -70,7 +62,7 @@ jobs: pull-requests: write steps: - name: Checkout - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@v6.0.2 with: fetch-depth: 0 persist-credentials: false @@ -95,22 +87,15 @@ jobs: 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 + --base-sha "${{ github.event.pull_request.base.sha }}" \ + --dashboard-url "https://${{ github.repository_owner }}.github.io/${{ github.event.repository.name }}/benchmarks/bundle-size/" - name: Upsert Sticky PR Comment - # Fork PRs have a read-only GITHUB_TOKEN, so they cannot update comments. - if: ${{ github.event.pull_request.head.repo.full_name == github.repository }} env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | @@ -120,24 +105,23 @@ jobs: benchmark-main: name: Publish Bundle Size History - if: (github.event_name == 'push' || github.event_name == 'workflow_dispatch') && github.ref == 'refs/heads/main' && github.repository_owner == 'TanStack' + if: github.event_name == 'push' && github.ref == 'refs/heads/main' && github.repository_owner == 'TanStack' runs-on: ubuntu-latest permissions: contents: write steps: - name: Checkout - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@v6.0.2 with: fetch-depth: 0 - persist-credentials: false - name: Setup Tools - uses: TanStack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 # main + uses: TanStack/config/.github/setup@main - name: Measure Bundle Size - run: pnpm benchmark:bundle-size --outputStyle=stream --skipRemoteCache + run: pnpm nx run @benchmarks/bundle-size:build --outputStyle=stream --skipRemoteCache - name: Publish Benchmark Dashboard - uses: benchmark-action/github-action-benchmark@52576c92bccf6ac60c8223ec7eb2565637cae9ba # v1.22.1 + uses: benchmark-action/github-action-benchmark@4bdcce38c94cec68da58d012ac24b7b1155efe8b # v1.20.7 with: tool: customSmallerIsBetter name: Bundle Size (gzip) diff --git a/.github/workflows/check-skills.yml b/.github/workflows/check-skills.yml index f00a11731b..9888015bb0 100644 --- a/.github/workflows/check-skills.yml +++ b/.github/workflows/check-skills.yml @@ -1,122 +1,172 @@ # 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. +# Checks for stale intent skills after a release and opens a review PR +# if any skills need attention. The PR body includes a prompt you can +# paste into Claude Code, Cursor, or any coding agent to update them. # -# Triggers: pull requests touching skills/artifacts, pushes to main affecting -# docs/source paths, new release published, or manual workflow_dispatch. -# -# intent-workflow-version: 4 +# Triggers: new release published, or manual workflow_dispatch. # # Template variables (replaced by `intent setup`): -# @tanstack/router — e.g. @tanstack/query or my-workspace workspace +# @tanstack/react-router — e.g. @tanstack/query +# +# Adapted for TanStack Router monorepo: loops over all packages with skills. 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: {} +permissions: + contents: write + pull-requests: write jobs: - validate: - name: Validate intent skills - if: github.event_name == 'pull_request' + check: + name: Check for stale skills 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 + uses: actions/checkout@v4 with: fetch-depth: 0 - persist-credentials: true # review job pushes a generated branch - name: Setup Node - uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 + uses: actions/setup-node@v4 with: - node-version: 24 - package-manager-cache: false + node-version: 20 - - name: Install intent + - name: Install intent CLI run: npm install -g @tanstack/intent - - name: Check skills + - name: Install dependencies + run: npm install --ignore-scripts + env: + npm_config_legacy_peer_deps: 'true' + + - name: Check staleness id: stale run: | - intent stale --github-review --package-label "@tanstack/router" + # Monorepo: collect stale reports from all packages with skills + ALL_OUTPUT="[" + FIRST=true + for dir in packages/*/; do + if [ -d "$dir/skills" ]; then + PKG_OUTPUT=$(cd "$dir" && npx @tanstack/intent stale --json 2>/dev/null) || true + if [ -n "$PKG_OUTPUT" ] && [ "$PKG_OUTPUT" != "[]" ] && [ "$PKG_OUTPUT" != "No intent-enabled packages found." ]; then + if [ "$FIRST" = true ]; then + FIRST=false + else + ALL_OUTPUT="${ALL_OUTPUT}," + fi + # Strip outer brackets and append entries + ENTRIES=$(echo "$PKG_OUTPUT" | node -e " + const input = require('fs').readFileSync('/dev/stdin','utf8').trim(); + try { const arr = JSON.parse(input); process.stdout.write(JSON.stringify(arr).slice(1, -1)); } catch {} + ") + ALL_OUTPUT="${ALL_OUTPUT}${ENTRIES}" + fi + fi + done + ALL_OUTPUT="${ALL_OUTPUT}]" - - 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' }} + echo "$ALL_OUTPUT" + + # Check if any skills need review + NEEDS_REVIEW=$(echo "$ALL_OUTPUT" | node -e " + const input = require('fs').readFileSync('/dev/stdin','utf8'); + try { + const reports = JSON.parse(input); + const stale = reports.flatMap(r => + r.skills.filter(s => s.needsReview).map(s => ({ library: r.library, skill: s.name, reasons: s.reasons })) + ); + if (stale.length > 0) { + console.log(JSON.stringify(stale)); + } + } catch {} + ") + + if [ -z "$NEEDS_REVIEW" ]; then + echo "has_stale=false" >> "$GITHUB_OUTPUT" + else + echo "has_stale=true" >> "$GITHUB_OUTPUT" + # Escape for multiline GH output + EOF=$(dd if=/dev/urandom bs=15 count=1 status=none | base64) + echo "stale_json<<$EOF" >> "$GITHUB_OUTPUT" + echo "$NEEDS_REVIEW" >> "$GITHUB_OUTPUT" + echo "$EOF" >> "$GITHUB_OUTPUT" + fi + + - name: Build summary + if: steps.stale.outputs.has_stale == 'true' + id: summary run: | + node -e " + const stale = JSON.parse(process.env.STALE_JSON); + const lines = stale.map(s => + '- **' + s.skill + '** (' + s.library + '): ' + s.reasons.join(', ') + ); + const summary = lines.join('\n'); + + const prompt = [ + 'Review and update the following stale intent skills for TanStack Router:', + '', + ...stale.map(s => '- ' + s.skill + ': ' + s.reasons.join(', ')), + '', + 'For each stale skill:', + '1. Read the current SKILL.md file', + '2. Check what changed in the library since the skill was last updated', + '3. Update the skill content to reflect current APIs and behavior', + '4. Run \`npx @tanstack/intent validate\` to verify the updated skill', + ].join('\n'); + + // Write outputs + const fs = require('fs'); + const env = fs.readFileSync(process.env.GITHUB_OUTPUT, 'utf8'); + const eof = require('crypto').randomBytes(15).toString('base64'); + fs.appendFileSync(process.env.GITHUB_OUTPUT, + 'summary<<' + eof + '\n' + summary + '\n' + eof + '\n' + + 'prompt<<' + eof + '\n' + prompt + '\n' + eof + '\n' + ); + " + env: + STALE_JSON: ${{ steps.stale.outputs.stale_json }} + + - name: Open review PR + if: steps.stale.outputs.has_stale == 'true' + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + VERSION="${{ github.event.release.tag_name || 'manual' }}" BRANCH="skills/review-${VERSION}" git config user.name "github-actions[bot]" git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git checkout -b "$BRANCH" + git commit --allow-empty -m "chore: review stale skills for ${VERSION}" + git push origin "$BRANCH" - 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 + gh pr create \ + --title "Review stale skills (${VERSION})" \ + --body "$(cat <<'PREOF' + ## Stale Skills Detected - 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 + The following skills may need updates after the latest release: + + ${{ steps.summary.outputs.summary }} + + --- + + ### Update Prompt + + Paste this into your coding agent (Claude Code, Cursor, etc.): + + ~~~ + ${{ steps.summary.outputs.prompt }} + ~~~ + + PREOF + )" \ + --head "$BRANCH" \ + --base main diff --git a/.github/workflows/client-nav-benchmarks.yml b/.github/workflows/client-nav-benchmarks.yml new file mode 100644 index 0000000000..1297e9c102 --- /dev/null +++ b/.github/workflows/client-nav-benchmarks.yml @@ -0,0 +1,52 @@ +# Setup taken from https://codspeed.io/docs/benchmarks/nodejs/vitest +name: Benchmarks + +on: + push: + branches: + - 'main' + paths: + - 'packages/**' + - 'benchmarks/**' + pull_request: + paths: + - 'packages/**' + - 'benchmarks/**' + workflow_dispatch: + +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 + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v6.0.2 + + - name: Setup Tools + uses: TanStack/config/.github/setup@main + + - name: Run ${{ matrix.benchmark }}:${{ matrix.framework }} CodSpeed benchmark + continue-on-error: true + uses: CodSpeedHQ/action@v4 + with: + mode: simulation + run: WITH_INSTRUMENTATION=1 pnpm nx run @benchmarks/${{ matrix.benchmark }}:test:perf:${{ matrix.framework }} diff --git a/.github/workflows/compiler-platforms.yml b/.github/workflows/compiler-platforms.yml deleted file mode 100644 index ad70e39bb6..0000000000 --- a/.github/workflows/compiler-platforms.yml +++ /dev/null @@ -1,101 +0,0 @@ -name: Compiler Platforms - -# The main PR workflow only runs on Linux x64 (glibc). The compilers load a -# native Yuku binary per platform and handle platform-specific paths, so run -# their unit tests and a Vite and Rsbuild production build on the other -# platforms we ship to. - -on: - pull_request: - paths: - - 'packages/router-utils/**' - - 'packages/router-generator/**' - - 'packages/router-plugin/**' - - 'packages/start-plugin-core/**' - - 'pnpm-lock.yaml' - - '.github/workflows/compiler-platforms.yml' - schedule: - # Weekly, to catch new Yuku releases and runner image updates - - cron: '0 6 * * 1' - workflow_dispatch: - -concurrency: - group: ${{ github.workflow }}-${{ github.event.number || github.ref }} - cancel-in-progress: true - -permissions: - contents: read - -env: - NX_DAEMON: 'false' - NX_NO_CLOUD: 'true' - -defaults: - run: - shell: bash - -jobs: - compiler: - name: ${{ matrix.name }} - runs-on: ${{ matrix.os }} - # actions/setup-node only ships glibc builds, so musl uses Alpine's Node image - container: ${{ matrix.container }} - strategy: - fail-fast: false - matrix: - include: - - name: Windows x64 - os: windows-latest - - name: macOS arm64 - os: macos-latest - - name: Linux arm64 - os: ubuntu-24.04-arm - - name: Linux x64 musl - os: ubuntu-latest - container: node:24.8.0-alpine3.22@sha256:3e843c608bb5232f39ecb2b25e41214b958b0795914707374c8acc28487dea17 - steps: - - name: Install system packages - if: ${{ matrix.container }} - shell: sh - run: apk add --no-cache bash git - - name: Keep LF line endings - # Snapshots are stored with LF. Windows runners check out CRLF by default, - # and with `* text=auto` disabling autocrlf alone still uses the native eol - run: | - git config --global core.autocrlf false - git config --global core.eol lf - - name: Checkout - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - with: - persist-credentials: false - - name: Setup pnpm - if: ${{ !matrix.container }} - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 - - name: Setup Node - if: ${{ !matrix.container }} - uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 - with: - node-version-file: .nvmrc - package-manager-cache: false - - name: Setup pnpm (container) - if: ${{ matrix.container }} - run: npm install --global "$(node -p "require('./package.json').packageManager")" - - name: Install dependencies - run: >- - pnpm install --frozen-lockfile - --filter . - --filter "@tanstack/router-utils..." - --filter "@tanstack/router-generator..." - --filter "@tanstack/router-plugin..." - --filter "@tanstack/start-plugin-core..." - --filter "tanstack-react-start-e2e-basic..." - - name: Unit tests - run: >- - pnpm nx run-many --targets=test:unit - --projects=@tanstack/router-utils,@tanstack/router-generator,@tanstack/router-plugin,@tanstack/start-plugin-core - --skip-nx-cache --outputStyle=static - - name: Production builds - run: >- - pnpm nx run-many --targets=build:vite:ssr,build:rsbuild:ssr - --projects=tanstack-react-start-e2e-basic - --skip-nx-cache --outputStyle=static diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml index fde1100409..5e53b3c5bd 100644 --- a/.github/workflows/labeler.yml +++ b/.github/workflows/labeler.yml @@ -1,7 +1,7 @@ name: Labeler on: - pull_request: + pull_request_target: permissions: contents: read @@ -9,12 +9,10 @@ permissions: jobs: labeler: - # Fork PRs have a read-only GITHUB_TOKEN, so they cannot update labels. - if: ${{ github.event.pull_request.head.repo.full_name == github.repository }} runs-on: ubuntu-latest steps: - name: Labeller - uses: actions/labeler@f27b608878404679385c85cfa523b85ccb86e213 # v6.1.0 + uses: actions/labeler@v6.0.1 with: repo-token: ${{ secrets.GITHUB_TOKEN }} configuration-path: labeler-config.yml diff --git a/.github/workflows/notify-playbooks.yml b/.github/workflows/notify-playbooks.yml new file mode 100644 index 0000000000..5e583930e7 --- /dev/null +++ b/.github/workflows/notify-playbooks.yml @@ -0,0 +1,54 @@ +# notify-intent.yml — Drop this into your library repo's .github/workflows/ +# +# Fires a repository_dispatch event to TanStack/intent whenever docs or +# source files change on merge to main. This triggers the skill staleness +# check workflow in the intent repo. +# +# Requirements: +# - A fine-grained PAT with contents:write on TanStack/intent stored +# as the INTENT_NOTIFY_TOKEN repository secret. +# +# Template variables (replaced by `intent setup`): +# @tanstack/react-router — e.g. @tanstack/query +# docs/** — e.g. docs/** +# packages/*/src/** — e.g. packages/query-core/src/** +# +# Adapted for TanStack Router monorepo: watches all packages. + +name: Notify Intent + +on: + push: + branches: [main] + paths: + - 'docs/**' + - 'packages/*/src/**' + +jobs: + notify: + name: Notify TanStack Intent + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 2 + + - name: Collect changed files + id: changes + run: | + FILES=$(git diff --name-only HEAD~1 HEAD | jq -R -s -c 'split("\n") | map(select(length > 0))') + echo "files=$FILES" >> "$GITHUB_OUTPUT" + + - name: Dispatch to intent repo + uses: peter-evans/repository-dispatch@v3 + with: + token: ${{ secrets.INTENT_NOTIFY_TOKEN }} + repository: TanStack/intent + event-type: skill-check + client-payload: | + { + "package": "@tanstack/router", + "sha": "${{ github.sha }}", + "changed_files": ${{ steps.changes.outputs.files }} + } diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index ae19b4f0d2..1290bf96b9 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -10,16 +10,10 @@ 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: @@ -29,37 +23,32 @@ jobs: TSR_TMP_DIR: ./tmp steps: - name: Checkout - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@v6.0.2 with: fetch-depth: 0 - persist-credentials: false - - name: Start Nx Workers - run: npx nx-cloud start-workers + - name: Start Nx Agents + run: npx nx-cloud start-ci-run --distribute-on=".nx/workflows/dynamic-changesets.yaml" - name: Setup Tools - uses: TanStack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 # main + uses: TanStack/config/.github/setup@main - name: Get base and head commits for `nx affected` - uses: nrwl/nx-set-shas@afb73a62d26e41464e9254689e1fd6122ee683c1 # v5.0.1 + uses: nrwl/nx-set-shas@v4.4.0 with: main-branch-name: main - name: Run Checks run: pnpm run test:pr --parallel=3 - - name: Stop Nx Workers + - name: Stop Nx Agents if: ${{ always() }} - run: npx nx-cloud stop-all-workers + run: npx nx-cloud stop-all-agents preview: name: Preview runs-on: ubuntu-latest - permissions: - contents: read - pull-requests: write steps: - name: Checkout - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@v6.0.2 with: fetch-depth: 0 - persist-credentials: false - name: Setup Tools - uses: TanStack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 # main + uses: TanStack/config/.github/setup@main - name: Build Packages run: pnpm run build:all - name: Publish Previews @@ -67,15 +56,10 @@ jobs: 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 + uses: actions/checkout@v6.0.2 - name: Setup Tools - uses: TanStack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 # main + uses: TanStack/config/.github/setup@main - name: Changeset Preview - uses: TanStack/config/.github/changeset-preview@e4b48f16568324f76f467aa4c2aac2f05db632c3 # main + uses: TanStack/config/.github/changeset-preview@main diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 115c3445e6..8f53614c97 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -20,21 +20,54 @@ permissions: jobs: release: name: Release + if: "!contains(github.event.head_commit.message, 'ci: changeset release')" runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@v6.0.2 with: fetch-depth: 0 - persist-credentials: true # changesets/action pushes Release PR commits + - name: Check for changesets + id: changesets + run: | + CHANGESET_FILES=$(ls .changeset/*.md 2>/dev/null | grep -v README.md || true) + if [ -z "$CHANGESET_FILES" ]; then + echo "has_changesets=false" >> "$GITHUB_OUTPUT" + else + echo "has_changesets=true" >> "$GITHUB_OUTPUT" + fi + - name: Start Nx Agents + if: steps.changesets.outputs.has_changesets == 'true' + run: npx nx-cloud start-ci-run --distribute-on=".nx/workflows/dynamic-changesets.yaml" - name: Setup Tools - uses: TanStack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 # main - - name: Run Build - run: pnpm run build:all + uses: TanStack/config/.github/setup@main + - name: Run Tests + if: steps.changesets.outputs.has_changesets == 'true' + run: pnpm run test:ci --parallel=3 + - name: Stop Nx Agents + if: ${{ always() && steps.changesets.outputs.has_changesets == 'true' }} + run: npx nx-cloud stop-all-agents - name: Enter Pre-Release Mode if: "contains(github.ref_name, '-pre') && !hashFiles('.changeset/pre.json')" run: pnpm changeset pre enter pre + - name: Version Packages + run: pnpm run changeset:version + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: Commit and Push Version Changes + id: commit + run: | + git config user.name "github-actions[bot]" + git config user.email "github-actions[bot]@users.noreply.github.com" + git add . + if git commit -m "ci: changeset release"; then + git push + echo "committed=true" >> "$GITHUB_OUTPUT" + fi + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - name: Determine dist-tag + if: steps.commit.outputs.committed == 'true' id: dist-tag run: | BRANCH="${GITHUB_REF_NAME}" @@ -45,19 +78,11 @@ jobs: 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: Publish Packages + if: steps.commit.outputs.committed == 'true' + run: pnpm run changeset:publish ${{ steps.dist-tag.outputs.tag && format('--tag {0}', steps.dist-tag.outputs.tag) }} - name: Create GitHub Release - if: steps.changesets.outputs.published == 'true' + if: steps.commit.outputs.committed == '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 }} diff --git a/.github/workflows/validate-skills.yml b/.github/workflows/validate-skills.yml new file mode 100644 index 0000000000..8f39716aa9 --- /dev/null +++ b/.github/workflows/validate-skills.yml @@ -0,0 +1,52 @@ +# validate-skills.yml — Drop this into your library repo's .github/workflows/ +# +# Validates skill files on PRs that touch the skills/ directory. +# Ensures frontmatter is correct, names match paths, and files stay under +# the 500-line limit. + +name: Validate Skills + +on: + pull_request: + paths: + - 'skills/**' + - '**/skills/**' + +jobs: + validate: + name: Validate skill files + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup Node + uses: actions/setup-node@v4 + with: + node-version: 20 + + - name: Install intent CLI + run: npm install -g @tanstack/intent + + - name: Find and validate skills + run: | + # Find all directories containing SKILL.md files + SKILLS_DIR="" + if [ -d "skills" ]; then + SKILLS_DIR="skills" + elif [ -d "packages" ]; then + # Monorepo — find skills/ under packages + for dir in packages/*/skills; do + if [ -d "$dir" ]; then + echo "Validating $dir..." + intent validate "$dir" + fi + done + exit 0 + fi + + if [ -n "$SKILLS_DIR" ]; then + intent validate "$SKILLS_DIR" + else + echo "No skills/ directory found — skipping validation." + fi diff --git a/.github/workflows/zizmor.yml b/.github/workflows/zizmor.yml deleted file mode 100644 index 55afe41cc7..0000000000 --- a/.github/workflows/zizmor.yml +++ /dev/null @@ -1,25 +0,0 @@ -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 70028b2860..982044b29b 100644 --- a/.gitignore +++ b/.gitignore @@ -24,7 +24,7 @@ coverage packages/router-generator/tests/**/*.gen.ts packages/router-generator/tests/**/*.gen.js **/port*.txt -**/test-results/** +**/test-results/ # Playwright artifacts **/playwright-report/ @@ -59,14 +59,10 @@ 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 @@ -88,9 +84,3 @@ 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 63f87c20ef..b404027604 100644 --- a/.nvmrc +++ b/.nvmrc @@ -1 +1 @@ -26.12.1 +24.8.0 diff --git a/.nx/ci-config.yaml b/.nx/ci-config.yaml deleted file mode 100644 index 2f0783feb4..0000000000 --- a/.nx/ci-config.yaml +++ /dev/null @@ -1,5 +0,0 @@ -dte: - distribute-on: - small-changeset: 6 linux-medium-js - medium-changeset: 12 linux-medium-js - large-changeset: 18 linux-medium-js diff --git a/.nx/workflows/dynamic-changesets.yaml b/.nx/workflows/dynamic-changesets.yaml new file mode 100644 index 0000000000..d3536f3ba7 --- /dev/null +++ b/.nx/workflows/dynamic-changesets.yaml @@ -0,0 +1,4 @@ +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 deleted file mode 100644 index b3ed223621..0000000000 --- a/.nx/workflows/ultracache-config.yaml +++ /dev/null @@ -1,124 +0,0 @@ -ignore-reads: - - e2e/.gitignore - - '**/src/routeTree.gen.ts' -ignore-writes: - - '**/src/routeTree.gen.ts' -task-exclusions: - - target: test:build - ignore-reads: - - LICENSE - # HMR tests edit these inputs in place and restore their original contents. - # Keep them out of cached outputs so cache replay never overwrites source. - - project: tanstack-react-start-e2e-deferred-hydration - target: test:e2e - ignore-writes: - - e2e/react-start/deferred-hydration/src/routes/components.tsx - - project: tanstack-react-start-e2e-hmr - target: test:e2e - ignore-writes: &hmr-source-writes - - e2e/react-start/hmr/src/components/AliasedRouteImportChildPanel.tsx - - e2e/react-start/hmr/src/components/AliasedRouteImportParentPanel.tsx - - e2e/react-start/hmr/src/hmr/server-fn-hmr-factory.ts - - e2e/react-start/hmr/src/routes/__root.tsx - - e2e/react-start/hmr/src/routes/child.tsx - - e2e/react-start/hmr/src/routes/component-hmr-inline-error-split.tsx - - e2e/react-start/hmr/src/routes/component-hmr-inline-nosplit.tsx - - e2e/react-start/hmr/src/routes/component-hmr-inline-split.tsx - - e2e/react-start/hmr/src/routes/component-hmr-lowercase-named-split.tsx - - e2e/react-start/hmr/src/routes/component-hmr-named-error-split.tsx - - e2e/react-start/hmr/src/routes/component-hmr-named-nosplit.tsx - - e2e/react-start/hmr/src/routes/component-hmr-named-split.tsx - - e2e/react-start/hmr/src/routes/index.tsx - - e2e/react-start/hmr/src/routes/inputs.tsx - - project: tanstack-react-start-e2e-hmr - target: test:e2e--vite-ssr - ignore-writes: *hmr-source-writes - - project: tanstack-react-start-e2e-hmr - target: test:e2e--vite-ssr--bundled-dev - ignore-writes: *hmr-source-writes - - project: tanstack-react-start-e2e-hmr - target: test:e2e--rsbuild-ssr - ignore-writes: *hmr-source-writes - - project: tanstack-react-start-e2e-rsbuild - target: test:e2e--rsbuild-ssr - ignore-writes: - - e2e/react-start/rsbuild/src/routes/index.tsx - - project: tanstack-react-start-e2e-server-functions - target: test:e2e - ignore-writes: - - e2e/react-start/server-functions/src/routes/consistent.tsx - # Scaffolding tests deliberately populate tracked empty route fixtures. - - project: '@tanstack/router-generator' - target: test:unit - ignore-writes: - - packages/router-generator/tests/generator/custom-scaffolding/routes/__root.tsx - - packages/router-generator/tests/generator/custom-scaffolding/routes/api/bar.tsx - - packages/router-generator/tests/generator/custom-scaffolding/routes/foo.lazy.tsx - - packages/router-generator/tests/generator/custom-scaffolding/routes/index.tsx - # These reads are of scratch files created by the same test invocation. - - project: tanstack-solid-start-e2e-basic-auth - target: test:e2e - ignore-reads: - - e2e/solid-start/basic-auth/.tmp/dev.db - - project: tanstack-vue-start-e2e-basic-auth - target: test:e2e - ignore-reads: - - e2e/vue-start/basic-auth/.tmp/dev.db - - project: '@tanstack/router-generator' - target: test:unit - ignore-reads: - - packages/router-generator/tests/generator/file-modification/routes/[(]test[)]/initiallyEmpty.tsx - - packages/router-generator/tests/generator/file-modification/routes/[(]test[)]/initiallyEmpty.lazy.tsx - # Mutable counters are scratch state, not artifacts to replay from cache. - - project: tanstack-react-start-e2e-basic-tsr-config - target: test:e2e - ignore-reads: - - e2e/react-start/basic-tsr-config/count.txt - ignore-writes: - - e2e/react-start/basic-tsr-config/count.txt - - project: tanstack-solid-start-e2e-basic-tsr-config - target: test:e2e - ignore-reads: - - e2e/solid-start/basic-tsr-config/count.txt - ignore-writes: - - e2e/solid-start/basic-tsr-config/count.txt - - project: tanstack-vue-start-e2e-basic-tsr-config - target: test:e2e - ignore-reads: - - e2e/vue-start/basic-tsr-config/count.txt - ignore-writes: - - e2e/vue-start/basic-tsr-config/count.txt - # Paraglide downloads compiler plugins from the URLs in settings.json. - # Ignore warm-cache reads; the settings remain inputs and cache files outputs. - - project: tanstack-react-start-e2e-i18n-paraglide - target: build - ignore-reads: - - e2e/react-start/i18n-paraglide/project.inlang/cache/plugins/* - - project: tanstack-router-e2e-react-i18n-paraglide - target: build - ignore-reads: - - e2e/react-router/i18n-paraglide/project.inlang/cache/plugins/* - - project: tanstack-react-start-e2e-i18n-paraglide - target: test:e2e - ignore-reads: - - e2e/react-start/i18n-paraglide/project.inlang/cache/plugins/* - - project: tanstack-router-e2e-react-i18n-paraglide - target: test:e2e - ignore-reads: - - e2e/react-router/i18n-paraglide/project.inlang/cache/plugins/* - - project: tanstack-router-i18n-paraglide - target: build - ignore-reads: - - examples/react/i18n-paraglide/project.inlang/cache/plugins/* - - project: tanstack-start-i18n-paraglide - target: build - ignore-reads: - - examples/react/start-i18n-paraglide/project.inlang/cache/plugins/* - - project: tanstack-router-solid-i18n-paraglide - target: build - ignore-reads: - - examples/solid/i18n-paraglide/project.inlang/cache/plugins/* - - project: tanstack-solid-start-i18n-paraglide - target: build - ignore-reads: - - examples/solid/start-i18n-paraglide/project.inlang/cache/plugins/* diff --git a/.prettierignore b/.prettierignore index de501452ad..f3c4cd0f97 100644 --- a/.prettierignore +++ b/.prettierignore @@ -16,8 +16,4 @@ 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 +packages/router-plugin/tests/**/test-files/** \ No newline at end of file diff --git a/AGENTS.md b/AGENTS.md index f47b5103e1..6ff30deb95 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,41 +1,176 @@ # AGENTS.md -## Scope +## Project overview -- 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 is a type-safe router with built-in caching and URL state management for React and Solid applications. This monorepo contains two main products: -## Work and validation +- **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 -- 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. +## Setup commands -```sh -CI=1 NX_DAEMON=false pnpm nx run-many -p -t --skipRemoteCache -``` +- 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` -- 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`. +## Code style -## Runtime rules +- 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:*`) -- 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. +## Dev environment tips -## Performance and final bundle pass +- This is a pnpm workspace monorepo with packages organized by functionality +- Nx provides caching, affected testing, targeting, and parallel execution for efficiency +- Use `pnpm nx show projects` to list all available packages +- Target specific packages: `pnpm nx run @tanstack/react-router:test:unit` +- Target multiple packages: `pnpm nx run-many --target=test:eslint --projects=@tanstack/history,@tanstack/router-core` +- Run affected tests only: `pnpm nx affected --target=test:unit` +- Exclude patterns: `pnpm nx run-many --target=test:unit --exclude="examples/**,e2e/**"` +- Navigate to examples and run `pnpm dev` to test changes: `cd examples/react/basic && pnpm dev` +- **Granular unit testing through Nx (recommended):** + - Specific files: `pnpm nx run @tanstack/react-router:test:unit -- tests/link.test.tsx tests/Scripts.test.tsx` + - Test patterns: `pnpm nx run @tanstack/react-router:test:unit -- tests/ClientOnly.test.tsx -t "should render fallback"` + - Name patterns: `pnpm nx run @tanstack/react-router:test:unit -- -t "navigation"` (all tests with "navigation" in name) + - Exclude patterns: `pnpm nx run @tanstack/react-router:test:unit -- --exclude="**/*link*" tests/` + - List tests: `pnpm nx run @tanstack/react-router:test:unit -- list tests/link.test.tsx` (or `-- list` for all) +- **Available test targets per package:** `test:unit`, `test:types`, `test:eslint`, `test:build`, `test:perf`, `build` +- **Testing strategy:** Package level (nx) → File-level args via nx → Test-level args (`-t`) via nx → Pattern-level args (`--exclude`) via nx +- **Agent execution guardrails (important):** + - Always prefer `pnpm nx ...` over `npx nx ...`. + - Prefer Nx targets over direct test runners so task dependencies (including required builds) remain in the graph. + - In sandbox, run Nx with `CI=1 NX_DAEMON=false pnpm nx run : --outputStyle=stream --skipRemoteCache` + - Run only one Nx command at a time. + - If an Nx command shows no output for ~20 seconds, stop, run `pnpm nx reset` once, and retry once. + - Do not loop retries indefinitely. If it still hangs or sandbox blocks graph/daemon behavior, request escalation immediately. -- 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. +## Testing instructions + +- **Critical**: Always run unit and type tests during development - do not proceed if they fail +- **Test types:** `pnpm test:unit`, `pnpm test:types`, `pnpm test:eslint`, `pnpm test:e2e`, `pnpm test:build` +- **Full CI suite:** `pnpm test:ci` +- **Fix formatting:** `pnpm format` +- **Efficient targeted testing workflow:** + 1. **Affected only:** `pnpm nx affected --target=test:unit` (compares to main branch) + 2. **Specific packages:** `pnpm nx run @tanstack/react-router:test:unit` + 3. **Specific files:** `pnpm nx run @tanstack/react-router:test:unit -- tests/link.test.tsx` + 4. **Specific patterns:** `pnpm nx run @tanstack/react-router:test:unit -- tests/link.test.tsx -t "preloading"` +- **Pro tips:** + - Use `pnpm nx run @tanstack/react-router:test:unit -- list` to explore available tests before running + - Use `-t "pattern"` to focus on specific functionality during development + - Use `--exclude` patterns to skip unrelated tests + - Keep all test filtering arguments behind `pnpm nx run ... -- ...` for maximum precision while preserving task dependencies +- **Example workflow:** `pnpm nx run @tanstack/react-router:test:unit` → `pnpm nx run @tanstack/react-router:test:unit -- tests/link.test.tsx` → `pnpm nx run @tanstack/react-router:test:unit -- tests/link.test.tsx -t "preloading"` + +## PR instructions + +- Always run `pnpm test:eslint`, `pnpm test:types`, and `pnpm test:unit` before committing +- Test changes in relevant example apps: `cd examples/react/basic && pnpm dev` +- Update corresponding documentation in `docs/` directory when adding features +- Add or update tests for any code changes +- Use internal docs links relative to `docs/` folder (e.g., `./guide/data-loading`) + +## Package structure + +**Core packages:** + +- `packages/router-core/` - Framework-agnostic core router logic +- `packages/react-router/`, `packages/solid-router/` - React/Solid bindings and components +- `packages/history/` - Browser history management + +**Tooling:** + +- `packages/router-cli/` - CLI tools for code generation +- `packages/router-generator/` - Route generation utilities +- `packages/router-plugin/` - Universal bundler plugins (Vite, Webpack, ESBuild, Rspack) +- `packages/virtual-file-routes/` - Virtual file routing system + +**Developer experience:** + +- `packages/router-devtools/`, `packages/*-router-devtools/` - Development tools +- `packages/eslint-plugin-router/` - ESLint rules for router + +**Validation adapters:** + +- `packages/zod-adapter/`, `packages/valibot-adapter/`, `packages/arktype-adapter/` + +**Start framework:** + +- `packages/*-start/`, `packages/start-*/` - Full-stack framework packages + +**Examples & testing:** + +- `examples/react/`, `examples/solid/` - Example applications (test changes here) +- `e2e/` - End-to-end tests (requires Playwright) +- `docs/router/`, `docs/start/` - Documentation with React/Solid subdirectories + +**Dependencies:** Uses workspace protocol (`workspace:*`) - core → framework → start packages + +## Common development tasks + +**Adding new routes:** + +- Use file-based routing in `src/routes/` directories +- Or use code-based routing with route definitions +- Run route generation with CLI tools + +**Testing changes:** + +- Build packages: `pnpm build` or `pnpm dev` (watch mode) +- Run example apps to test functionality +- Use devtools for debugging router state + +**Documentation updates:** + +- Update relevant docs in `docs/` directory +- Ensure examples reflect documentation changes +- Test documentation links and references +- Use relative links to `docs/` folder format + +## Framework-specific notes + +**React:** + +- Uses React Router components and hooks +- Supports React Server Components (RSC) +- Examples include React Query integration +- Package: `@tanstack/react-router` + +**Solid:** + +- Uses Solid Router components and primitives +- Supports Solid Start for full-stack applications +- Examples include Solid Query integration +- Package: `@tanstack/solid-router` + +## Environment requirements + +- **Node.js** - Required for development +- **pnpm** - Package manager (required for workspace features) +- **Playwright** - Required for e2e tests (`pnpm exec playwright install`) + +## Key architecture patterns + +- **Type Safety**: Extensive TypeScript for type-safe routing +- **Framework Agnostic**: Core logic separated from framework bindings +- **Plugin Architecture**: Universal bundler plugins using unplugin +- **File-based Routing**: Support for both code-based and file-based routing +- **Search Params**: First-class support for type-safe search parameters + +## Development workflow + +1. **Setup**: `pnpm install` and `pnpm exec playwright install` +2. **Build**: `pnpm build:all` or `pnpm dev` for watch mode +3. **Test**: Make changes and run relevant tests (use nx for targeted testing) +4. **Examples**: Navigate to examples and run `pnpm dev` to test changes +5. **Quality**: Run `pnpm test:eslint`, `pnpm test:types`, `pnpm test:unit` before committing + +## References + +- **Documentation**: https://tanstack.com/router +- **GitHub**: https://github.com/TanStack/router +- **Discord Community**: https://discord.com/invite/WrRKjPJ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4b6e808af1..c28d01241b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,95 +1,30 @@ -# Contributing to TanStack Router +# Contributing -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: +- 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. > [!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`. @@ -118,7 +53,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!) @@ -140,21 +75,6 @@ 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! -## AI-assisted contributions +You can see the whole process in the screen capture below: - - -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. +https://github.com/fulopkovacs/form/assets/43729152/9d35a3c3-8153-4e74-9cb2-af275f7a269b diff --git a/README.md b/README.md index 736715b12a..8dd7deef41 100644 --- a/README.md +++ b/README.md @@ -4,20 +4,10 @@ - - - - TanStack Router - + ## TanStack Router @@ -33,20 +23,10 @@ A modern router designed for type safety, data‑driven navigation, and seamless - - - - TanStack Start - + ## TanStack Start diff --git a/_artifacts/domain_map.yaml b/_artifacts/domain_map.yaml index 0b2672f0c6..4b5d6f8386 100644 --- a/_artifacts/domain_map.yaml +++ b/_artifacts/domain_map.yaml @@ -147,15 +147,13 @@ skills: context types to not flow into loader. wrong_pattern: | createFileRoute('/posts')({ - loader: ({ context }) => - context.queryClient.query({ ...postsQuery, staleTime: 'static' }), + loader: ({ context }) => context.queryClient.ensureQueryData(postsQuery), beforeLoad: ({ context }) => ({ queryClient: context.queryClient }), }) correct_pattern: | createFileRoute('/posts')({ beforeLoad: ({ context }) => ({ queryClient: context.queryClient }), - loader: ({ context }) => - context.queryClient.query({ ...postsQuery, staleTime: 'static' }), + loader: ({ context }) => context.queryClient.ensureQueryData(postsQuery), }) source: 'docs/router/eslint/create-route-property-order.md' priority: HIGH @@ -538,7 +536,7 @@ skills: - '@tanstack/react-router-ssr-query' covers: - External cache coordination pattern - - "queryClient.query with staleTime: 'static' in loader" + - queryClient.ensureQueryData in loader - useSuspenseQuery in components - setupRouterSsrQueryIntegration - defaultPreloadStaleTime @@ -581,11 +579,11 @@ skills: priority: HIGH status: active - - mistake: 'Awaiting a fire-and-forget query in loader blocks rendering' + - mistake: 'Awaiting prefetchQuery in loader blocks rendering' mechanism: >- - For streaming/deferred patterns, start a query without awaiting - it and handle failures with catch(noop) — it starts fetching on - the server and streams without blocking. Awaiting defeats the purpose. + For streaming/deferred patterns, prefetchQuery should NOT + be awaited in the loader — it starts fetching on server + and streams without blocking. Awaiting defeats the purpose. source: 'docs/router/integrations/query.md' priority: MEDIUM status: active diff --git a/_artifacts/skill_spec.md b/_artifacts/skill_spec.md index 7eb9554a42..35c811a3bc 100644 --- a/_artifacts/skill_spec.md +++ b/_artifacts/skill_spec.md @@ -67,7 +67,7 @@ TanStack Router is a type-safe router for React and Solid applications with buil | # | Mistake | Priority | Source | Cross-skill? | | --- | --------------------------------------------- | -------- | ----------------------------- | ------------ | -| 1 | Interpolating path params into `to` string | CRITICAL | docs/guide/navigation | navigation | +| 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 | — | @@ -83,11 +83,11 @@ TanStack Router is a type-safe router for React and Solid applications with buil ### external-data-loading (3 failure modes) -| # | Mistake | Priority | Source | Cross-skill? | -| --- | ----------------------------------------------------------- | -------- | -------------------------------- | ------------ | -| 1 | Not setting defaultPreloadStaleTime to 0 | HIGH | docs/guide/external-data-loading | — | -| 2 | Creating QueryClient outside createRouter for SSR | HIGH | docs/guide/external-data-loading | — | -| 3 | Awaiting a fire-and-forget query in loader blocks rendering | MEDIUM | docs/integrations/query | — | +| # | Mistake | Priority | Source | Cross-skill? | +| --- | ------------------------------------------------- | -------- | -------------------------------- | ------------ | +| 1 | Not setting defaultPreloadStaleTime to 0 | HIGH | docs/guide/external-data-loading | — | +| 2 | Creating QueryClient outside createRouter for SSR | HIGH | docs/guide/external-data-loading | — | +| 3 | Awaiting prefetchQuery in loader blocks rendering | MEDIUM | docs/integrations/query | — | ### auth-and-guards (3 failure modes) diff --git a/_artifacts/skill_tree.yaml b/_artifacts/skill_tree.yaml index 6f7c4c8742..b5ce76f547 100644 --- a/_artifacts/skill_tree.yaml +++ b/_artifacts/skill_tree.yaml @@ -135,6 +135,7 @@ skills: for auth state. requires: - 'router-core' + - 'router-core/data-loading' sources: - 'TanStack/router:docs/router/guide/authenticated-routes.md' - 'TanStack/router:docs/router/how-to/setup-authentication.md' @@ -246,7 +247,7 @@ skills: package: 'packages/react-router' description: >- Integrating TanStack Router with TanStack Query: queryClient - in router context, static queries and fire-and-forget queries in loaders, + in router context, ensureQueryData/prefetchQuery in loaders, useSuspenseQuery in components, defaultPreloadStaleTime: 0, setupRouterSsrQueryIntegration for SSR dehydration/hydration and streaming, per-request QueryClient isolation. diff --git a/_artifacts/start_domain_map.yaml b/_artifacts/start_domain_map.yaml index a557901075..b5e84d4dfb 100644 --- a/_artifacts/start_domain_map.yaml +++ b/_artifacts/start_domain_map.yaml @@ -134,7 +134,7 @@ skills: - '@tanstack/start-server-core' covers: - createServerFn (GET/POST) - - validator (Zod or function) + - inputValidator (Zod or function) - useServerFn hook - Server context utilities (getRequest, getRequestHeader, setResponseHeader, setResponseStatus) - Error handling (throw errors, redirect, notFound) @@ -229,7 +229,7 @@ skills: - Middleware factories - Fetch override precedence - Header merging - - Method order enforcement (middleware → validator → client → server) + - Method order enforcement (middleware → inputValidator → client → server) tasks: - 'Add authentication middleware' - 'Pass context through middleware chain' @@ -247,7 +247,7 @@ skills: - mistake: 'Wrong middleware method order' mechanism: >- - TypeScript enforces method order: middleware → validator + TypeScript enforces method order: middleware → inputValidator → client → server. Wrong order causes type errors and runtime failures. source: 'docs/start/framework/react/guide/middleware.md' diff --git a/_artifacts/start_skill_tree.yaml b/_artifacts/start_skill_tree.yaml index 4d221068fd..cf743b067c 100644 --- a/_artifacts/start_skill_tree.yaml +++ b/_artifacts/start_skill_tree.yaml @@ -37,7 +37,7 @@ skills: path: 'skills/start-core/server-functions/SKILL.md' package: 'packages/start-client-core' description: >- - createServerFn (GET/POST), validator (Zod or function), + createServerFn (GET/POST), inputValidator (Zod or function), useServerFn hook, server context utilities (getRequest, getRequestHeader, setResponseHeader, setResponseStatus), error handling (throw errors, redirect, notFound), streaming diff --git a/benchmarks/AGENTS.md b/benchmarks/AGENTS.md deleted file mode 100644 index 9d56a2411a..0000000000 --- a/benchmarks/AGENTS.md +++ /dev/null @@ -1,15 +0,0 @@ -# Benchmarks - -Read the relevant README before running benchmarks. Compare baseline and candidate with the same workload and production builds; add a focused case when existing scenarios miss the changed mechanism. Keep workloads and benchmark names stable for historical comparisons. - -| Changed behavior | Guide | Nx project | -| ------------------------------------------ | ---------------------------------- | -------------------------------------------------------- | -| Standalone Router navigation/rendering CPU | [client-nav](client-nav/README.md) | `@benchmarks/client-nav` | -| Start request/SSR CPU | [ssr](ssr/README.md) | `@benchmarks/ssr` | -| Client/server retention and allocations | [memory](memory/README.md) | `@benchmarks/memory-client`, `@benchmarks/memory-server` | - -Use `test:perf:` through Nx. Plain memory runs only smoke-test; memory metrics require CodSpeed. Client navigation benchmarks do not cover Start hydration or client server-function calls. - -Run `vitest bench` directly only with `--mode benchmark`, as the Nx targets do. Vitest 5 otherwise uses Vite's `test` mode, where vite-plugin-solid injects a jest-dom setup file that benchmark packages cannot resolve. - -For bundle-size work, follow the full optimization skill required by the root guide. Full API fixtures are maintained manually: when public hooks/components change, update matching `bundle-size/scenarios/*-full/src/routes/__root.tsx` fixtures. Save baseline results separately because each run overwrites `bundle-size/results/current.json`; report final gzip deltas and explain remaining growth. diff --git a/benchmarks/README.md b/benchmarks/README.md deleted file mode 100644 index 94d2f31802..0000000000 --- a/benchmarks/README.md +++ /dev/null @@ -1,88 +0,0 @@ -# CPU simulation benchmarks - -`client-nav` measures navigation, mounting, and React/Solid hydration in -Node/jsdom; `ssr` measures server requests. -Both suites run through the CodSpeed Vitest integration in CPU simulation mode. - -## Worker runtime - -Every CPU benchmark project includes `cpuSimulationExecArgv()` from -[`cpu-simulation.ts`](./cpu-simulation.ts). It augments CodSpeed's worker flags -only during CPU simulation, including the legacy `instrumentation` mode. - -The pinned CodSpeed integration supplies `--no-opt`. In Node 24 this is an alias -for `--no-turbofan`, so Maglev can still optimize and inline hot functions. The -additional `--no-maglev` keeps the optimizing compiler out of the simulation. -`--always-sparkplug` compiles baseline code on first use, so warmup does not leave -functions approaching a later tier-up or batch-compilation threshold. The worker -regression test checks that even a once-called function receives baseline code. -The integration also omits the old `--no-scavenge-task` flag on Node 20 and -newer, where V8 renamed it to `--no-minor-gc-task`. Supplying the renamed flag -keeps minor GC tied to allocation pressure instead of scheduled foreground -tasks. Both flags follow the fixes in -[CodSpeed's Node 24 support](https://github.com/CodSpeedHQ/codspeed-node/commit/e3224e7872). - -`--initial-old-space-size=512` fixes the initial/minimum old-generation -allocation budget at 512 MiB. Removing only this override after worker isolation -left two Vue SSR scenarios with same-commit spreads above 2% in five full-suite -repetitions. The paired default-heap comparison with stock incremental-marking -tasks also exceeded 2%. Runtime comparisons and tested alternatives are recorded in -[PR #8248](https://github.com/TanStack/router/pull/8248). - -This is a GC-policy tradeoff. Minor collections and allocation work remain -measured, and CodSpeed still explicitly collects before measurement. However, -V8 can skip automatic full collections below this old-generation budget, so the -benchmark can omit some eventual full-GC CPU cost from increased object -retention. Repeatability does not establish representative production GC -frequency. The flag does not preallocate 512 MiB; the existing 4096 MiB maximum -remains. See [V8's initial/minimum heap configuration](https://github.com/nodejs/node/blob/v24.8.0/deps/v8/src/heap/heap.cc#L5071). - -The configuration preserves CodSpeed's incremental-marking task settings; the -additional `--no-incremental-marking-task` from the initial stabilization proposal -has been removed. - -The flags are intentionally absent from ordinary Vitest timing and walltime runs. - -Changing simulation compiler settings changes the measurement baseline. Compare -repeatability within each configuration before interpreting performance changes -between configurations as router improvements or regressions. - -## Worker isolation - -Keep one SSR workload in each `speed*.bench.ts` file. These projects explicitly -enable Vitest isolation; CodSpeed uses the forks pool, so every file receives a -fresh worker. Multiple workloads in one file share the worker's runtime state, -even though CodSpeed collects before each measurement. Later control cases -remained noisy after the runtime flag corrections. Running the React plain -dehydration and linked-CSS controls alone reduced their observed three-run spreads -to 0.09% and 0.02% respectively. - -Variant files keep their workload names, request counts, concurrency, payloads -and assertions. CodSpeed includes the file path in a benchmark's identity, so -moved variants start a new history. The first workload keeps `speed.bench.ts`; -the additional variants have descriptive file names alongside it. Type-check -includes cover all of these files. - -## Streaming workload - -Deferred payloads in the SSR streaming scenario resolve after two task turns on -Node. A real 1 ms timer lets elapsed host time decide which concurrent requests -resolve together. Counted turns preserve the initial loading render and deferred -payloads; the existing HTML assertions check both. These benchmarks execute in -Node and use `setImmediate` directly. - -## Repeatability checks - -Dispatch the existing `Benchmarks` workflow against an unchanged branch: - -```sh -gh workflow run benchmarks.yml --ref -``` - -Wait for each workflow run to finish before dispatching the next repetition at -the same commit. The workflow also runs memory benchmarks; exclude those results -when assessing CPU repeatability. Check that every repetition has all expected -CPU results (currently 134), rather than inherited results from an earlier run. -Compare each benchmark's minimum and maximum across repetitions; keep input data, -navigation/request counts, builds, dependencies and Node version fixed when -testing runtime configuration changes. diff --git a/benchmarks/bundle-size/.gitignore b/benchmarks/bundle-size/.gitignore index bd05a98cee..dc7703a1be 100644 --- a/benchmarks/bundle-size/.gitignore +++ b/benchmarks/bundle-size/.gitignore @@ -1,11 +1,8 @@ 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 index 2185d6b43f..1ac80b5870 100644 --- a/benchmarks/bundle-size/README.md +++ b/benchmarks/bundle-size/README.md @@ -8,147 +8,37 @@ This workspace contains deterministic bundle-size fixtures for: - `@tanstack/react-start` - `@tanstack/solid-start` -Each package has `minimal` and `full` scenarios: +Each package has two 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`. +- Start scenarios use `@tanstack/-start/plugin/vite` with router code-splitting enabled. - 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. +- Metrics are measured from initial-load JS graph only and reported as raw/gzip/brotli bytes. +- Gzip 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 +pnpm nx run @benchmarks/bundle-size:build ``` 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 + - current gzip values + - baseline delta - inline sparkline trend - Pushes to `main` publish historical chart data to GitHub Pages via `benchmark-action/github-action-benchmark`. @@ -163,10 +53,6 @@ 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 index ca34cd6cd7..32f9af558b 100644 --- a/benchmarks/bundle-size/package.json +++ b/benchmarks/bundle-size/package.json @@ -3,82 +3,29 @@ "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" - ] - } - } + "build": "node ../../scripts/benchmarks/bundle-size/measure.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", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", "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" + "typescript": "^5.7.2", + "vite": "^8.0.0", + "vite-plugin-solid": "3.0.0-next.3" } } 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 index aeea465e04..76fb363538 100644 --- a/benchmarks/bundle-size/scenarios/react-router-full/src/routes/index.tsx +++ b/benchmarks/bundle-size/scenarios/react-router-full/src/routes/index.tsx @@ -1,18 +1,6 @@ -import { - createFileRoute, - retainSearchParams, - stripSearchParams, -} from '@tanstack/react-router' - -const defaultSearch = { page: 1 } +import { createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/')({ - search: { - middlewares: [ - retainSearchParams>(['persist']), - stripSearchParams(defaultSearch), - ], - }, component: IndexComponent, }) 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 deleted file mode 100644 index 9d87d8748b..0000000000 --- a/benchmarks/bundle-size/scenarios/react-start-deferred-hydration/src/router.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index ff1da4c304..0000000000 --- a/benchmarks/bundle-size/scenarios/react-start-deferred-hydration/src/routes/__root.tsx +++ /dev/null @@ -1,24 +0,0 @@ -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 deleted file mode 100644 index a462508abd..0000000000 --- a/benchmarks/bundle-size/scenarios/react-start-deferred-hydration/src/routes/index.tsx +++ /dev/null @@ -1,15 +0,0 @@ -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 deleted file mode 100644 index d4e4cd980d..0000000000 --- a/benchmarks/bundle-size/scenarios/react-start-deferred-hydration/vite.config.ts +++ /dev/null @@ -1,7 +0,0 @@ -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 deleted file mode 100644 index 349e11bec1..0000000000 --- a/benchmarks/bundle-size/scenarios/react-start-full/rsbuild.config.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { defineConfig } from '@rsbuild/core' -import { pluginReact } from '@rsbuild/plugin-react' -import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild' - -const outDir = process.env.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-minimal/rsbuild.config.ts b/benchmarks/bundle-size/scenarios/react-start-minimal/rsbuild.config.ts deleted file mode 100644 index 7d27421d4d..0000000000 --- a/benchmarks/bundle-size/scenarios/react-start-minimal/rsbuild.config.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { defineConfig } from '@rsbuild/core' -import { pluginReact } from '@rsbuild/plugin-react' -import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild' - -const outDir = process.env.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-query-integration/src/router.tsx b/benchmarks/bundle-size/scenarios/react-start-query-integration/src/router.tsx deleted file mode 100644 index 93b95f3148..0000000000 --- a/benchmarks/bundle-size/scenarios/react-start-query-integration/src/router.tsx +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index ff1da4c304..0000000000 --- a/benchmarks/bundle-size/scenarios/react-start-query-integration/src/routes/__root.tsx +++ /dev/null @@ -1,24 +0,0 @@ -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 deleted file mode 100644 index 76fb363538..0000000000 --- a/benchmarks/bundle-size/scenarios/react-start-query-integration/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index d4e4cd980d..0000000000 --- a/benchmarks/bundle-size/scenarios/react-start-query-integration/vite.config.ts +++ /dev/null @@ -1,7 +0,0 @@ -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/src/main.tsx b/benchmarks/bundle-size/scenarios/solid-router-full/src/main.tsx index 505f79aee0..eaa48dd6c1 100644 --- a/benchmarks/bundle-size/scenarios/solid-router-full/src/main.tsx +++ b/benchmarks/bundle-size/scenarios/solid-router-full/src/main.tsx @@ -1,4 +1,4 @@ -import { render } from 'solid-js/web' +import { render } from '@solidjs/web' import { RouterProvider, createRouter } from '@tanstack/solid-router' import { routeTree } from './routeTree.gen' 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 index de52291cac..01d3b701ae 100644 --- a/benchmarks/bundle-size/scenarios/solid-router-full/src/routes/index.tsx +++ b/benchmarks/bundle-size/scenarios/solid-router-full/src/routes/index.tsx @@ -1,18 +1,6 @@ -import { - createFileRoute, - retainSearchParams, - stripSearchParams, -} from '@tanstack/solid-router' - -const defaultSearch = { page: 1 } +import { createFileRoute } from '@tanstack/solid-router' export const Route = createFileRoute('/')({ - search: { - middlewares: [ - retainSearchParams>(['persist']), - stripSearchParams(defaultSearch), - ], - }, component: IndexComponent, }) diff --git a/benchmarks/bundle-size/scenarios/solid-router-minimal/src/main.tsx b/benchmarks/bundle-size/scenarios/solid-router-minimal/src/main.tsx index 210120b3f1..f7c0b4bc7f 100644 --- a/benchmarks/bundle-size/scenarios/solid-router-minimal/src/main.tsx +++ b/benchmarks/bundle-size/scenarios/solid-router-minimal/src/main.tsx @@ -1,4 +1,4 @@ -import { render } from 'solid-js/web' +import { render } from '@solidjs/web' import { RouterProvider, createRouter } from '@tanstack/solid-router' import { routeTree } from './routeTree.gen' 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 deleted file mode 100644 index aa7ead6752..0000000000 --- a/benchmarks/bundle-size/scenarios/solid-start-deferred-hydration/src/router.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index e59de72236..0000000000 --- a/benchmarks/bundle-size/scenarios/solid-start-deferred-hydration/src/routes/__root.tsx +++ /dev/null @@ -1,24 +0,0 @@ -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 deleted file mode 100644 index 80362386b2..0000000000 --- a/benchmarks/bundle-size/scenarios/solid-start-deferred-hydration/src/routes/index.tsx +++ /dev/null @@ -1,15 +0,0 @@ -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 deleted file mode 100644 index 0bd21e64f4..0000000000 --- a/benchmarks/bundle-size/scenarios/solid-start-deferred-hydration/vite.config.ts +++ /dev/null @@ -1,7 +0,0 @@ -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/src/routes/__root.tsx b/benchmarks/bundle-size/scenarios/vue-router-full/src/routes/__root.tsx index 0ff40aebfc..d696063083 100644 --- a/benchmarks/bundle-size/scenarios/vue-router-full/src/routes/__root.tsx +++ b/benchmarks/bundle-size/scenarios/vue-router-full/src/routes/__root.tsx @@ -1,4 +1,3 @@ -import { defineComponent } from 'vue' import { Asset, Await, @@ -46,151 +45,143 @@ import { useTags, } from '@tanstack/vue-router' -const RootComponent = defineComponent({ - setup() { - const router = useRouter() - const [awaited] = useAwaited({ promise: Promise.resolve('ready') }) - const linkProps = useLinkProps({ to: '/' } as any) - const matchRoute = useMatchRoute() - const matches = useMatches() - const parentMatches = useParentMatches() - const childMatches = useChildMatches() - const match = useMatch({ strict: false, shouldThrow: false } as any) - const loaderDeps = useLoaderDeps({ strict: false } as any) - const loaderData = useLoaderData({ strict: false } as any) - const params = useParams({ strict: false } as any) - const search = useSearch({ strict: false } as any) - const routeContext = useRouteContext({ strict: false } as any) - const routerState = useRouterState({ - select: (state) => state.status, - } as any) - const location = useLocation() - const canGoBack = useCanGoBack() - const navigate = useNavigate() - const scrollEntry = useElementScrollRestoration({ id: 'root-scroll' }) - const tags = useTags() - - useBlocker({ - shouldBlockFn: () => false, - disabled: true, - withResolver: false, - }) - - const linkFactoryResult = linkOptions({ to: '/' } as any) - const routeMatchResult = matchRoute({ to: '/' } as any) - const SvgLink = createLink('svg') - - const hooksAndComponents = [ - useAwaited, - useLinkProps, - useMatchRoute, - useMatches, - useParentMatches, - useChildMatches, - useMatch, - useLoaderDeps, - useLoaderData, - useBlocker, - useNavigate, - useParams, - useSearch, - useRouteContext, - useRouter, - useRouterState, - useLocation, - useCanGoBack, - useElementScrollRestoration, - useTags, - Await, - CatchBoundary, - CatchNotFound, - ClientOnly, - DefaultGlobalNotFound, - ErrorComponent, - Link, - Match, - MatchRoute, - Matches, - Navigate, - Outlet, - RouterContextProvider, - ScrollRestoration, - Block, - ScriptOnce, - Asset, - HeadContent, - Scripts, - Body, - Html, - ] - - ;(globalThis as any).__TANSTACK_BUNDLE_SIZE_KEEP__ = { - hooksAndComponents, - } - - return () => { - void awaited - void linkFactoryResult - void matches.value - void parentMatches.value - void childMatches.value - void match.value - void loaderDeps.value - void loaderData.value - void params.value - void search.value - void routeContext.value - void routerState.value - void location.value - void canGoBack.value - void navigate - void scrollEntry - void tags() - void routeMatchResult.value - - return ( - <> - - {'window.__tsr_bundle_size = true'} - - home - - - - - {() => } - - }> - - - } - /> - false} disabled withResolver={false}> - {() => } - - }> - - - - - - - - -
-
hello world
-
- - ) - } - }, -}) - export const Route = createRootRoute({ component: RootComponent, }) + +function RootComponent() { + const router = useRouter() + const [awaited] = useAwaited({ promise: Promise.resolve('ready') }) + const linkProps = useLinkProps({ to: '/' } as any) + const matchRoute = useMatchRoute() + const matches = useMatches() + const parentMatches = useParentMatches() + const childMatches = useChildMatches() + const match = useMatch({ strict: false, shouldThrow: false } as any) + const loaderDeps = useLoaderDeps({ strict: false } as any) + const loaderData = useLoaderData({ strict: false } as any) + const params = useParams({ strict: false } as any) + const search = useSearch({ strict: false } as any) + const routeContext = useRouteContext({ strict: false } as any) + const routerState = useRouterState({ select: (state) => state.status } as any) + const location = useLocation() + const canGoBack = useCanGoBack() + const navigate = useNavigate() + const scrollEntry = useElementScrollRestoration({ id: 'root-scroll' }) + const tags = useTags() + + useBlocker({ + shouldBlockFn: () => false, + disabled: true, + withResolver: false, + }) + + const linkFactoryResult = linkOptions({ to: '/' } as any) + const routeMatchResult = matchRoute({ to: '/' } as any) + const SvgLink = createLink('svg') + + const hooksAndComponents = [ + useAwaited, + useLinkProps, + useMatchRoute, + useMatches, + useParentMatches, + useChildMatches, + useMatch, + useLoaderDeps, + useLoaderData, + useBlocker, + useNavigate, + useParams, + useSearch, + useRouteContext, + useRouter, + useRouterState, + useLocation, + useCanGoBack, + useElementScrollRestoration, + useTags, + Await, + CatchBoundary, + CatchNotFound, + ClientOnly, + DefaultGlobalNotFound, + ErrorComponent, + Link, + Match, + MatchRoute, + Matches, + Navigate, + Outlet, + RouterContextProvider, + ScrollRestoration, + Block, + ScriptOnce, + Asset, + HeadContent, + Scripts, + Body, + Html, + ] + + ;(globalThis as any).__TANSTACK_BUNDLE_SIZE_KEEP__ = { + hooksAndComponents, + } + + void awaited + void linkFactoryResult + void matches.value + void parentMatches.value + void childMatches.value + void match.value + void loaderDeps.value + void loaderData.value + void params.value + void search.value + void routeContext.value + void routerState.value + void location.value + void canGoBack.value + void navigate + void scrollEntry + void tags() + void routeMatchResult.value + + return ( + <> + + {'window.__tsr_bundle_size = true'} + + home + + + + {() => } + }> + + + } + /> + false} disabled withResolver={false}> + {() => } + + }> + + + + + + + + +
+
hello world
+
+ + ) +} diff --git a/benchmarks/bundle-size/scenarios/vue-router-full/src/routes/index.tsx b/benchmarks/bundle-size/scenarios/vue-router-full/src/routes/index.tsx index bf165a33b5..3899022bdd 100644 --- a/benchmarks/bundle-size/scenarios/vue-router-full/src/routes/index.tsx +++ b/benchmarks/bundle-size/scenarios/vue-router-full/src/routes/index.tsx @@ -1,18 +1,6 @@ -import { - createFileRoute, - retainSearchParams, - stripSearchParams, -} from '@tanstack/vue-router' - -const defaultSearch = { page: 1 } +import { createFileRoute } from '@tanstack/vue-router' export const Route = createFileRoute('/')({ - search: { - middlewares: [ - retainSearchParams>(['persist']), - stripSearchParams(defaultSearch), - ], - }, component: IndexComponent, }) diff --git a/benchmarks/bundle-size/scenarios/vue-start-full/src/router.tsx b/benchmarks/bundle-size/scenarios/vue-start-full/src/router.tsx deleted file mode 100644 index 9b893112b4..0000000000 --- a/benchmarks/bundle-size/scenarios/vue-start-full/src/router.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 8e8870a2ce..0000000000 --- a/benchmarks/bundle-size/scenarios/vue-start-full/src/routes/__root.tsx +++ /dev/null @@ -1,227 +0,0 @@ -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 deleted file mode 100644 index 3899022bdd..0000000000 --- a/benchmarks/bundle-size/scenarios/vue-start-full/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 3005d7504b..0000000000 --- a/benchmarks/bundle-size/scenarios/vue-start-full/vite.config.ts +++ /dev/null @@ -1,8 +0,0 @@ -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 deleted file mode 100644 index 9b893112b4..0000000000 --- a/benchmarks/bundle-size/scenarios/vue-start-minimal/src/router.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 49422aac38..0000000000 --- a/benchmarks/bundle-size/scenarios/vue-start-minimal/src/routes/__root.tsx +++ /dev/null @@ -1,26 +0,0 @@ -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 deleted file mode 100644 index 3899022bdd..0000000000 --- a/benchmarks/bundle-size/scenarios/vue-start-minimal/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 3005d7504b..0000000000 --- a/benchmarks/bundle-size/scenarios/vue-start-minimal/vite.config.ts +++ /dev/null @@ -1,8 +0,0 @@ -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/client-nav/README.md b/benchmarks/client-nav/README.md index ec34ecc0c1..44b58107e3 100644 --- a/benchmarks/client-nav/README.md +++ b/benchmarks/client-nav/README.md @@ -1,87 +1,16 @@ # Client Navigation Benchmarks -Cross-framework client-side CPU benchmarks for: +Cross-framework client-side navigation 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). +- `react/` - React benchmark + Vitest config +- `solid/` - Solid benchmark + Vitest config +- `vue/` - Vue benchmark + Vitest config ## Run @@ -91,7 +20,7 @@ Run all benchmarks through Nx so dependency builds are part of the graph: CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav:test:perf --outputStyle=stream --skipRemoteCache ``` -Run framework-specific benchmarks (baseline + all scenarios): +Run framework-specific benchmarks: ```bash CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav:test:perf:react --outputStyle=stream --skipRemoteCache @@ -99,209 +28,16 @@ CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav:test:perf:solid --output CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav:test:perf:vue --outputStyle=stream --skipRemoteCache ``` -Run a single scenario app manually (after building it through Nx): - -```bash -CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav--:build:client --outputStyle=stream --skipRemoteCache -cd benchmarks/client-nav && NODE_ENV=production vitest bench --mode benchmark --config ./scenarios///vite.config.ts -``` - Run framework-specific flame benchmarks (10 second loop, profiled with `@platformatic/flame`, forced to `NODE_ENV=production`): ```bash -# baseline CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav:test:flame:react --outputStyle=stream --skipRemoteCache CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav:test:flame:solid --outputStyle=stream --skipRemoteCache CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav:test:flame:vue --outputStyle=stream --skipRemoteCache -# scenarios -CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav--:test:flame --outputStyle=stream --skipRemoteCache ``` -Typecheck benchmark sources (baseline + scenarios): +Typecheck benchmark sources: ```bash CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav:test:types --outputStyle=stream --skipRemoteCache ``` - -## Hydration - -`scenarios/hydration/{react,solid}` provide the same initial-hydration -workload: 192 ordinary Links, eight hash-sensitive Links, and three matched -routes with three `beforeLoad` contexts and two loader results. The server URL -has no fragment; the client URL has `#details`, matching half of the hash-sensitive Links. - -```bash -CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav-hydration-react:test:perf --outputStyle=stream --skipRemoteCache -CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav-hydration-react:test:unit --outputStyle=stream --skipRemoteCache -CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav-hydration-react:test:types:client --outputStyle=stream --skipRemoteCache -``` - -Replace `react` with `solid` to run the other adapter. - -The build generates static HTML and its real Router SSR bootstrap scripts once -with `createRequestHandler` and the adapter's streaming renderer. Generation -fully consumes the response and runs outside the CodSpeed action. The measured -worker only reads these artifacts; it does not import a server renderer or start a server. - -Each invocation uses a fresh jsdom window and a fresh evaluation of the complete -production client bundle in that window's realm. HTML parsing, bundle evaluation, -and the initial document lifecycle finish in untimed setup. This resets module -state as well as the DOM, avoiding cached hydration promises and cross-realm -payload objects. The bundle and bootstrap scripts are compiled once, so this -measures a fresh application with warm code, not JavaScript download/parse cost. - -The timed region executes the serialized payload, creates the router and its -small code-based route tree, calls the public client `hydrate` API, and hydrates -the existing DOM with the framework's native renderer: - -- **React:** a separate completion component signals from its post-hydration - effect, after the same snapshot transition as hash-sensitive Links. The harness - awaits that signal and two idle React scheduler turns, then checks the expected - active links. The window's `performance.now()` is frozen, so React's - scheduler yields only to paint after commits, not after 5 ms of wall time, which CPU - instrumentation stretches by a runner-dependent factor. Each sample therefore - uses the same number of scheduler tasks. `Date.now()` is unchanged. A - 60-second watchdog fails a sample that never settles. -- **Solid:** execute the native hydration bootstrap and retain the server's - component/key hierarchy. Wait for mount, the router's rendered event, active-link - effects, and two idle turns. DOM identity assertions include every workload - element so template fallback cannot silently replace server nodes. - -Solid bounds settlement to 100 turns. Ending at the hydration call or the -first mount would miss post-hydration Link updates. -Timer turns use `setImmediate`; scrolling is a no-op -because this is CPU simulation rather than browser layout/paint measurement. - -Untimed assertions verify restored contexts and every loader row, zero client -`beforeLoad`/loader calls, expected hrefs/active state, original DOM-node identity, -working event handlers, and absence of hydration errors. Root unmount, pending -task cancellation, and window disposal also run outside measurement. Diagnostic -tests count Link renders or reactive evaluations and check they stop before the -measured region ends; counting is disabled in the timed workload. - -The bench's own `beforeEach`/`afterEach` hooks prepare and dispose every -sample outside timing, in both CodSpeed and ordinary Vitest runs. Per-phase -setup would let later iterations reuse an already hydrated document. The -hydration unit tests cover repeated fresh-state setup. - -Each scenario is included in its framework's aggregate build and CodSpeed run. -Land the benchmark independently to establish main's baseline before comparing a -hydration optimization. Regenerate each revision's artifacts with identical -fixture data and dependencies; do not pin an old hydration wire format forever. - -## Isolated route-tree construction - -`scenarios/route-tree-scale` measures navigation over an existing tree, not -construction. `scenarios/mount` includes construction but also rendering and -loading. To isolate initialization, use the core construction benchmark: - -```bash -CI=1 NX_DAEMON=false pnpm nx run @tanstack/router-core:test:unit --outputStyle=stream --skipRemoteCache -- bench tests/route-tree-construction.bench.ts --run --testNamePattern=1000.routes --reporter=json --outputFile=/tmp/route-tree-construction.json -``` - -It covers 100, 1,000, and 10,000 static, dynamic, nested, or mixed routes. -The processing-only case creates fresh route objects in an untimed -`beforeEach`, then measures `processRouteTree` and `route.init`. A separate -case includes route-object creation. Neither case measures first interpolation -or navigation. Remove the name filter to run all sizes. Compare identical -benchmark sources in separate checkouts and repeat fresh processes; a cached -router or repeatedly initialized tree is not a construction baseline. - -## Opt-in React Link performance suite - -`link-performance/` contains additional client-navigation and SSR workloads for -focused Link work. They are **not included** in the regular client-nav/SSR -aggregate projects or their CodSpeed build dependencies; they only run through -the dedicated `@benchmarks/react-link-performance` targets below. Use `-t` to -narrow a run to specific cases. - -```bash -CI=1 NX_DAEMON=false pnpm nx run @benchmarks/react-link-performance:test:perf:client --outputStyle=stream --skipRemoteCache -- --run -CI=1 NX_DAEMON=false pnpm nx run @benchmarks/react-link-performance:test:perf:ssr --outputStyle=stream --skipRemoteCache -- --run - -# Select a feature and save the normal Vitest JSON report. -CI=1 NX_DAEMON=false pnpm nx run @benchmarks/react-link-performance:test:perf:client --outputStyle=stream --skipRemoteCache -- --run -t "updater|optional|splat" --reporter=json --outputFile=/tmp/link-perf.json -``` - -The cases cover repeated versus unique destination params, updater functions, -relative/inherited values, search middleware chains, param stringification, -optional and splat segments, encoding, masks, basepath/rewrites, and active -props with structured search. These exercise different costs: cache hits and -misses, parameter cloning, callbacks, middleware traversal, URI encoding, -building masked/public locations, active-state comparisons, and prop merging. -Existing preload, mount, and route-tree-scale scenarios remain responsible for -those separate workloads. - -- **Client:** 200 persistent measured Links, four control Links, and eight - completed navigations per timed batch. The existing client harness checks - hrefs and active state during its untimed warm-up lap. Control navigations - replace the history entry, keeping history size constant. Post-measurement - assertions also check that the measured anchors stayed mounted. -- **SSR:** four fresh-router requests per timed batch, each rendering 200 - measured Links through `RouterProvider` and `renderToString`. Router creation, - `router.load()`, rendering, and history cleanup are included. This isolates - Router SSR Link work, not Start HTTP handling, dehydration, or streaming. - HTML assertions run outside the timed batch. -- Both use the same code-based workload definitions and production JSX/library - builds. The regular Vitest entry points use at least 100 warm-up iterations, - one second of warm-up time, and five-second measurement windows. The client - and server bundles assert their resolved `isServer` environment. React and - React DOM remain external so comparisons can share the same renderer runtime. - These bundles are Node-hosted (jsdom for client mode), not browser deployments. - -Run the gate tests and typecheck separately: - -```bash -CI=1 NX_DAEMON=false pnpm nx run @benchmarks/react-link-performance:test:unit --outputStyle=stream --skipRemoteCache -CI=1 NX_DAEMON=false pnpm nx run @benchmarks/react-link-performance:test:types --outputStyle=stream --skipRemoteCache -``` - -For before/after comparisons, use identical benchmark files and dependencies -on both refs, build each ref through its Nx targets, and alternate fresh -Vitest processes. Report the actual refs, per-case means and relative margins -of error; rerun noisy or borderline results with `-t` rather than interpreting -a small difference as a proven speedup. Client and SSR times have different -batch units and should not be compared directly. - -### Stable paired comparisons - -For regression decisions, prefer the paired runner over a whole-file Vitest -run. It starts a fresh process for every case and repetition, avoiding JIT -feedback from earlier cases. Inside each process, both revisions share the -same production React installation but have separate router/app modules and -router instances. Initialization order alternates between repetitions. -Built snapshots are staged under `node_modules/.cache` so the TypeScript -harness loader does not transpile their emitted JavaScript a second time. - -```bash -# Build the baseline using these same benchmark sources in its own checkout. -# --baseline points to that checkout's link-performance/dist directory. -pnpm nx run @benchmarks/react-link-performance:test:perf:stable -- \ - --baseline /path/to/baseline/benchmarks/client-nav/link-performance/dist \ - --outputJson /tmp/paired-links.json - -# Narrow a comparison, or increase independent process repetitions. -pnpm nx run @benchmarks/react-link-performance:test:perf:stable -- \ - --baseline /path/to/baseline/benchmarks/client-nav/link-performance/dist \ - --mode ssr -t "middleware|unique-params" --repeats 6 \ - --outputJson /tmp/paired-links-ssr.json -``` - -The runner requires Node with `process.threadCpuUsage` (Node 24 works). -It fixes V8 random/hash seeds, warms each variant for at least two seconds -and 100 batches, then alternates ABBA/BAAB blocks calibrated to roughly 500 ms. -Both variants do exactly the same number of batches per block. It records -main-thread CPU time, wall time, and whole-process CPU time; GC during -measurement is not disabled or discarded. - -The default is four independent process repetitions. Reported 95% intervals -use their paired log-ratios, not the many correlated batches as independent -samples. A faster/slower verdict requires CPU and wall intervals to agree. -Intervals overlapping zero or disagreeing metrics are inconclusive; narrow -intervals entirely inside +/-2% are reported separately. - -An A/A calibration uses the current `dist` directory as `--baseline`. Its -intervals should contain zero before trusting similarly sized A/B differences. -Shared-machine contention can still make small changes unresolved. Do not -interpret a point estimate alone, or an inconclusive result, as proof that -a workload is unchanged. diff --git a/benchmarks/client-nav/jsdom.ts b/benchmarks/client-nav/jsdom.ts index 855c2a2316..d2183decee 100644 --- a/benchmarks/client-nav/jsdom.ts +++ b/benchmarks/client-nav/jsdom.ts @@ -25,16 +25,10 @@ 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', @@ -50,6 +44,5 @@ setGlobal( ) window.scrollTo = () => {} -setGlobal('scrollTo', () => {}) export { window } diff --git a/benchmarks/client-nav/link-performance/cases.ts b/benchmarks/client-nav/link-performance/cases.ts deleted file mode 100644 index a25eac563b..0000000000 --- a/benchmarks/client-nav/link-performance/cases.ts +++ /dev/null @@ -1,360 +0,0 @@ -export const LINK_CASES = [ - { - id: 'shared-params', - label: 'Shared string params', - description: '200 persistent Links reuse 40 string parameter values.', - }, - { - id: 'unique-params', - label: 'Unique string params', - description: '200 distinct parameter values exceed the 128-result cache.', - }, - { - id: 'param-updaters', - label: 'Parameter updaters', - description: 'Parameter functions derive destinations from current params.', - }, - { - id: 'location-updaters', - label: 'Search, hash and state updaters', - description: - 'Functions derive search, hash and history state from the source.', - }, - { - id: 'relative', - label: 'Relative targets', - description: 'Parent and child targets inherit current params and search.', - }, - { - id: 'middleware', - label: 'Search middleware chain', - description: - 'Retain a tenant, strip a default page and normalize a filter.', - }, - { - id: 'numeric-params', - label: 'Numeric params', - description: 'Parse numbers, update them numerically and stringify them.', - }, - { - id: 'optional-params', - label: 'Optional segments', - description: 'Set, inherit and explicitly clear an optional path segment.', - }, - { - id: 'splats', - label: 'Splat params', - description: 'Empty, multi-segment and encoded splat values.', - }, - { - id: 'encoding', - label: 'Allowed path characters', - description: 'Preserve allowed @, : and + while encoding other characters.', - }, - { - id: 'masks', - label: 'Explicit route masks', - description: - 'Build a different public path and search for each destination.', - }, - { - id: 'rewrites', - label: 'Basepath and rewrites', - description: 'Compose /app with input/output locale path rewrites.', - }, - { - id: 'active', - label: 'Active props and structured search', - description: - 'Exact, fuzzy and search matching with props and render children.', - }, -] as const - -export type LinkCaseId = (typeof LINK_CASES)[number]['id'] - -export const LINK_COUNT = 200 -export const NAVIGATION_STATES = [1, 2, 3, 0] as const -export const LOCALES = ['en', 'fr', 'de', 'es'] as const - -export interface Filter { - tag: string - flags: { open: boolean } - tags: Array -} - -export interface LinkSearch { - page?: number - tenant?: string - filter?: Filter -} - -export function sourceFilter(index: number): Filter { - return { - tag: `group-${index}`, - flags: { open: index % 2 === 0 }, - tags: ['links', `state-${index}`], - } -} - -export function sourceSearch( - caseId: LinkCaseId, - stateIndex: number, -): Partial { - switch (caseId) { - case 'location-updaters': - case 'relative': - case 'middleware': - case 'active': - return { - page: stateIndex + 1, - tenant: `tenant-${stateIndex}`, - filter: sourceFilter(stateIndex), - } - case 'rewrites': - return { tenant: LOCALES[stateIndex] } - default: - return {} - } -} - -export function optionalCategory(stateIndex: number) { - return stateIndex % 2 === 0 ? `category-${stateIndex}` : undefined -} - -export function splatValue(index: number) { - switch (index % 4) { - case 0: - return '' - case 1: - return `folder/sub/file-${index % 40}` - case 2: - return 'a b/100%/caf\u00e9?#' - default: - return 'literal%2F/\u{1f680}' - } -} - -export function encodedValue(index: number) { - return `user-${index % 40}@mail.test:tag+value /?#% caf\u00e9` -} - -function url(pathname: string, search: Partial = {}, hash = '') { - const result = new URL(pathname, 'http://localhost') - for (const [key, value] of Object.entries( - search, - )) { - if (value !== undefined) { - result.searchParams.set( - key, - typeof value === 'object' ? JSON.stringify(value) : String(value), - ) - } - } - result.hash = hash - return result.pathname + result.search + result.hash -} - -function sourcePath(caseId: LinkCaseId, stateIndex: number) { - switch (caseId) { - case 'relative': - return `/teams/team-${stateIndex}/item-${stateIndex}` - case 'numeric-params': - return `/numbers/${stateIndex}` - case 'optional-params': { - const category = optionalCategory(stateIndex) - return `/optional/${category ? `${category}/` : ''}item-${stateIndex}` - } - case 'splats': - return `/files/source/state-${stateIndex}` - case 'encoding': - return `/encoded/source-${stateIndex}` - case 'active': - return `/items/item-${stateIndex}/details` - default: - return `/items/item-${stateIndex}` - } -} - -export function getSourceUrl(caseId: LinkCaseId, stateIndex: number): string { - if (!Number.isInteger(stateIndex) || stateIndex < 0 || stateIndex > 3) { - throw new Error(`Invalid Link performance state: ${stateIndex}`) - } - const pathname = sourcePath(caseId, stateIndex) - if (caseId === 'rewrites') { - return `/app/${LOCALES[stateIndex]}${pathname}` - } - return url( - pathname, - sourceSearch(caseId, stateIndex), - caseId === 'location-updaters' ? `source-${stateIndex}` : '', - ) -} - -// These expectations use fixture values and platform encoding, not router APIs. -function expectedHref(caseId: LinkCaseId, stateIndex: number, index: number) { - const itemId = `item-${index % 40}` - switch (caseId) { - case 'shared-params': - return `/items/${itemId}` - case 'unique-params': - return `/items/item-${index}` - case 'param-updaters': - return `/items/item-${stateIndex}-related-${index % 40}` - case 'location-updaters': - return url( - `/items/item-${stateIndex}`, - { - ...sourceSearch(caseId, stateIndex), - page: stateIndex + 2 + (index % 5), - }, - `source-${stateIndex}-link-${index % 5}`, - ) - case 'relative': - return url( - index % 2 === 0 - ? `/teams/team-${stateIndex}` - : `/teams/team-${stateIndex}/item-${stateIndex}/details`, - sourceSearch(caseId, stateIndex), - ) - case 'middleware': - return url(`/filtered/${itemId}`, { - tenant: `tenant-${stateIndex}`, - page: index % 2 === 0 ? undefined : 2, - filter: { ...sourceFilter(index % 4), tag: `LABEL-${index % 40}` }, - }) - case 'numeric-params': - return `/numbers/${stateIndex + (index % 40)}` - case 'optional-params': { - const category = - index % 3 === 0 - ? 'fixed' - : index % 3 === 1 - ? optionalCategory(stateIndex) - : undefined - return `/optional/${category ? `${category}/` : ''}${itemId}` - } - case 'splats': { - const value = splatValue(index) - return `/files${value ? `/${value.split('/').map(encodeURIComponent).join('/')}` : ''}` - } - case 'encoding': { - const value = encodeURIComponent(encodedValue(index)) - .replaceAll('%40', '@') - .replaceAll('%3A', ':') - .replaceAll('%2B', '+') - return `/encoded/${value}` - } - case 'masks': - return url(`/public/display-${index % 40}`, { - tenant: `mask-${index % 4}`, - }) - case 'rewrites': - return url(`/app/${LOCALES[index % 4]}/items/${itemId}`, { - page: (index % 3) + 1, - }) - case 'active': { - const item = Math.floor(index / 5) - const variant = index % 5 - const search = - variant < 3 - ? { filter: sourceFilter(item % 4) } - : { - ...sourceSearch('active', item % 4), - ...(variant === 4 ? { filter: undefined } : {}), - } - return url(`/items/item-${item}${variant < 2 ? '' : '/details'}`, search) - } - } -} - -function assertUrl( - actualHref: string | null, - expectedHref: string, - label: string, -) { - if (actualHref === null) { - throw new Error(`${label}: missing href`) - } - const actual = new URL(actualHref, 'http://localhost') - const expected = new URL(expectedHref, 'http://localhost') - // Query ordering and the platform's '+' versus '%20' are immaterial here. - const query = (value: URL) => - JSON.stringify([...value.searchParams.entries()].sort()) - if ( - actual.origin !== expected.origin || - actual.pathname !== expected.pathname || - actual.hash !== expected.hash || - query(actual) !== query(expected) - ) { - throw new Error( - `${label}: expected ${expectedHref}, received ${actualHref}`, - ) - } -} - -export function assertScenario( - caseId: LinkCaseId, - stateIndex: number, - root: ParentNode, -): void { - const source = root.querySelector('[data-testid="source-path"]') - if (source?.textContent !== sourcePath(caseId, stateIndex)) { - throw new Error( - `${caseId}/${stateIndex}: unexpected source path ${source?.textContent}`, - ) - } - const links = root.querySelectorAll('a[data-perf-link]') - if (links.length !== LINK_COUNT) { - throw new Error( - `${caseId}: expected ${LINK_COUNT} Links, got ${links.length}`, - ) - } - for (const [index, link] of links.entries()) { - const label = `${caseId}/${stateIndex}/link-${index}` - if (link.getAttribute('data-perf-link') !== String(index)) { - throw new Error(`${label}: unexpected Link order`) - } - assertUrl( - link.getAttribute('href'), - expectedHref(caseId, stateIndex, index), - label, - ) - let active: boolean | undefined - if (caseId === 'shared-params') { - active = index % 40 === stateIndex - } else if (caseId === 'unique-params') { - active = index === stateIndex - } else if (caseId === 'active') { - active = - Math.floor(index / 5) === stateIndex && [0, 2, 3].includes(index % 5) - if ( - link.textContent !== `${index}:${active ? 'active' : 'inactive'}` || - link.getAttribute('title') !== (active ? 'active' : 'inactive') || - !link.classList.contains(active ? 'perf-active' : 'perf-inactive') || - link.style.color !== (active ? 'green' : 'gray') || - link.style.opacity !== '0.8' - ) { - throw new Error( - `${label}: active props or render children are incorrect`, - ) - } - } - if ( - active !== undefined && - (link.getAttribute('data-status') === 'active') !== active - ) { - throw new Error(`${label}: expected active=${active}`) - } - } - for (let state = 0; state < 4; state++) { - const control = root.querySelector(`[data-testid="go-state-${state}"]`) - if (!control || control.hasAttribute('data-perf-link')) { - throw new Error(`${caseId}: missing or measured control Link ${state}`) - } - assertUrl( - control.getAttribute('href'), - getSourceUrl(caseId, state), - `${caseId}/control-${state}`, - ) - } -} diff --git a/benchmarks/client-nav/link-performance/client.bench.ts b/benchmarks/client-nav/link-performance/client.bench.ts deleted file mode 100644 index f819fab52b..0000000000 --- a/benchmarks/client-nav/link-performance/client.bench.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../cpu-simulation' -import { LINK_CASES } from './cases' -import { createClientScenario, samplingOptions } from './scenario' -import type * as App from './src/client' - -const appModulePath = './dist/client/app.js' -const app: typeof App = await import(/* @vite-ignore */ appModulePath) -if (app.serverEnvironment !== false) { - throw new Error('Link client benchmarks must use the production client build') -} - -for (const { id, label } of LINK_CASES) { - test(label, async ({ bench }) => { - const scenario = createClientScenario(app, id) - function finish() { - try { - scenario.check() - } finally { - scenario.teardown() - } - } - - await bench( - `client Links: ${id}`, - benchLifecycle({ before: scenario.setup, after: finish }), - scenario.batch, - ).run(samplingOptions) - }) -} diff --git a/benchmarks/client-nav/link-performance/config.test.ts b/benchmarks/client-nav/link-performance/config.test.ts deleted file mode 100644 index 1a468a3169..0000000000 --- a/benchmarks/client-nav/link-performance/config.test.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { afterEach, describe, expect, test, vi } from 'vitest' -import { createLinkPerformanceConfig } from './config' - -afterEach(() => vi.unstubAllEnvs()) - -describe.each(['client', 'ssr'] as const)('%s configuration', (target) => { - test('discovers only the requested suite', () => { - const config = createLinkPerformanceConfig(target) - expect(config.test?.benchmark?.include).toEqual([`${target}.bench.ts`]) - }) - - test('builds production code for the correct environment', () => { - const config = createLinkPerformanceConfig(target) - expect(config.define?.['process.env.NODE_ENV']).toBe('"production"') - expect(config.resolve?.conditions).toContain( - target === 'ssr' ? 'node' : 'browser', - ) - expect(config.build?.ssr).toBe(target === 'ssr') - expect(config.build?.outDir).toBe(`./dist/${target}`) - expect(config.build?.rolldownOptions?.platform).toBe('node') - expect(config.build?.rolldownOptions?.external).toEqual([ - 'node:module', - 'module', - /^react(?:\/|$)/, - /^react-dom(?:\/|$)/, - ]) - }) - - test('does not retransform built bundles in the test environment', () => { - vi.stubEnv('VITEST', 'true') - const config = createLinkPerformanceConfig(target) - expect(config.ssr?.noExternal).toBeUndefined() - expect(config.test?.server?.deps?.external).toEqual([ - /\/link-performance\/dist\//, - ]) - }) - - test('bundles router dependencies when building app snapshots', () => { - vi.stubEnv('VITEST', undefined) - expect(createLinkPerformanceConfig(target).ssr?.noExternal).toBe(true) - }) -}) diff --git a/benchmarks/client-nav/link-performance/config.ts b/benchmarks/client-nav/link-performance/config.ts deleted file mode 100644 index 416b027057..0000000000 --- a/benchmarks/client-nav/link-performance/config.ts +++ /dev/null @@ -1,69 +0,0 @@ -import { fileURLToPath } from 'node:url' -import react from '@vitejs/plugin-react' -import codspeedPlugin from '@codspeed/vitest-plugin' -import type { UserConfig } from 'vite' - -const root = fileURLToPath(new URL('.', import.meta.url)) - -export function createLinkPerformanceConfig( - target: 'client' | 'ssr', -): UserConfig { - const server = target === 'ssr' - - return { - root, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - react(), - ], - resolve: { - conditions: [server ? 'node' : 'browser', 'production'], - }, - ssr: { - noExternal: process.env.VITEST ? undefined : true, - resolve: { - conditions: ['node', 'production'], - }, - }, - build: { - outDir: `./dist/${target}`, - emptyOutDir: true, - minify: false, - ssr: server, - lib: { - entry: `${root}src/${target}.tsx`, - formats: ['es'], - fileName: 'app', - }, - rolldownOptions: { - platform: 'node', - external: [ - 'node:module', - 'module', - /^react(?:\/|$)/, - /^react-dom(?:\/|$)/, - ], - output: { entryFileNames: 'app.js' }, - }, - }, - test: { - name: `react-link-performance-${target}`, - watch: false, - environment: server ? 'node' : 'jsdom', - setupFiles: server ? [] : ['../vitest.setup.ts'], - server: { - deps: { - external: [/\/link-performance\/dist\//], - }, - }, - include: [], - benchmark: { - include: [`${target}.bench.ts`], - }, - }, - } -} diff --git a/benchmarks/client-nav/link-performance/project.json b/benchmarks/client-nav/link-performance/project.json deleted file mode 100644 index fd1751c081..0000000000 --- a/benchmarks/client-nav/link-performance/project.json +++ /dev/null @@ -1,103 +0,0 @@ -{ - "name": "@benchmarks/react-link-performance", - "projectType": "application", - "tags": ["optional-benchmark"], - "targets": { - "build:client": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-router"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config ./link-performance/vite.client.config.ts", - "cwd": "benchmarks/client-nav" - } - }, - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-router"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config ./link-performance/vite.ssr.config.ts", - "cwd": "benchmarks/client-nav" - } - }, - "test:perf:client": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": ["build:client"], - "options": { - "command": "NODE_ENV=production vitest bench --mode benchmark --config ./link-performance/vite.client.config.ts", - "cwd": "benchmarks/client-nav" - } - }, - "test:perf:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": ["build:ssr"], - "options": { - "command": "NODE_ENV=production vitest bench --mode benchmark --config ./link-performance/vite.ssr.config.ts", - "cwd": "benchmarks/client-nav" - } - }, - "test:perf:stable": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": ["build:client", "build:ssr"], - "options": { - "command": "NODE_ENV=production node --import=@swc-node/register/esm-register benchmarks/client-nav/link-performance/stable-runner.ts" - } - }, - "test:unit": { - "executor": "nx:run-commands", - "inputs": [ - "...", - "{workspaceRoot}/benchmarks/client-nav/scenarios/harness.ts", - "{workspaceRoot}/benchmarks/client-nav/scenarios/links/shared.ts", - "{workspaceRoot}/benchmarks/client-nav/setup-helpers.ts", - "{workspaceRoot}/benchmarks/client-nav/tsconfig.json" - ], - "dependsOn": [ - { - "projects": ["@tanstack/history"], - "target": "build" - } - ], - "options": { - "command": "vitest run --config ./link-performance/vitest.config.ts", - "cwd": "benchmarks/client-nav" - } - }, - "test:types": { - "executor": "nx:run-commands", - "inputs": [ - "...", - "{workspaceRoot}/benchmarks/client-nav/jsdom.ts", - "{workspaceRoot}/benchmarks/client-nav/scenarios/harness.ts", - "{workspaceRoot}/benchmarks/client-nav/scenarios/links/shared.ts", - "{workspaceRoot}/benchmarks/client-nav/setup-helpers.ts", - "{workspaceRoot}/benchmarks/client-nav/tsconfig.json", - "{workspaceRoot}/benchmarks/client-nav/vitest.setup.ts" - ], - "dependsOn": [ - { - "projects": ["@tanstack/react-router"], - "target": "build" - } - ], - "options": { - "command": "tsc -p ./link-performance/tsconfig.json --noEmit", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/link-performance/scenario.ts b/benchmarks/client-nav/link-performance/scenario.ts deleted file mode 100644 index f1a3fb6df7..0000000000 --- a/benchmarks/client-nav/link-performance/scenario.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { JSDOM } from 'jsdom' -import { createScenarioSetup } from '../scenarios/harness' -import { ticksPerIteration } from '../scenarios/links/shared' -import { NAVIGATION_STATES, assertScenario, getSourceUrl } from './cases' -import type { LinkCaseId } from './cases' -import type * as ClientApp from './src/client' -import type * as SsrApp from './src/ssr' - -export interface LinkScenario { - setup: () => Promise - batch: () => Promise - check: () => void - teardown: () => void -} - -export const samplingOptions = { - warmupIterations: 100, - warmupTime: 1_000, - time: 5_000, - throws: true, -} - -export function createClientScenario( - app: typeof ClientApp, - id: LinkCaseId, -): LinkScenario { - let mounted: ReturnType | undefined - let container: HTMLElement | undefined - let anchors: Array = [] - const test = createScenarioSetup({ - frameworkLabel: 'React', - mount: (element, history) => { - container = element - mounted = app.mountTestApp(element, history, id) - return mounted - }, - initialUrl: getSourceUrl(id, 0), - steps: NAVIGATION_STATES.map((state) => `go-state-${state}`), - assertAfterStep: (index, element) => { - assertScenario(id, NAVIGATION_STATES[index]!, element) - if (!mounted) { - throw new Error('Link benchmark app was not mounted') - } - mounted.assertStateUpdates() - }, - }) - - return { - async setup() { - await test.before() - if (!container) { - throw new Error('Link benchmark container was not created') - } - anchors = [...container.querySelectorAll('a[data-perf-link]')] - }, - async batch() { - for (let index = 0; index < ticksPerIteration; index++) { - await test.tick() - } - await test.finishBatch() - }, - check() { - if (!container || !mounted) { - throw new Error('Link benchmark app was not mounted') - } - assertScenario(id, 0, container) - mounted.assertStateUpdates() - if (mounted.router.history.length !== 1) { - throw new Error('Link benchmark history must remain bounded') - } - const current = container.querySelectorAll('a[data-perf-link]') - if (anchors.some((anchor, index) => current[index] !== anchor)) { - throw new Error('Measured Links must stay mounted across navigations') - } - }, - teardown: test.after, - } -} - -export function createSsrScenario( - app: typeof SsrApp, - id: LinkCaseId, -): LinkScenario { - let html = '' - let state = 0 - function check() { - const dom = new JSDOM(html) - try { - assertScenario(id, state, dom.window.document) - } finally { - dom.window.close() - } - } - - return { - async setup() { - for (const nextState of NAVIGATION_STATES) { - state = nextState - html = await app.renderScenario(id, state, true) - check() - } - }, - async batch() { - for (const nextState of NAVIGATION_STATES) { - state = nextState - html = await app.renderScenario(id, state) - } - }, - check, - teardown() { - html = '' - }, - } -} diff --git a/benchmarks/client-nav/link-performance/src/client.tsx b/benchmarks/client-nav/link-performance/src/client.tsx deleted file mode 100644 index a187ee8c15..0000000000 --- a/benchmarks/client-nav/link-performance/src/client.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { RouterProvider } from '@tanstack/react-router' -import { isServer } from '@tanstack/router-core/isServer' -import { createRoot } from 'react-dom/client' -import { assertStateUpdates, createLinkRouter } from './workload' -import type { LinkRouter } from './workload' -import type { RouterHistory } from '@tanstack/history' -import type { LinkCaseId } from '../cases' - -export const serverEnvironment: boolean | undefined = isServer - -export function mountTestApp( - container: HTMLElement, - history: RouterHistory, - caseId: LinkCaseId, -): { - router: LinkRouter - unmount: () => void - assertStateUpdates: () => void -} { - const router = createLinkRouter(caseId, history, false) - const root = createRoot(container) - root.render() - - return { - router, - unmount: () => root.unmount(), - assertStateUpdates: () => assertStateUpdates(router), - } -} diff --git a/benchmarks/client-nav/link-performance/src/ssr.tsx b/benchmarks/client-nav/link-performance/src/ssr.tsx deleted file mode 100644 index 491191b1f9..0000000000 --- a/benchmarks/client-nav/link-performance/src/ssr.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { RouterProvider, createMemoryHistory } from '@tanstack/react-router' -import { isServer } from '@tanstack/router-core/isServer' -import { renderToString } from 'react-dom/server' -import { getSourceUrl } from '../cases' -import { assertStateUpdates, createLinkRouter } from './workload' -import type { LinkCaseId } from '../cases' - -export const serverEnvironment: boolean | undefined = isServer - -export async function renderScenario( - caseId: LinkCaseId, - stateIndex: number, - verify = false, -) { - const history = createMemoryHistory({ - initialEntries: [getSourceUrl(caseId, stateIndex)], - }) - const router = createLinkRouter(caseId, history, true) - try { - await router.load() - const html = renderToString() - if (verify) { - assertStateUpdates(router) - } - return html - } finally { - history.destroy() - } -} diff --git a/benchmarks/client-nav/link-performance/src/workload.tsx b/benchmarks/client-nav/link-performance/src/workload.tsx deleted file mode 100644 index 8315b85b8b..0000000000 --- a/benchmarks/client-nav/link-performance/src/workload.tsx +++ /dev/null @@ -1,506 +0,0 @@ -import { - Link, - Outlet, - createRootRouteWithContext, - createRoute, - createRouter, - linkOptions, - retainSearchParams, - stripSearchParams, - useLocation, -} from '@tanstack/react-router' -import { - LINK_COUNT, - LOCALES, - encodedValue, - optionalCategory, - sourceFilter, - sourceSearch, - splatValue, -} from '../cases' -import type { RouterHistory } from '@tanstack/history' -import type { SearchSchemaInput } from '@tanstack/react-router' -import type { Filter, LinkCaseId, LinkSearch } from '../cases' - -interface StateUpdates { - calls: number - verifiedCalls: number - input: number - output: number - offset: number -} - -interface WorkloadContext { - caseId: LinkCaseId - stateUpdates: StateUpdates -} - -function isFilter(value: unknown): value is Filter { - return ( - typeof value === 'object' && - value !== null && - 'tag' in value && - typeof value.tag === 'string' && - 'flags' in value && - typeof value.flags === 'object' && - value.flags !== null && - 'open' in value.flags && - typeof value.flags.open === 'boolean' && - 'tags' in value && - Array.isArray(value.tags) && - value.tags.every((tag: unknown) => typeof tag === 'string') - ) -} - -const rootRoute = createRootRouteWithContext()({ - validateSearch: ( - search: Record & SearchSchemaInput, - ): LinkSearch => ({ - page: typeof search.page === 'number' ? search.page : undefined, - tenant: typeof search.tenant === 'string' ? search.tenant : undefined, - filter: isFilter(search.filter) ? search.filter : undefined, - }), - component: RootLayout, -}) - -const itemsRoute = createRoute({ - getParentRoute: () => rootRoute, - path: 'items/$itemId', -}) -const detailsRoute = createRoute({ - getParentRoute: () => itemsRoute, - path: 'details', -}) -const teamRoute = createRoute({ - getParentRoute: () => rootRoute, - path: 'teams/$teamId', -}) -const teamItemRoute = createRoute({ - getParentRoute: () => teamRoute, - path: '$itemId', -}) -const teamDetailsRoute = createRoute({ - getParentRoute: () => teamItemRoute, - path: 'details', -}) -const filteredRoute = createRoute({ - getParentRoute: () => rootRoute, - path: 'filtered/$itemId', - search: { - middlewares: [ - retainSearchParams(['tenant']), - stripSearchParams({ page: 1 }), - ({ search, next }) => { - const result = next(search) - return { - ...result, - filter: result.filter - ? { ...result.filter, tag: result.filter.tag.trim().toUpperCase() } - : undefined, - } - }, - ], - }, -}) -const numericRoute = createRoute({ - getParentRoute: () => rootRoute, - path: 'numbers/$number', - params: { - parse: ({ number }) => { - const value = Number(number) - if (!Number.isFinite(value)) { - throw new Error(`Invalid number: ${number}`) - } - return { number: value } - }, - stringify: ({ number }) => ({ number: String(number) }), - }, -}) -const optionalRoute = createRoute({ - getParentRoute: () => rootRoute, - path: 'optional/{-$category}/$itemId', -}) -const splatRoute = createRoute({ - getParentRoute: () => rootRoute, - path: 'files/$', -}) -const encodedRoute = createRoute({ - getParentRoute: () => rootRoute, - path: 'encoded/$value', -}) -const publicRoute = createRoute({ - getParentRoute: () => rootRoute, - path: 'public/$itemId', -}) - -const routeTree = rootRoute.addChildren([ - itemsRoute.addChildren([detailsRoute]), - teamRoute.addChildren([teamItemRoute.addChildren([teamDetailsRoute])]), - filteredRoute, - numericRoute, - optionalRoute, - splatRoute, - encodedRoute, - publicRoute, -]) - -const localeRewrite = { - input: ({ url }: { url: URL }) => { - const match = /^\/(en|fr|de|es)(\/.*)$/.exec(url.pathname) - if (match) { - url.pathname = match[2]! - url.searchParams.set('tenant', match[1]!) - } - return url - }, - output: ({ url }: { url: URL }) => { - const locale = url.searchParams.get('tenant') - if (locale) { - url.searchParams.delete('tenant') - url.pathname = `/${locale}${url.pathname}` - } - return url - }, -} - -export function createLinkRouter( - caseId: LinkCaseId, - history: RouterHistory, - isServer: boolean, -) { - const context: WorkloadContext = { - caseId, - stateUpdates: { - calls: 0, - verifiedCalls: 0, - input: 0, - output: 0, - offset: 0, - }, - } - return createRouter({ - routeTree, - history, - isServer, - context, - scrollRestoration: false, - defaultPreload: false, - trailingSlash: 'never', - pathParamsAllowedCharacters: - caseId === 'encoding' ? ['@', ':', '+'] : undefined, - ...(caseId === 'rewrites' - ? { basepath: '/app', rewrite: localeRewrite } - : {}), - }) -} - -export type LinkRouter = ReturnType - -declare module '@tanstack/react-router' { - interface Register { - router: LinkRouter - } -} - -declare module '@tanstack/history' { - interface HistoryState { - linkPerfState?: number - } -} - -// Call alongside DOM assertions, outside the timed loop, after each sample. -export function assertStateUpdates(router: LinkRouter): void { - const { caseId, stateUpdates } = router.options.context - if (caseId !== 'location-updaters') { - return - } - const input = router.state.location.state.linkPerfState ?? 0 - if ( - stateUpdates.calls - stateUpdates.verifiedCalls < LINK_COUNT || - stateUpdates.input !== input || - stateUpdates.output !== input + stateUpdates.offset || - stateUpdates.offset < 1 || - stateUpdates.offset > 40 - ) { - throw new Error( - 'Link history-state updaters did not run with current state', - ) - } - stateUpdates.verifiedCalls = stateUpdates.calls -} - -function sourceOptions(caseId: LinkCaseId, stateIndex: number) { - const itemId = `item-${stateIndex}` - const common = { - search: sourceSearch(caseId, stateIndex), - hash: caseId === 'location-updaters' ? `source-${stateIndex}` : '', - state: { linkPerfState: stateIndex + 10 }, - } - switch (caseId) { - case 'relative': - return linkOptions({ - ...common, - to: '/teams/$teamId/$itemId', - params: { teamId: `team-${stateIndex}`, itemId }, - }) - case 'numeric-params': - return linkOptions({ - ...common, - to: '/numbers/$number', - params: { number: stateIndex }, - }) - case 'optional-params': - return linkOptions({ - ...common, - to: '/optional/{-$category}/$itemId', - params: { category: optionalCategory(stateIndex), itemId }, - }) - case 'splats': - return linkOptions({ - ...common, - to: '/files/$', - params: { _splat: `source/state-${stateIndex}` }, - }) - case 'encoding': - return linkOptions({ - ...common, - to: '/encoded/$value', - params: { value: `source-${stateIndex}` }, - }) - case 'active': - return linkOptions({ - ...common, - to: '/items/$itemId/details', - params: { itemId }, - }) - default: - return linkOptions({ - ...common, - to: '/items/$itemId', - params: { itemId }, - }) - } -} - -const indexes = Array.from({ length: LINK_COUNT }, (_, index) => index) -const controls = [0, 1, 2, 3] as const - -function SourcePath() { - const pathname = useLocation({ select: (location) => location.pathname }) - return {pathname} -} - -function RootLayout() { - const context = rootRoute.useRouteContext() - return ( - <> - - -
- {indexes.map((index) => measuredLink(context, index))} -
- - - ) -} - -function measuredLink( - { caseId, stateUpdates }: WorkloadContext, - index: number, -) { - const common = { - key: index, - 'data-perf-link': index, - preload: false, - children: `Link ${index}`, - } as const - const itemId = `item-${index % 40}` - switch (caseId) { - case 'shared-params': - case 'unique-params': - return ( - - ) - case 'param-updaters': - return ( - ({ - itemId: `${previous.itemId}-related-${index % 40}`, - })} - /> - ) - case 'location-updaters': - return ( - ({ - ...previous, - page: (previous.page ?? 1) + 1 + (index % 5), - })} - hash={(previous) => `${previous}-link-${index % 5}`} - state={(previous) => { - const input = previous.linkPerfState ?? 0 - const offset = (index % 40) + 1 - const output = input + offset - stateUpdates.calls++ - stateUpdates.input = input - stateUpdates.output = output - stateUpdates.offset = offset - return { ...previous, linkPerfState: output } - }} - /> - ) - case 'relative': - return ( - - ) - case 'middleware': - return ( - - ) - case 'numeric-params': - return ( - ({ number: previous.number + (index % 40) })} - /> - ) - case 'optional-params': - return ( - - ) - case 'splats': - return ( - - ) - case 'encoding': - return ( - - ) - case 'masks': - return ( - - ) - case 'rewrites': - return ( - - ) - case 'active': { - const item = Math.floor(index / 5) - const variant = index % 5 - return ( - ({ - className: 'perf-active', - title: 'active', - style: { color: 'green' }, - })} - inactiveProps={() => ({ - className: 'perf-inactive', - title: 'inactive', - style: { color: 'gray' }, - })} - > - {({ isActive }) => `${index}:${isActive ? 'active' : 'inactive'}`} - - ) - } - } -} diff --git a/benchmarks/client-nav/link-performance/ssr.bench.ts b/benchmarks/client-nav/link-performance/ssr.bench.ts deleted file mode 100644 index c30084e510..0000000000 --- a/benchmarks/client-nav/link-performance/ssr.bench.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../cpu-simulation' -import { LINK_CASES } from './cases' -import { createSsrScenario, samplingOptions } from './scenario' -import type * as App from './src/ssr' - -const appUrl = new URL('./dist/ssr/app.js', import.meta.url).href -const app: typeof App = await import(/* @vite-ignore */ appUrl) -if (app.serverEnvironment !== true) { - throw new Error('Link SSR benchmarks must use the production server build') -} - -for (const { id, label } of LINK_CASES) { - test(label, async ({ bench }) => { - const scenario = createSsrScenario(app, id) - function finish() { - try { - scenario.check() - } finally { - scenario.teardown() - } - } - - await bench( - `SSR Links: ${id}`, - benchLifecycle({ before: scenario.setup, after: finish }), - scenario.batch, - ).run(samplingOptions) - }) -} diff --git a/benchmarks/client-nav/link-performance/stable-runner.ts b/benchmarks/client-nav/link-performance/stable-runner.ts deleted file mode 100644 index 59ccfa3cb4..0000000000 --- a/benchmarks/client-nav/link-performance/stable-runner.ts +++ /dev/null @@ -1,269 +0,0 @@ -import { fork } from 'node:child_process' -import { createHash } from 'node:crypto' -import { - copyFileSync, - mkdirSync, - readFileSync, - rmSync, - writeFileSync, -} from 'node:fs' -import { dirname, resolve } from 'node:path' -import { fileURLToPath } from 'node:url' -import { parseArgs } from 'node:util' -import { LINK_CASES } from './cases' -import { createStagingDirectory } from './staging' -import { classify, mean, summarizeRatios } from './statistics' -import type { LinkCaseId } from './cases' -import type { - BlockSample, - Mode, - Variant, - WorkerRequest, - WorkerResponse, -} from './worker-protocol' - -const projectRoot = fileURLToPath(new URL('.', import.meta.url)) -const workspaceRoot = resolve(projectRoot, '../../..') - -function startWorker() { - const child = fork( - fileURLToPath(new URL('./stable-worker.ts', import.meta.url)), - { - cwd: workspaceRoot, - env: { ...process.env, NODE_ENV: 'production' }, - execArgv: [ - '--import=@swc-node/register/esm-register', - '--random-seed=42', - '--hash-seed=42', - ], - stdio: ['ignore', 'ignore', 'pipe', 'ipc'], - }, - ) - let stderr = '' - child.stderr?.on('data', (data: Buffer) => { - stderr = (stderr + data.toString()).slice(-4_096) - }) - - function request(message: WorkerRequest): Promise { - return new Promise((resolveResponse, reject) => { - const timeout = setTimeout(() => { - finish( - new Error(`Sampling worker timed out: ${message.kind}\n${stderr}`), - ) - }, 60_000) - const onExit = (code: number | null) => - finish(new Error(`Sampling worker exited (${code})\n${stderr}`)) - const onError = (error: Error) => finish(error) - const onMessage = (response: WorkerResponse) => { - if (response.kind === 'error') { - finish(new Error(response.message)) - } else { - finish(undefined, response) - } - } - function finish(error?: Error, response?: WorkerResponse) { - clearTimeout(timeout) - child.off('message', onMessage) - child.off('error', onError) - child.off('exit', onExit) - if (error) { - reject(error) - } else if (response) { - resolveResponse(response) - } - } - child.once('message', onMessage) - child.once('error', onError) - child.once('exit', onExit) - child.send(message, (error) => { - if (error) { - finish(error) - } - }) - }) - } - - return { - request, - kill: () => child.kill(), - } -} - -async function sampleReplica( - mode: Mode, - caseId: LinkCaseId, - baseline: string, - current: string, - replica: number, -) { - const worker = startWorker() - const samples: Array> = [[], []] - const ratios: Array<{ cpu: number; wall: number }> = [] - try { - const starts: Array = [] - // Balance module initialization and which variant finishes warming last. - const startupOrder: Array = replica % 2 ? [1, 0] : [0, 1] - for (const index of startupOrder) { - const ready = await worker.request({ - kind: 'init', - mode, - caseId, - bundle: index === 0 ? baseline : current, - variant: index, - }) - if (ready.kind !== 'ready') { - throw new Error('Expected a ready sampling worker') - } - starts[index] = ready.batchMs - } - const iterations = Math.max(1, Math.ceil(500 / Math.min(...starts))) - for (let round = 0; round < 2; round++) { - const block: Array> = [[], []] - const order: Array = - (round + replica) % 2 ? [1, 0, 0, 1] : [0, 1, 1, 0] - for (const index of order) { - const result = await worker.request({ - kind: 'measure', - iterations, - variant: index, - }) - if (result.kind !== 'sample') { - throw new Error('Expected a block measurement') - } - samples[index]!.push(result.sample) - block[index]!.push(result.sample) - } - ratios.push({ - cpu: - mean(block[1]!.map((s) => s.cpuMs)) / - mean(block[0]!.map((s) => s.cpuMs)), - wall: - mean(block[1]!.map((s) => s.wallMs)) / - mean(block[0]!.map((s) => s.wallMs)), - }) - } - const response = await worker.request({ kind: 'stop' }) - if (response.kind !== 'stopped') { - throw new Error('Expected successful post-measurement assertions') - } - return { - iterations, - baseline: samples[0]!, - current: samples[1]!, - cpuRatio: Math.exp(mean(ratios.map((r) => Math.log(r.cpu)))), - wallRatio: Math.exp(mean(ratios.map((r) => Math.log(r.wall)))), - } - } finally { - worker.kill() - } -} - -async function main() { - const { values } = parseArgs({ - options: { - baseline: { type: 'string' }, - current: { type: 'string', default: resolve(projectRoot, 'dist') }, - mode: { type: 'string', default: 'all' }, - repeats: { type: 'string', default: '4' }, - outputJson: { type: 'string' }, - testNamePattern: { type: 'string', short: 't' }, - }, - }) - if (!values.baseline || !values.outputJson) { - throw new Error( - 'Specify --baseline and --outputJson ', - ) - } - const repeats = Number(values.repeats) - if (!Number.isInteger(repeats) || repeats < 3 || repeats > 11) { - throw new Error('--repeats must be an integer between 3 and 11') - } - if (!['all', 'client', 'ssr'].includes(values.mode)) { - throw new Error('--mode must be all, client, or ssr') - } - const modes: Array = - values.mode === 'all' - ? ['client', 'ssr'] - : values.mode === 'client' - ? ['client'] - : ['ssr'] - const pattern = values.testNamePattern - ? new RegExp(values.testNamePattern) - : undefined - const cases = LINK_CASES.filter( - (c) => !pattern || pattern.test(`${c.label} ${c.id}`), - ) - if (!cases.length) { - throw new Error('No Link workloads match the requested pattern') - } - const report: { - protocol: string - node: string - complete: boolean - results: Array<{ - mode: Mode - caseId: LinkCaseId - baselineSha256: string - currentSha256: string - replicas: Array>> - cpu: ReturnType - wall: ReturnType - verdict: ReturnType - }> - } = { - protocol: - 'fresh process per case/replica; shared React runtime; separately loaded router variants; 2 ABBA/BAAB rounds; ~500ms calibrated fixed-work blocks; >=2s/100 batches warmup; main-thread CPU and wall time; fixed V8 random/hash seeds', - node: process.version, - complete: false, - results: [], - } - const output = resolve(values.outputJson) - mkdirSync(dirname(output), { recursive: true }) - const staging = createStagingDirectory() - try { - for (const mode of modes) { - const baselineInput = resolve(values.baseline, mode, 'app.js') - const currentInput = resolve(values.current, mode, 'app.js') - // Both snapshots resolve React from the same package installation. - const baseline = resolve(staging, `baseline-${mode}.mjs`) - const current = resolve(staging, `current-${mode}.mjs`) - copyFileSync(baselineInput, baseline) - copyFileSync(currentInput, current) - const digest = (file: string) => - createHash('sha256').update(readFileSync(file)).digest('hex') - const baselineSha256 = digest(baseline) - const currentSha256 = digest(current) - for (const { id } of cases) { - const replicas = [] - for (let replica = 0; replica < repeats; replica++) { - replicas.push( - await sampleReplica(mode, id, baseline, current, replica), - ) - } - const cpu = summarizeRatios(replicas.map((r) => r.cpuRatio)) - const wall = summarizeRatios(replicas.map((r) => r.wallRatio)) - const verdict = classify(cpu, wall) - report.results.push({ - mode, - caseId: id, - baselineSha256, - currentSha256, - replicas, - cpu, - wall, - verdict, - }) - writeFileSync(output, JSON.stringify(report, null, 2)) - console.log( - `${mode} ${id}: CPU ${cpu.changePercent.toFixed(2)}% [${cpu.low95.toFixed(2)}, ${cpu.high95.toFixed(2)}], wall ${wall.changePercent.toFixed(2)}% [${wall.low95.toFixed(2)}, ${wall.high95.toFixed(2)}] ${verdict}`, - ) - } - } - report.complete = true - writeFileSync(output, JSON.stringify(report, null, 2)) - } finally { - rmSync(staging, { recursive: true }) - } -} - -await main() diff --git a/benchmarks/client-nav/link-performance/stable-worker.test.ts b/benchmarks/client-nav/link-performance/stable-worker.test.ts deleted file mode 100644 index 087b32414a..0000000000 --- a/benchmarks/client-nav/link-performance/stable-worker.test.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { fork } from 'node:child_process' -import { rmdirSync, unlinkSync, writeFileSync } from 'node:fs' -import { join } from 'node:path' -import { fileURLToPath } from 'node:url' -import { expect, test } from 'vitest' -import { createStagingDirectory } from './staging' -import type { WorkerResponse } from './worker-protocol' - -test('loads emitted JavaScript without retranspiling it through SWC', async () => { - const directory = createStagingDirectory() - const bundle = join(directory, 'app.mjs') - const definition = 'function untouched ( ) { return 1 }' - writeFileSync( - bundle, - `${definition}\nawait Promise.resolve()\nthrow new Error(untouched.toString())`, - ) - const worker = fork( - fileURLToPath(new URL('./stable-worker.ts', import.meta.url)), - { - cwd: fileURLToPath(new URL('../../../', import.meta.url)), - execArgv: ['--import=@swc-node/register/esm-register'], - env: { ...process.env, NODE_ENV: 'production' }, - stdio: ['ignore', 'ignore', 'pipe', 'ipc'], - }, - ) - let stderr = '' - worker.stderr?.on('data', (data: Buffer) => { - stderr += data.toString() - }) - let timeout: ReturnType | undefined - try { - const result = new Promise((resolve, reject) => { - worker.once('message', (message: WorkerResponse) => resolve(message)) - worker.once('error', reject) - worker.once('exit', (code) => { - reject(new Error(`Worker exited (${code}): ${stderr}`)) - }) - timeout = setTimeout(() => { - reject(new Error(`Worker timed out: ${stderr}`)) - }, 5_000) - }) - worker.send({ - kind: 'init', - mode: 'ssr', - caseId: 'shared-params', - bundle, - variant: 0, - }) - const response = await result - expect(response.kind).toBe('error') - if (response.kind === 'error') { - expect(response.message).toContain(`Error: ${definition}`) - } - } finally { - clearTimeout(timeout) - worker.kill() - unlinkSync(bundle) - rmdirSync(directory) - } -}) diff --git a/benchmarks/client-nav/link-performance/stable-worker.ts b/benchmarks/client-nav/link-performance/stable-worker.ts deleted file mode 100644 index d98679dc15..0000000000 --- a/benchmarks/client-nav/link-performance/stable-worker.ts +++ /dev/null @@ -1,112 +0,0 @@ -import { pathToFileURL } from 'node:url' -import { createClientScenario, createSsrScenario } from './scenario' -import type { LinkScenario } from './scenario' -import type { WorkerRequest, WorkerResponse } from './worker-protocol' -import type * as ClientApp from './src/client' -import type * as SsrApp from './src/ssr' - -const scenarios: Array = [] -const creationOrder: Array = [] -let closeWindow = () => {} - -function reply(response: WorkerResponse) { - if (!process.send) { - throw new Error('The Link sampling worker requires an IPC parent') - } - process.send(response) -} - -async function handle(request: WorkerRequest) { - if (request.kind === 'init') { - if (typeof process.threadCpuUsage !== 'function') { - throw new Error( - 'Stable sampling requires Node.js with process.threadCpuUsage', - ) - } - if (scenarios[request.variant]) { - throw new Error('A worker must only initialize each variant once') - } - let scenario: LinkScenario - const bundleUrl = pathToFileURL(request.bundle) - bundleUrl.searchParams.set('linkPerfVariant', String(request.variant)) - if (request.mode === 'client') { - const { window } = await import('../jsdom') - closeWindow = () => window.close() - const app: typeof ClientApp = await import(bundleUrl.href) - if (app.serverEnvironment !== false) { - throw new Error('Expected a production client bundle') - } - scenario = createClientScenario(app, request.caseId) - } else { - const app: typeof SsrApp = await import(bundleUrl.href) - if (app.serverEnvironment !== true) { - throw new Error('Expected a production SSR bundle') - } - scenario = createSsrScenario(app, request.caseId) - } - scenarios[request.variant] = scenario - creationOrder.push(scenario) - await scenario.setup() - const start = performance.now() - let iterations = 0 - do { - await scenario.batch() - iterations++ - } while (iterations < 100 || performance.now() - start < 2_000) - reply({ - kind: 'ready', - batchMs: (performance.now() - start) / iterations, - }) - return - } - if (request.kind === 'measure') { - const scenario = scenarios[request.variant] - if (!scenario) { - throw new Error('The sampling worker has not been initialized') - } - if (!Number.isInteger(request.iterations) || request.iterations < 1) { - throw new Error('Expected a positive batch count') - } - const cpuStart = process.threadCpuUsage() - const processStart = process.cpuUsage() - const start = performance.now() - for (let index = 0; index < request.iterations; index++) { - await scenario.batch() - } - const wallMs = performance.now() - start - const cpu = process.threadCpuUsage(cpuStart) - const processCpu = process.cpuUsage(processStart) - reply({ - kind: 'sample', - sample: { - iterations: request.iterations, - wallMs: wallMs / request.iterations, - cpuMs: (cpu.user + cpu.system) / 1_000 / request.iterations, - processCpuMs: - (processCpu.user + processCpu.system) / 1_000 / request.iterations, - }, - }) - return - } - try { - for (const scenario of creationOrder) { - scenario.check() - } - } finally { - for (const scenario of creationOrder.reverse()) { - scenario.teardown() - } - closeWindow() - } - reply({ kind: 'stopped' }) -} - -process.on('message', (request: WorkerRequest) => { - void handle(request).catch((error: unknown) => { - reply({ - kind: 'error', - message: - error instanceof Error ? error.stack || error.message : String(error), - }) - }) -}) diff --git a/benchmarks/client-nav/link-performance/staging.ts b/benchmarks/client-nav/link-performance/staging.ts deleted file mode 100644 index ac07d34c29..0000000000 --- a/benchmarks/client-nav/link-performance/staging.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { mkdirSync, mkdtempSync } from 'node:fs' -import { resolve } from 'node:path' -import { fileURLToPath } from 'node:url' - -export function createStagingDirectory() { - // SWC skips node_modules, leaving the emitted benchmark JavaScript intact. - const root = fileURLToPath(new URL('./node_modules/.cache/', import.meta.url)) - mkdirSync(root, { recursive: true }) - return mkdtempSync(resolve(root, 'link-performance-')) -} diff --git a/benchmarks/client-nav/link-performance/statistics.test.ts b/benchmarks/client-nav/link-performance/statistics.test.ts deleted file mode 100644 index 8f5f37413b..0000000000 --- a/benchmarks/client-nav/link-performance/statistics.test.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { expect, test } from 'vitest' -import { classify, mean, summarizeRatios } from './statistics' - -test('summarizes multiplicative paired changes across process replicas', () => { - const result = summarizeRatios([0.9, 0.9, 0.9, 0.9]) - expect(result.changePercent).toBeCloseTo(-10) - expect(result.low95).toBeCloseTo(-10) - expect(result.high95).toBeCloseTo(-10) - expect(result.replicas).toBe(4) -}) - -test('does not turn opposite noisy runs into a conclusive result', () => { - const result = summarizeRatios([0.9, 1.1, 0.95, 1.05]) - expect(result.low95).toBeLessThan(0) - expect(result.high95).toBeGreaterThan(0) - expect(classify(result, result)).toBe('inconclusive') -}) - -test('requires CPU and wall time to corroborate a direction', () => { - const slower = summarizeRatios([1.08, 1.09, 1.08, 1.09]) - const faster = summarizeRatios([0.9, 0.91, 0.9, 0.91]) - expect(classify(slower, slower)).toBe('slower') - expect(classify(faster, faster)).toBe('faster') - expect(classify(slower, faster)).toBe('inconclusive') - expect(classify(summarizeRatios([1, 1, 1]), summarizeRatios([1, 1, 1]))).toBe( - 'within-2%', - ) -}) - -test('rejects incomplete or invalid sampling data', () => { - expect(() => summarizeRatios([1])).toThrow() - expect(() => summarizeRatios([0, 1])).toThrow() - expect(() => summarizeRatios([NaN, 1])).toThrow() - expect(() => mean([])).toThrow() - expect(() => mean([Infinity])).toThrow() -}) diff --git a/benchmarks/client-nav/link-performance/statistics.ts b/benchmarks/client-nav/link-performance/statistics.ts deleted file mode 100644 index 469bdaf65a..0000000000 --- a/benchmarks/client-nav/link-performance/statistics.ts +++ /dev/null @@ -1,57 +0,0 @@ -const critical95 = [ - 12.7062, 4.3027, 3.1824, 2.7764, 2.5706, 2.4469, 2.3646, 2.306, 2.2622, - 2.2281, -] - -export function mean(values: ReadonlyArray) { - if (!values.length || values.some((value) => !Number.isFinite(value))) { - throw new Error('Expected finite, nonempty samples') - } - return values.reduce((sum, value) => sum + value, 0) / values.length -} - -export function summarizeRatios(ratios: ReadonlyArray) { - if ( - ratios.length < 2 || - ratios.length > 11 || - ratios.some((value) => value <= 0) - ) { - throw new Error('Expected 2-11 independent positive process-replica ratios') - } - const logs = ratios.map(Math.log) - const center = mean(logs) - const variance = - logs.reduce((sum, value) => sum + (value - center) ** 2, 0) / - (logs.length - 1) - // Replicas, not the many correlated batches inside a worker, are the samples. - const margin = - critical95[logs.length - 2]! * Math.sqrt(variance / logs.length) - const percent = (value: number) => (Math.exp(value) - 1) * 100 - return { - changePercent: percent(center), - low95: percent(center - margin), - high95: percent(center + margin), - replicas: ratios.length, - } -} - -export function classify( - cpu: ReturnType, - wall: ReturnType, -) { - if (cpu.low95 > 0 && wall.low95 > 0) { - return 'slower' - } - if (cpu.high95 < 0 && wall.high95 < 0) { - return 'faster' - } - if ( - cpu.low95 >= -2 && - cpu.high95 <= 2 && - wall.low95 >= -2 && - wall.high95 <= 2 - ) { - return 'within-2%' - } - return 'inconclusive' -} diff --git a/benchmarks/client-nav/link-performance/tsconfig.json b/benchmarks/client-nav/link-performance/tsconfig.json deleted file mode 100644 index fbf230c977..0000000000 --- a/benchmarks/client-nav/link-performance/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "extends": "../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "./**/*.ts", - "./**/*.tsx", - "../scenarios/harness.ts", - "../setup-helpers.ts", - "../vitest.setup.ts" - ] -} diff --git a/benchmarks/client-nav/link-performance/vite.client.config.ts b/benchmarks/client-nav/link-performance/vite.client.config.ts deleted file mode 100644 index 1cd45fc45e..0000000000 --- a/benchmarks/client-nav/link-performance/vite.client.config.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { createLinkPerformanceConfig } from './config' - -export default createLinkPerformanceConfig('client') diff --git a/benchmarks/client-nav/link-performance/vite.ssr.config.ts b/benchmarks/client-nav/link-performance/vite.ssr.config.ts deleted file mode 100644 index f59148eaf6..0000000000 --- a/benchmarks/client-nav/link-performance/vite.ssr.config.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { createLinkPerformanceConfig } from './config' - -export default createLinkPerformanceConfig('ssr') diff --git a/benchmarks/client-nav/link-performance/vitest.config.ts b/benchmarks/client-nav/link-performance/vitest.config.ts deleted file mode 100644 index f8454c819d..0000000000 --- a/benchmarks/client-nav/link-performance/vitest.config.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' - -export default defineConfig({ - root: fileURLToPath(new URL('.', import.meta.url)), - test: { - watch: false, - environment: 'node', - include: ['*.test.ts'], - }, -}) diff --git a/benchmarks/client-nav/link-performance/worker-protocol.ts b/benchmarks/client-nav/link-performance/worker-protocol.ts deleted file mode 100644 index 474858a529..0000000000 --- a/benchmarks/client-nav/link-performance/worker-protocol.ts +++ /dev/null @@ -1,28 +0,0 @@ -import type { LinkCaseId } from './cases' - -export type Mode = 'client' | 'ssr' -export type Variant = 0 | 1 - -export type WorkerRequest = - | { - kind: 'init' - mode: Mode - caseId: LinkCaseId - bundle: string - variant: Variant - } - | { kind: 'measure'; iterations: number; variant: Variant } - | { kind: 'stop' } - -export interface BlockSample { - wallMs: number - cpuMs: number - processCpuMs: number - iterations: number -} - -export type WorkerResponse = - | { kind: 'ready'; batchMs: number } - | { kind: 'sample'; sample: BlockSample } - | { kind: 'stopped' } - | { kind: 'error'; message: string } diff --git a/benchmarks/client-nav/package.json b/benchmarks/client-nav/package.json index 1f878adc67..76bb69387e 100644 --- a/benchmarks/client-nav/package.json +++ b/benchmarks/client-nav/package.json @@ -3,49 +3,44 @@ "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", + "build:react": "vite build --config ./react/vite.config.ts", + "build:solid": "vite build --config ./solid/vite.config.ts", + "build:vue": "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:perf": "NODE_ENV=production vitest bench --config ./vitest.config.ts", + "test:perf:react": "NODE_ENV=production vitest bench --config ./react/vite.config.ts ./react/speed.bench.ts", + "test:perf:solid": "NODE_ENV=production vitest bench --config ./solid/vite.config.ts ./solid/speed.bench.ts", + "test:perf:vue": "NODE_ENV=production vitest bench --config ./vue/vite.config.ts ./vue/speed.bench.ts", "test: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", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", "vue": "^3.5.16" }, "devDependencies": { "@platformatic/flame": "^1.6.0", - "@codspeed/vitest-plugin": "^6.0.1", - "@tanstack/router-plugin": "workspace:^", + "@codspeed/vitest-plugin": "^5.0.1", "@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:" + "typescript": "^5.7.2", + "vite": "^8.0.0", + "vite-plugin-solid": "3.0.0-next.3", + "vitest": "^4.0.17" }, "nx": { "targets": { @@ -57,25 +52,6 @@ "@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" } ] }, @@ -87,25 +63,6 @@ "@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" } ] }, @@ -117,24 +74,6 @@ "@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" } ] }, @@ -183,61 +122,9 @@ ] }, "test:types": { - "inputs": [ - "default", - "^production", - "{workspaceRoot}/eslint.config.js", - "{workspaceRoot}/benchmarks/cpu-simulation.ts", - "dependentTaskOutputs" - ], + "cache": false, "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" - } + "^build" ] } } diff --git a/benchmarks/client-nav/react/app.tsx b/benchmarks/client-nav/react/app.tsx index cad766e26c..d26aba6e91 100644 --- a/benchmarks/client-nav/react/app.tsx +++ b/benchmarks/client-nav/react/app.tsx @@ -14,130 +14,53 @@ import { createRoot } from 'react-dom/client' function runPerfSelectorComputation(seed: number) { let value = Math.trunc(seed) | 0 - for (let index = 0; index < 40; index++) { + for (let index = 0; index < 100; 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 -} +const selectors = Array.from({ length: 20 }, (_, index) => index) -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() { +function Params() { const params = useParams({ strict: false, select: (params) => runPerfSelectorComputation(Number(params.id ?? 0)), }) - - void runPerfSelectorComputation(params) + void params return null } -function RootSearchSubscriber() { +function Search() { const search = useSearch({ strict: false, - select: (search) => runPerfSelectorComputation(Number(search.page ?? 0)), + select: (search) => runPerfSelectorComputation(Number(search.id ?? 0)), }) - - void runPerfSelectorComputation(search) + void search return null } -function LinkPanel() { +function Links() { 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}` - } - -
- ) - })} - + + Link + ) } function Root() { return ( <> - {rootSelectors.map((selector) => ( - + {selectors.map((selector) => ( + ))} - {rootSelectors.map((selector) => ( - + {selectors.map((selector) => ( + + ))} + {selectors.map((selector) => ( + ))} - ) @@ -147,230 +70,19 @@ const rootRoute = createRootRoute({ component: Root, }) -const itemsRoute = createRoute({ +const route = 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, + path: '/$id', + component: () =>
, }) -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'], + initialEntries: ['/0'], }), scrollRestoration: true, - routeTree: rootRoute.addChildren([ - itemsRoute.addChildren([itemDetailsRoute]), - searchRoute, - contextRoute, - ]), + routeTree: rootRoute.addChildren([route]), }) const reactRoot = createRoot(container) diff --git a/benchmarks/client-nav/react/setup.ts b/benchmarks/client-nav/react/setup.ts index 11541383ec..bc51cdb53b 100644 --- a/benchmarks/client-nav/react/setup.ts +++ b/benchmarks/client-nav/react/setup.ts @@ -1,11 +1,8 @@ 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 +const { mountTestApp } = (await import(appModulePath)) as typeof App export function setup() { if (process.env.NODE_ENV !== 'production') { @@ -13,85 +10,40 @@ export function setup() { 'client-nav benchmark is running without NODE_ENV=production; React dev overhead will dominate results.', ) } - - let container: HTMLDivElement | undefined = undefined + let id = 0 let unmount: (() => void) | undefined = undefined + let container: HTMLDivElement | undefined = undefined let unsub = () => {} - let stepIndex = 0 let next: () => Promise = () => Promise.reject('Test not initialized') async function before() { - stepIndex = 0 + id = 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() - }) + let resolve: () => void = () => {} + unsub = router.subscribe('onRendered', () => resolve()) const navigate = (opts: NavigateOptions) => new Promise((resolveNext) => { - resolveRendered = resolveNext + resolve = 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() + const nextId = id++ + + return navigate({ + to: '/$id', + params: { id: nextId }, + // update search every 2 navigations, to still test them, but also measure the impact of granular re-rendering + search: { id: Math.floor(nextId / 2) }, + replace: true, + }) } + await router.load() } function after() { diff --git a/benchmarks/client-nav/react/speed.bench.ts b/benchmarks/client-nav/react/speed.bench.ts index 944f182734..fcc15b5fbc 100644 --- a/benchmarks/client-nav/react/speed.bench.ts +++ b/benchmarks/client-nav/react/speed.bench.ts @@ -1,19 +1,34 @@ -import { test } from 'vitest' +import { afterAll, beforeAll, bench, describe } from 'vitest' import { setup } from './setup' -test('client-nav', async ({ bench }) => { - const scenario = setup() +describe('client-nav', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, + * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. + * + * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, + * but it does support `beforeAll` and `afterAll`. + * + * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. + */ + + beforeAll(test.before) + afterAll(test.after) + + bench( 'client-side navigation loop (react)', - { beforeAll: scenario.before, afterAll: scenario.after }, async () => { for (let i = 0; i < 10; i++) { - await scenario.tick() + await test.tick() } }, - ).run({ - warmupIterations: 100, - time: 10_000, - }) + { + warmupIterations: 100, + time: 10_000, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/react/vite.config.ts b/benchmarks/client-nav/react/vite.config.ts index 7df3f80e71..90f5261644 100644 --- a/benchmarks/client-nav/react/vite.config.ts +++ b/benchmarks/client-nav/react/vite.config.ts @@ -1,18 +1,8 @@ -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(), @@ -29,11 +19,9 @@ export default defineConfig({ }, }, test: { - execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav (react)', watch: false, environment: 'jsdom', - setupFiles: [`${rootDir}vitest.setup.ts`], - benchmark: { include: ['react/speed.bench.ts'] }, + setupFiles: ['./vitest.setup.ts'], }, }) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/project.json b/benchmarks/client-nav/scenarios/async-pipeline/react/project.json deleted file mode 100644 index 44ab55ccfe..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/react/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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 deleted file mode 100644 index 130583b190..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/react/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index 65dab0781e..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/react/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-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 deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/react/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/src/main.tsx b/benchmarks/client-nav/scenarios/async-pipeline/react/src/main.tsx deleted file mode 100644 index cab86a1272..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/react/src/main.tsx +++ /dev/null @@ -1,39 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { RouterProvider, createRouter } from '@tanstack/react-router' -import { createRoot } from 'react-dom/client' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - 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 deleted file mode 100644 index 9c79bab826..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/react/src/routeTree.gen.ts +++ /dev/null @@ -1,140 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 1cc8566678..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/__root.tsx +++ /dev/null @@ -1,50 +0,0 @@ -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 deleted file mode 100644 index d644376b7b..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/ctx.$id.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index 5b6d70e744..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/index.tsx +++ /dev/null @@ -1,13 +0,0 @@ -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 deleted file mode 100644 index bc002c303f..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/nested.$id.tsx +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index 443f592373..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/nested.tsx +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 4839b0ca6d..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/slow.$id.tsx +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index 1d59cbb450..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/react/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/vite.config.ts b/benchmarks/client-nav/scenarios/async-pipeline/react/vite.config.ts deleted file mode 100644 index e36a5244b1..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/react/vite.config.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import react from '@vitejs/plugin-react' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'react', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav 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 deleted file mode 100644 index 02123309b2..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/shared.ts +++ /dev/null @@ -1,113 +0,0 @@ -/** - * 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 deleted file mode 100644 index 2fce426b1e..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/solid/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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 deleted file mode 100644 index 6a46971603..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/solid/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index acef710469..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/solid/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-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 deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/solid/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/main.tsx b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/main.tsx deleted file mode 100644 index 4c6d49f501..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/main.tsx +++ /dev/null @@ -1,36 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { render } from 'solid-js/web' -import { RouterProvider, createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - 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 deleted file mode 100644 index 27b9498b11..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,140 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 7d3647fee8..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/__root.tsx +++ /dev/null @@ -1,46 +0,0 @@ -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 deleted file mode 100644 index e757b57b9d..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/ctx.$id.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index 12907d440d..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/index.tsx +++ /dev/null @@ -1,13 +0,0 @@ -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 deleted file mode 100644 index 5518ccf498..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/nested.$id.tsx +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index fdc939dc95..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/nested.tsx +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 4c229407e1..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/slow.$id.tsx +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index 98d76ad6b8..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/solid/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "solid-js", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/vite.config.ts b/benchmarks/client-nav/scenarios/async-pipeline/solid/vite.config.ts deleted file mode 100644 index 214da8042e..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/solid/vite.config.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import solid from 'vite-plugin-solid' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'solid', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - solid({ hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - resolve: { - conditions: ['solid', 'browser'], - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav 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 deleted file mode 100644 index 911bb61e38..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/vue/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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 deleted file mode 100644 index 97b74b3892..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/vue/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index f0fd3e58df..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/vue/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-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 deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/vue/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/main.tsx b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/main.tsx deleted file mode 100644 index e1bfa5965f..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/main.tsx +++ /dev/null @@ -1,43 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import * as Vue from 'vue' -import { RouterProvider, createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - 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 deleted file mode 100644 index 66b9efd7aa..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,140 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index c477ab7e68..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/__root.tsx +++ /dev/null @@ -1,53 +0,0 @@ -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 deleted file mode 100644 index d995f1ff6c..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/ctx.$id.tsx +++ /dev/null @@ -1,32 +0,0 @@ -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 deleted file mode 100644 index 128e132190..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/index.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index bbeaaa7dd7..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/nested.$id.tsx +++ /dev/null @@ -1,21 +0,0 @@ -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 deleted file mode 100644 index 763657dfc6..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/nested.tsx +++ /dev/null @@ -1,26 +0,0 @@ -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 deleted file mode 100644 index c9afccba97..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/slow.$id.tsx +++ /dev/null @@ -1,21 +0,0 @@ -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 deleted file mode 100644 index 7786fc3da9..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/vue/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/vite.config.ts b/benchmarks/client-nav/scenarios/async-pipeline/vue/vite.config.ts deleted file mode 100644 index ce4fa7318a..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/vue/vite.config.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import vue from '@vitejs/plugin-vue' -import vueJsx from '@vitejs/plugin-vue-jsx' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'vue', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - vue(), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav 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 deleted file mode 100644 index e3e580911f..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/react/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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 deleted file mode 100644 index 130583b190..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/react/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index d6f2190be7..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/react/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-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 deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/react/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/control-flow/react/src/main.tsx b/benchmarks/client-nav/scenarios/control-flow/react/src/main.tsx deleted file mode 100644 index da9e63d293..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/react/src/main.tsx +++ /dev/null @@ -1,39 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { RouterProvider, createRouter } from '@tanstack/react-router' -import { createRoot } from 'react-dom/client' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - // 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 deleted file mode 100644 index 7b6db9b237..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/react/src/routeTree.gen.ts +++ /dev/null @@ -1,156 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 63d5feb901..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/react/src/routes/__root.tsx +++ /dev/null @@ -1,52 +0,0 @@ -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 deleted file mode 100644 index b11bb845bc..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/react/src/routes/broken.tsx +++ /dev/null @@ -1,20 +0,0 @@ -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 deleted file mode 100644 index aacba39384..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/react/src/routes/hop1.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index db31abe9f3..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/react/src/routes/hop2.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 24e856ea15..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/react/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 0c807bb2bc..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/react/src/routes/missing.$id.tsx +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 280f65835e..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/react/src/routes/target.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 1d59cbb450..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/react/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/control-flow/react/vite.config.ts b/benchmarks/client-nav/scenarios/control-flow/react/vite.config.ts deleted file mode 100644 index 1eefca0fc3..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/react/vite.config.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import react from '@vitejs/plugin-react' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'react', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav 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 deleted file mode 100644 index c4f368bee1..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/shared.ts +++ /dev/null @@ -1,91 +0,0 @@ -/** - * 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 deleted file mode 100644 index 2b5154d385..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/solid/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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 deleted file mode 100644 index 6a46971603..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/solid/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index d803d2a313..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/solid/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-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 deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/solid/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/src/main.tsx b/benchmarks/client-nav/scenarios/control-flow/solid/src/main.tsx deleted file mode 100644 index fa9d239418..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/solid/src/main.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { render } from 'solid-js/web' -import { RouterProvider, createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const unmount = render(() => , container) - - return { - router, - unmount, - } -} diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/control-flow/solid/src/routeTree.gen.ts deleted file mode 100644 index cd84f99d5d..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,156 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 1bce9e8a3e..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/__root.tsx +++ /dev/null @@ -1,52 +0,0 @@ -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 deleted file mode 100644 index 9931ef9c58..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/broken.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 1aedb481ec..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/hop1.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 91b601c516..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/hop2.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index cc46764de5..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 9c0493fb48..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/missing.$id.tsx +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 87de4e59a7..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/target.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 98d76ad6b8..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/solid/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "solid-js", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/vite.config.ts b/benchmarks/client-nav/scenarios/control-flow/solid/vite.config.ts deleted file mode 100644 index f4fa916154..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/solid/vite.config.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import solid from 'vite-plugin-solid' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'solid', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - solid({ hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - resolve: { - conditions: ['solid', 'browser'], - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav 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 deleted file mode 100644 index 7370687988..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/vue/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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 deleted file mode 100644 index 97b74b3892..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/vue/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index 8a019945c7..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/vue/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-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 deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/vue/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/src/main.tsx b/benchmarks/client-nav/scenarios/control-flow/vue/src/main.tsx deleted file mode 100644 index cae9b54f1d..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/vue/src/main.tsx +++ /dev/null @@ -1,41 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import * as Vue from 'vue' -import { RouterProvider, createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const component = - const app = Vue.createApp({ - render: () => component, - }) - - app.mount(container) - - return { - router, - unmount() { - app.unmount() - }, - } -} diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/control-flow/vue/src/routeTree.gen.ts deleted file mode 100644 index 6b53a6a203..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,156 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 9695c4b32d..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/__root.tsx +++ /dev/null @@ -1,57 +0,0 @@ -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 deleted file mode 100644 index c67fa2817e..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/broken.tsx +++ /dev/null @@ -1,21 +0,0 @@ -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 deleted file mode 100644 index ed00cefe3f..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/hop1.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index f6d4b1c1e0..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/hop2.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index f3ffc58610..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/index.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index 022ea656a6..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/missing.$id.tsx +++ /dev/null @@ -1,28 +0,0 @@ -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 deleted file mode 100644 index 4e22d0993a..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/target.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index 7786fc3da9..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/vue/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/vite.config.ts b/benchmarks/client-nav/scenarios/control-flow/vue/vite.config.ts deleted file mode 100644 index 3c2750d2a6..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/vue/vite.config.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import vue from '@vitejs/plugin-vue' -import vueJsx from '@vitejs/plugin-vue-jsx' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'vue', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - vue(), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav 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 deleted file mode 100644 index cf3c39c7e6..0000000000 --- a/benchmarks/client-nav/scenarios/harness.ts +++ /dev/null @@ -1,534 +0,0 @@ -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 deleted file mode 100644 index 1becf30fb9..0000000000 --- a/benchmarks/client-nav/scenarios/head/react/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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 deleted file mode 100644 index 1a28b0ca94..0000000000 --- a/benchmarks/client-nav/scenarios/head/react/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index d0d731a09f..0000000000 --- a/benchmarks/client-nav/scenarios/head/react/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-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 deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/head/react/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/head/react/src/main.tsx b/benchmarks/client-nav/scenarios/head/react/src/main.tsx deleted file mode 100644 index 5febd6f795..0000000000 --- a/benchmarks/client-nav/scenarios/head/react/src/main.tsx +++ /dev/null @@ -1,37 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { RouterProvider, createRouter } from '@tanstack/react-router' -import { createRoot } from 'react-dom/client' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const reactRoot = createRoot(container) - reactRoot.render() - - return { - router, - unmount() { - reactRoot.unmount() - }, - } -} diff --git a/benchmarks/client-nav/scenarios/head/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/head/react/src/routeTree.gen.ts deleted file mode 100644 index 88867d9190..0000000000 --- a/benchmarks/client-nav/scenarios/head/react/src/routeTree.gen.ts +++ /dev/null @@ -1,145 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 3d61dad0e9..0000000000 --- a/benchmarks/client-nav/scenarios/head/react/src/routes/__root.tsx +++ /dev/null @@ -1,59 +0,0 @@ -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 deleted file mode 100644 index 6f5b78d60e..0000000000 --- a/benchmarks/client-nav/scenarios/head/react/src/routes/articles.$id.tsx +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index 6ed1935ada..0000000000 --- a/benchmarks/client-nav/scenarios/head/react/src/routes/docs.$section.tsx +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index a2da216ddb..0000000000 --- a/benchmarks/client-nav/scenarios/head/react/src/routes/docs.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 6ac318452f..0000000000 --- a/benchmarks/client-nav/scenarios/head/react/src/routes/index.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index cd73902bff..0000000000 --- a/benchmarks/client-nav/scenarios/head/react/src/routes/settings.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 1d59cbb450..0000000000 --- a/benchmarks/client-nav/scenarios/head/react/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/head/react/vite.config.ts b/benchmarks/client-nav/scenarios/head/react/vite.config.ts deleted file mode 100644 index 7c8d6d4c15..0000000000 --- a/benchmarks/client-nav/scenarios/head/react/vite.config.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import react from '@vitejs/plugin-react' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'react', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav 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 deleted file mode 100644 index db185d602b..0000000000 --- a/benchmarks/client-nav/scenarios/head/shared.ts +++ /dev/null @@ -1,152 +0,0 @@ -/** - * 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 deleted file mode 100644 index 2575a19b89..0000000000 --- a/benchmarks/client-nav/scenarios/head/solid/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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 deleted file mode 100644 index 4ee924acff..0000000000 --- a/benchmarks/client-nav/scenarios/head/solid/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index ca156c950b..0000000000 --- a/benchmarks/client-nav/scenarios/head/solid/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-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 deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/head/solid/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/head/solid/src/main.tsx b/benchmarks/client-nav/scenarios/head/solid/src/main.tsx deleted file mode 100644 index fa9d239418..0000000000 --- a/benchmarks/client-nav/scenarios/head/solid/src/main.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { render } from 'solid-js/web' -import { RouterProvider, createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const unmount = render(() => , container) - - return { - router, - unmount, - } -} diff --git a/benchmarks/client-nav/scenarios/head/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/head/solid/src/routeTree.gen.ts deleted file mode 100644 index b6f217e527..0000000000 --- a/benchmarks/client-nav/scenarios/head/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,145 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 52ca7da373..0000000000 --- a/benchmarks/client-nav/scenarios/head/solid/src/routes/__root.tsx +++ /dev/null @@ -1,58 +0,0 @@ -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 deleted file mode 100644 index dab11ada18..0000000000 --- a/benchmarks/client-nav/scenarios/head/solid/src/routes/articles.$id.tsx +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index 7ab1123e7a..0000000000 --- a/benchmarks/client-nav/scenarios/head/solid/src/routes/docs.$section.tsx +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index 7f84b214d0..0000000000 --- a/benchmarks/client-nav/scenarios/head/solid/src/routes/docs.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 229eecc8c1..0000000000 --- a/benchmarks/client-nav/scenarios/head/solid/src/routes/index.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 88424caef3..0000000000 --- a/benchmarks/client-nav/scenarios/head/solid/src/routes/settings.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 98d76ad6b8..0000000000 --- a/benchmarks/client-nav/scenarios/head/solid/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "solid-js", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/head/solid/vite.config.ts b/benchmarks/client-nav/scenarios/head/solid/vite.config.ts deleted file mode 100644 index 986b2de2b0..0000000000 --- a/benchmarks/client-nav/scenarios/head/solid/vite.config.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import solid from 'vite-plugin-solid' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'solid', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - solid({ hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - resolve: { - conditions: ['solid', 'browser'], - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav 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 deleted file mode 100644 index 5ad7909d74..0000000000 --- a/benchmarks/client-nav/scenarios/head/vue/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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 deleted file mode 100644 index 3dd6bc95a5..0000000000 --- a/benchmarks/client-nav/scenarios/head/vue/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index d188a9dd7a..0000000000 --- a/benchmarks/client-nav/scenarios/head/vue/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-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 deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/head/vue/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/head/vue/src/main.tsx b/benchmarks/client-nav/scenarios/head/vue/src/main.tsx deleted file mode 100644 index cae9b54f1d..0000000000 --- a/benchmarks/client-nav/scenarios/head/vue/src/main.tsx +++ /dev/null @@ -1,41 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import * as Vue from 'vue' -import { RouterProvider, createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const component = - const app = Vue.createApp({ - render: () => component, - }) - - app.mount(container) - - return { - router, - unmount() { - app.unmount() - }, - } -} diff --git a/benchmarks/client-nav/scenarios/head/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/head/vue/src/routeTree.gen.ts deleted file mode 100644 index 161f99a65c..0000000000 --- a/benchmarks/client-nav/scenarios/head/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,145 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index ad87699fef..0000000000 --- a/benchmarks/client-nav/scenarios/head/vue/src/routes/__root.tsx +++ /dev/null @@ -1,58 +0,0 @@ -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 deleted file mode 100644 index 43a6fade58..0000000000 --- a/benchmarks/client-nav/scenarios/head/vue/src/routes/articles.$id.tsx +++ /dev/null @@ -1,21 +0,0 @@ -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 deleted file mode 100644 index ebb59d61a2..0000000000 --- a/benchmarks/client-nav/scenarios/head/vue/src/routes/docs.$section.tsx +++ /dev/null @@ -1,21 +0,0 @@ -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 deleted file mode 100644 index feabbc4d4a..0000000000 --- a/benchmarks/client-nav/scenarios/head/vue/src/routes/docs.tsx +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index 421478833f..0000000000 --- a/benchmarks/client-nav/scenarios/head/vue/src/routes/index.tsx +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index 1a519e16c2..0000000000 --- a/benchmarks/client-nav/scenarios/head/vue/src/routes/settings.tsx +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index 7786fc3da9..0000000000 --- a/benchmarks/client-nav/scenarios/head/vue/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/head/vue/vite.config.ts b/benchmarks/client-nav/scenarios/head/vue/vite.config.ts deleted file mode 100644 index bb1126d85f..0000000000 --- a/benchmarks/client-nav/scenarios/head/vue/vite.config.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import vue from '@vitejs/plugin-vue' -import vueJsx from '@vitejs/plugin-vue-jsx' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'vue', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - vue(), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav 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 deleted file mode 100644 index a2fe0001be..0000000000 --- a/benchmarks/client-nav/scenarios/history/react/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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 deleted file mode 100644 index c26b7ffd08..0000000000 --- a/benchmarks/client-nav/scenarios/history/react/setup.ts +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index 6ec7031857..0000000000 --- a/benchmarks/client-nav/scenarios/history/react/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-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 deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/history/react/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/history/react/src/main.tsx b/benchmarks/client-nav/scenarios/history/react/src/main.tsx deleted file mode 100644 index 5febd6f795..0000000000 --- a/benchmarks/client-nav/scenarios/history/react/src/main.tsx +++ /dev/null @@ -1,37 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { RouterProvider, createRouter } from '@tanstack/react-router' -import { createRoot } from 'react-dom/client' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const reactRoot = createRoot(container) - reactRoot.render() - - return { - router, - unmount() { - reactRoot.unmount() - }, - } -} diff --git a/benchmarks/client-nav/scenarios/history/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/history/react/src/routeTree.gen.ts deleted file mode 100644 index 21bb12ba35..0000000000 --- a/benchmarks/client-nav/scenarios/history/react/src/routeTree.gen.ts +++ /dev/null @@ -1,113 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 240d8719d4..0000000000 --- a/benchmarks/client-nav/scenarios/history/react/src/routes/__root.tsx +++ /dev/null @@ -1,66 +0,0 @@ -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 deleted file mode 100644 index 55094556a6..0000000000 --- a/benchmarks/client-nav/scenarios/history/react/src/routes/gallery.tsx +++ /dev/null @@ -1,13 +0,0 @@ -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 deleted file mode 100644 index 932a72f2ef..0000000000 --- a/benchmarks/client-nav/scenarios/history/react/src/routes/index.tsx +++ /dev/null @@ -1,13 +0,0 @@ -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 deleted file mode 100644 index b9c5e2f8d0..0000000000 --- a/benchmarks/client-nav/scenarios/history/react/src/routes/pages.$n.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 793b531c89..0000000000 --- a/benchmarks/client-nav/scenarios/history/react/src/routes/photos.$photoId.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 1d59cbb450..0000000000 --- a/benchmarks/client-nav/scenarios/history/react/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/history/react/vite.config.ts b/benchmarks/client-nav/scenarios/history/react/vite.config.ts deleted file mode 100644 index bdbde9c668..0000000000 --- a/benchmarks/client-nav/scenarios/history/react/vite.config.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import react from '@vitejs/plugin-react' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'react', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav 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 deleted file mode 100644 index be6096cea8..0000000000 --- a/benchmarks/client-nav/scenarios/history/shared.ts +++ /dev/null @@ -1,94 +0,0 @@ -/** - * 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 deleted file mode 100644 index 6f4bba1ca5..0000000000 --- a/benchmarks/client-nav/scenarios/history/solid/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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 deleted file mode 100644 index 4adf55d6df..0000000000 --- a/benchmarks/client-nav/scenarios/history/solid/setup.ts +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index 56af035b2b..0000000000 --- a/benchmarks/client-nav/scenarios/history/solid/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-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 deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/history/solid/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/history/solid/src/main.tsx b/benchmarks/client-nav/scenarios/history/solid/src/main.tsx deleted file mode 100644 index fa9d239418..0000000000 --- a/benchmarks/client-nav/scenarios/history/solid/src/main.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { render } from 'solid-js/web' -import { RouterProvider, createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const unmount = render(() => , container) - - return { - router, - unmount, - } -} diff --git a/benchmarks/client-nav/scenarios/history/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/history/solid/src/routeTree.gen.ts deleted file mode 100644 index af253f4a15..0000000000 --- a/benchmarks/client-nav/scenarios/history/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,113 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index edf7368929..0000000000 --- a/benchmarks/client-nav/scenarios/history/solid/src/routes/__root.tsx +++ /dev/null @@ -1,66 +0,0 @@ -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 deleted file mode 100644 index b72d1c6195..0000000000 --- a/benchmarks/client-nav/scenarios/history/solid/src/routes/gallery.tsx +++ /dev/null @@ -1,13 +0,0 @@ -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 deleted file mode 100644 index 44a0b8045a..0000000000 --- a/benchmarks/client-nav/scenarios/history/solid/src/routes/index.tsx +++ /dev/null @@ -1,13 +0,0 @@ -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 deleted file mode 100644 index 1def6674c6..0000000000 --- a/benchmarks/client-nav/scenarios/history/solid/src/routes/pages.$n.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index ab2fe06e3f..0000000000 --- a/benchmarks/client-nav/scenarios/history/solid/src/routes/photos.$photoId.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 98d76ad6b8..0000000000 --- a/benchmarks/client-nav/scenarios/history/solid/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "solid-js", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/history/solid/vite.config.ts b/benchmarks/client-nav/scenarios/history/solid/vite.config.ts deleted file mode 100644 index 4da589ff0e..0000000000 --- a/benchmarks/client-nav/scenarios/history/solid/vite.config.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import solid from 'vite-plugin-solid' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'solid', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - solid({ hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - resolve: { - conditions: ['solid', 'browser'], - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav 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 deleted file mode 100644 index 17fca887ca..0000000000 --- a/benchmarks/client-nav/scenarios/history/vue/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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 deleted file mode 100644 index df689964e4..0000000000 --- a/benchmarks/client-nav/scenarios/history/vue/setup.ts +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index 3d36ac4cfa..0000000000 --- a/benchmarks/client-nav/scenarios/history/vue/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-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 deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/history/vue/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/history/vue/src/main.tsx b/benchmarks/client-nav/scenarios/history/vue/src/main.tsx deleted file mode 100644 index cae9b54f1d..0000000000 --- a/benchmarks/client-nav/scenarios/history/vue/src/main.tsx +++ /dev/null @@ -1,41 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import * as Vue from 'vue' -import { RouterProvider, createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const component = - const app = Vue.createApp({ - render: () => component, - }) - - app.mount(container) - - return { - router, - unmount() { - app.unmount() - }, - } -} diff --git a/benchmarks/client-nav/scenarios/history/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/history/vue/src/routeTree.gen.ts deleted file mode 100644 index 519aef7c8f..0000000000 --- a/benchmarks/client-nav/scenarios/history/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,113 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 7f7dff159c..0000000000 --- a/benchmarks/client-nav/scenarios/history/vue/src/routes/__root.tsx +++ /dev/null @@ -1,69 +0,0 @@ -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 deleted file mode 100644 index 3a397b1843..0000000000 --- a/benchmarks/client-nav/scenarios/history/vue/src/routes/gallery.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index fbc5b957a7..0000000000 --- a/benchmarks/client-nav/scenarios/history/vue/src/routes/index.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 560e83ed29..0000000000 --- a/benchmarks/client-nav/scenarios/history/vue/src/routes/pages.$n.tsx +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index 186566fe72..0000000000 --- a/benchmarks/client-nav/scenarios/history/vue/src/routes/photos.$photoId.tsx +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index 7786fc3da9..0000000000 --- a/benchmarks/client-nav/scenarios/history/vue/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/history/vue/vite.config.ts b/benchmarks/client-nav/scenarios/history/vue/vite.config.ts deleted file mode 100644 index c5f1ca9807..0000000000 --- a/benchmarks/client-nav/scenarios/history/vue/vite.config.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import vue from '@vitejs/plugin-vue' -import vueJsx from '@vitejs/plugin-vue-jsx' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'vue', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - vue(), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav 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 deleted file mode 100644 index 950c870a1c..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/fixture.ts +++ /dev/null @@ -1,31 +0,0 @@ -export const ordinaryLinkCount = 192 -export const hashLinkCount = 8 -export const serverUrl = '/teams/team-7/items/item-42?view=summary' -export const clientUrl = `${serverUrl}#details` - -export interface Diagnostics { - beforeLoads: number - loaders: number - mounted: boolean - clicks: number - ordinaryRenders: number - hashRenders: number - countRenders: boolean -} - -export function createDiagnostics(countRenders = false): Diagnostics { - return { - beforeLoads: 0, - loaders: 0, - mounted: false, - clicks: 0, - ordinaryRenders: 0, - hashRenders: 0, - countRenders, - } -} - -export interface FixtureArtifact { - html: string - scripts: Array -} diff --git a/benchmarks/client-nav/scenarios/hydration/react/generate-fixture.mjs b/benchmarks/client-nav/scenarios/hydration/react/generate-fixture.mjs deleted file mode 100644 index fbc67c5a08..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/generate-fixture.mjs +++ /dev/null @@ -1,23 +0,0 @@ -import assert from 'node:assert/strict' -import { writeFile } from 'node:fs/promises' -import { JSDOM } from 'jsdom' - -if (process.env.NODE_ENV !== 'production') { - throw new Error('Generate the hydration fixture in production mode') -} -const { renderFixture } = await import('./dist/server/server.js') -const html = await renderFixture() -const dom = new JSDOM(html) -try { - const scriptElements = [...dom.window.document.querySelectorAll('script')] - assert.ok(scriptElements.length > 0) - assert.ok(scriptElements.every((script) => !script.src)) - const scripts = scriptElements.map((script) => script.textContent) - assert.ok(scripts.some((script) => script.includes('$_TSR'))) - await writeFile( - new URL('./dist/fixture.json', import.meta.url), - JSON.stringify({ html, scripts }), - ) -} finally { - dom.window.close() -} diff --git a/benchmarks/client-nav/scenarios/hydration/react/hydration.test.ts b/benchmarks/client-nav/scenarios/hydration/react/hydration.test.ts deleted file mode 100644 index 7e466cbaed..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/hydration.test.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { expect, test } from 'vitest' -import { hashLinkCount, ordinaryLinkCount } from './fixture' -import { setup } from './setup' -import { settleHydration } from './settle' - -const turn = () => new Promise((resolve) => setImmediate(resolve)) - -test('restores data and context into fresh DOMs and includes follow-up renders', async () => { - const scenario = setup({ countRenders: true }) - const schedulerTasks = new Set() - for (let iteration = 0; iteration < 3; iteration++) { - await scenario.before() - try { - expect(scenario.snapshot().diagnostics.mounted).toBe(false) - expect(scenario.snapshot().matches).toBeUndefined() - await scenario.run() - schedulerTasks.add(scenario.schedulerTasks()) - const completed = scenario.snapshot() - // Supports both main's extra Link update and the optimized snapshot. - expect([ordinaryLinkCount, ordinaryLinkCount * 2]).toContain( - completed.diagnostics.ordinaryRenders, - ) - expect(completed.diagnostics.hashRenders).toBeGreaterThanOrEqual( - hashLinkCount + hashLinkCount / 2, - ) - for (let index = 0; index < 4; index++) { - await turn() - } - expect(scenario.snapshot()).toEqual(completed) - await expect(scenario.run()).rejects.toThrow('newly prepared sample') - } finally { - await scenario.after() - } - } - // React yields on its pinned clock, never on wall time spent hydrating. - expect(schedulerTasks.size).toBe(1) -}) - -test('rejects an empty measurement and still releases its sample', async () => { - const scenario = setup() - await scenario.before() - await expect(scenario.after()).rejects.toThrow( - 'Hydration sample was not completed', - ) - await scenario.before() - try { - await scenario.run() - } finally { - await scenario.after() - } -}) - -test('waits for a commit and scheduler work lasting more than 100 turns', async () => { - let committed = false - const commit = (async () => { - for (let index = 0; index < 150; index++) { - await turn() - } - committed = true - })() - let remainingCallbacks = 150 - await settleHydration( - commit, - () => { - expect(committed).toBe(true) - return remainingCallbacks-- <= 0 - }, - () => 'delayed commit', - ) - expect(remainingCallbacks).toBeLessThan(0) -}) - -test('retains a watchdog for a commit that never completes', async () => { - await expect( - settleHydration( - new Promise(() => {}), - () => true, - () => 'commit pending', - 10, - ), - ).rejects.toThrow('Hydration did not settle within 10ms: commit pending') -}) - -test('retains a watchdog when scheduler work never becomes idle', async () => { - await expect( - settleHydration( - Promise.resolve(), - () => false, - () => 'callbacks pending', - 10, - ), - ).rejects.toThrow('Hydration did not settle within 10ms: callbacks pending') -}) diff --git a/benchmarks/client-nav/scenarios/hydration/react/project.json b/benchmarks/client-nav/scenarios/hydration/react/project.json deleted file mode 100644 index ca23838c0f..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-hydration-react", - "projectType": "application", - "targets": { - "build:client": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { "projects": ["@tanstack/react-router"], "target": "build" } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.server.config.ts && NODE_ENV=production node {projectRoot}/generate-fixture.mjs && NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:unit": { - "executor": "nx:run-commands", - "dependsOn": ["build:client"], - "options": { - "command": "vitest run --config ./scenarios/hydration/react/vite.config.ts", - "cwd": "benchmarks/client-nav" - } - }, - "test:perf": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": ["build:client"], - "options": { - "command": "NODE_ENV=production vitest bench --mode benchmark --run --config ./scenarios/hydration/react/vite.config.ts", - "cwd": "benchmarks/client-nav" - } - }, - "test:types:client": { - "executor": "nx:run-commands", - "dependsOn": [ - { "projects": ["@tanstack/react-router"], "target": "build" } - ], - "options": { "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" } - } - } -} diff --git a/benchmarks/client-nav/scenarios/hydration/react/settle.ts b/benchmarks/client-nav/scenarios/hydration/react/settle.ts deleted file mode 100644 index cc4c09a72d..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/settle.ts +++ /dev/null @@ -1,35 +0,0 @@ -const turn = () => new Promise((resolve) => setImmediate(resolve)) - -export async function settleHydration( - committed: Promise, - isIdle: () => boolean, - describeProgress: () => string, - timeoutMs = 60_000, -) { - let timeoutError: Error | undefined - let watchdog: ReturnType | undefined - const timeout = new Promise((_, reject) => { - watchdog = setTimeout(() => { - timeoutError = new Error( - `Hydration did not settle within ${timeoutMs}ms: ${describeProgress()}`, - ) - reject(timeoutError) - }, timeoutMs) - }) - try { - // Concurrent hydration can need many more scheduler turns under CPU - // instrumentation. Await its commit instead of limiting successful work - // to an arbitrary number of event-loop polls. - await Promise.race([committed, timeout]) - let idleTurns = 0 - while (idleTurns < 2) { - await turn() - if (timeoutError) { - throw timeoutError - } - idleTurns = isIdle() ? idleTurns + 1 : 0 - } - } finally { - clearTimeout(watchdog) - } -} diff --git a/benchmarks/client-nav/scenarios/hydration/react/setup.ts b/benchmarks/client-nav/scenarios/hydration/react/setup.ts deleted file mode 100644 index 7c588af3fd..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/setup.ts +++ /dev/null @@ -1,316 +0,0 @@ -import assert from 'node:assert/strict' -import { readFileSync } from 'node:fs' -import { fileURLToPath } from 'node:url' -import { Script } from 'node:vm' -import { JSDOM, VirtualConsole } from 'jsdom' -import { clientUrl, hashLinkCount, ordinaryLinkCount } from './fixture' -import { settleHydration } from './settle' -import type { FixtureArtifact } from './fixture' -import type * as Client from './src/client' - -type ClientApp = typeof Client -const turn = () => new Promise((resolve) => setImmediate(resolve)) - -// React's scheduler ends a time slice once performance.now() has advanced 5 ms. -// Under CodSpeed's CPU simulation the wall clock advances much further per -// instruction, by a runner-dependent factor, so real time turned identical -// samples into different numbers of yields, scheduler tasks and event-loop -// turns. With a frozen clock React yields only to paint after a commit, as on -// a fast host. 1 s is past React's initial 300 ms fallback throttle. Only the -// window's performance clock is pinned: Date.now(), which the Router uses for -// match timestamps, is unchanged. -const schedulerTime = 1_000 - -export function setup({ countRenders = false } = {}) { - // Compile once, outside measurement. Evaluation below creates fresh objects - // in each window's realm; neither the payload nor module state is reused. - const artifact: FixtureArtifact = JSON.parse( - readFileSync(new URL('./dist/fixture.json', import.meta.url), 'utf8'), - ) - const clientPath = new URL('./dist/client/client.js', import.meta.url) - const clientScript = new Script(readFileSync(clientPath, 'utf8'), { - filename: fileURLToPath(clientPath), - }) - const bootstrapScripts = artifact.scripts.map( - (source, index) => - new Script(source, { - filename: `hydration-bootstrap-${index}.js`, - }), - ) - let current: Awaited> | undefined - - async function prepare() { - const errors: Array = [] - const virtualConsole = new VirtualConsole() - virtualConsole.on('jsdomError', (error) => errors.push(String(error))) - virtualConsole.on('error', (...args) => - errors.push(args.map(String).join(' ')), - ) - const dom = new JSDOM(artifact.html, { - url: `http://localhost${clientUrl}`, - runScripts: 'outside-only', - virtualConsole, - }) - const immediates = new Set() - const scheduler = { tasks: 0 } - try { - Object.assign(dom.window, { - TextEncoder, - TextDecoder, - ReadableStream, - WritableStream, - TransformStream, - // Let React's production scheduler use the same task-turn primitive as - // the existing Node client benchmarks, without a real-delay timer. - setImmediate( - callback: (...args: Array) => void, - ...args: Array - ) { - scheduler.tasks++ - const handle = setImmediate(() => { - immediates.delete(handle) - callback(...args) - }) - immediates.add(handle) - return handle - }, - clearImmediate(handle: NodeJS.Immediate) { - immediates.delete(handle) - clearImmediate(handle) - }, - fetch() { - throw new Error('Hydration attempted a network request') - }, - scrollTo() {}, - }) - dom.window.performance.now = () => schedulerTime - const context = dom.getInternalVMContext() - // jsdom has no layout/scroll implementation; only hydration CPU is measured. - dom.window.HTMLElement.prototype.scrollIntoView = () => {} - clientScript.runInContext(context) - const app = (dom.window as unknown as { HydrationBenchmark: ClientApp }) - .HydrationBenchmark - assert.equal(app.serverEnvironment, false) - const anchors = Array.from(dom.window.document.querySelectorAll('a')) - const scriptElements = Array.from( - dom.window.document.querySelectorAll('script'), - ) - const executingScript = { current: null as HTMLScriptElement | null } - Object.defineProperty(dom.window.document, 'currentScript', { - configurable: true, - get: () => executingScript.current, - }) - assert.equal(anchors.length, ordinaryLinkCount + hashLinkCount) - const content = dom.window.document.getElementById('hydration-content') - assert.ok(content) - // Finish jsdom's initial document lifecycle before opening the measure. - await turn() - assert.equal(dom.window.document.readyState, 'complete') - assert.equal(app.ready(), false) - return { - dom, - context, - app, - anchors, - content, - scriptElements, - executingScript, - immediates, - scheduler, - errors, - started: false, - completed: false, - failed: false, - } - } catch (error) { - for (const handle of immediates) { - clearImmediate(handle) - } - dom.window.close() - throw error - } - } - - async function before() { - if (current) { - throw new Error('Previous hydration sample was not disposed') - } - current = await prepare() - } - - async function run() { - const sample = current - if (!sample || sample.started) { - throw new Error('Hydration requires a newly prepared sample') - } - sample.started = true - try { - // HTML parsing/module evaluation are already done. Payload execution, - // router initialization/restoration and React hydration are measured. - for (let index = 0; index < bootstrapScripts.length; index++) { - // SSR bootstrap scripts remove their own script element after running. - sample.executingScript.current = sample.scriptElements[index]! - try { - bootstrapScripts[index]!.runInContext(sample.context) - } finally { - sample.executingScript.current = null - } - } - await settleHydration( - sample.app.start(countRenders), - () => sample.immediates.size === 0, - () => { - const progress = sample.app.snapshot() - return JSON.stringify({ - diagnostics: progress.diagnostics, - errors: [...sample.errors, ...progress.errors], - restoredMatches: progress.matches?.length, - pendingSchedulerCallbacks: sample.immediates.size, - }) - }, - ) - if (sample.errors.length) { - throw new Error(sample.errors.join('\n')) - } - assert.ok( - sample.app.ready(), - 'Hydration committed without the expected active links', - ) - sample.completed = true - } catch (error) { - sample.failed = true - throw error - } - } - - function snapshot() { - if (!current) { - throw new Error('No hydration sample') - } - // Normalize realm prototypes only for untimed assertions. - return JSON.parse(JSON.stringify(current.app.snapshot())) as ReturnType< - ClientApp['snapshot'] - > - } - - function schedulerTasks() { - if (!current) { - throw new Error('No hydration sample') - } - return current.scheduler.tasks - } - - function validate() { - assert.ok(current?.started) - const { dom, anchors, content, errors } = current - const doc = dom.window.document - const result = snapshot() - assert.deepEqual(errors, []) - assert.deepEqual(result.errors, []) - assert.equal(result.diagnostics.beforeLoads, 0) - assert.equal(result.diagnostics.loaders, 0) - assert.equal(result.diagnostics.mounted, true) - assert.equal(result.location, clientUrl) - assert.equal(result.matches?.length, 3) - for (const match of result.matches) { - assert.equal(match.status, 'success') - assert.deepEqual(match.context.viewer, { - id: 'viewer-3', - name: 'Ada', - role: 'editor', - }) - } - assert.deepEqual(result.matches[1]!.context.team, { - id: 'team-7', - member: 'viewer-3', - }) - assert.deepEqual(result.matches[2]!.context.permissions, { edit: true }) - assert.deepEqual(result.matches[1]!.loaderData, { - title: 'Team team-7', - categories: ['open', 'closed'], - }) - const data = result.matches[2]!.loaderData as { - owner: string - selected: string - rows: Array<{ - id: string - label: string - details: { score: number; open: boolean } - }> - } - assert.equal(data.owner, 'viewer-3') - assert.equal(data.selected, 'item-42') - assert.equal(data.rows.length, ordinaryLinkCount) - assert.equal(doc.getElementById('hydration-content'), content) - assert.equal(doc.querySelectorAll('a').length, anchors.length) - assert.equal(doc.getElementById('viewer')?.textContent, 'Ada') - assert.equal(doc.getElementById('permission')?.textContent, 'Editable') - for (const anchor of anchors) { - assert.equal(doc.getElementById(anchor.id), anchor) - } - for (let index = 0; index < ordinaryLinkCount; index++) { - const anchor = doc.getElementById(`ordinary-item-${index}`)! - assert.equal( - anchor.getAttribute('href'), - `/teams/team-7/items/item-${index}?view=summary`, - ) - assert.equal(anchor.textContent, `Item ${index}`) - assert.equal( - anchor.getAttribute('data-status'), - index === 42 ? 'active' : null, - ) - assert.deepEqual(data.rows[index], { - id: `item-${index}`, - label: `Item ${index}`, - details: { score: index * 3, open: index % 2 === 0 }, - }) - } - for (let index = 0; index < hashLinkCount; index++) { - assert.equal( - doc.getElementById(`hash-${index}`)?.getAttribute('data-status'), - index % 2 === 0 ? 'active' : null, - ) - } - doc - .getElementById('interactive')! - .dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true })) - assert.equal( - current.app.snapshot().diagnostics.clicks, - result.diagnostics.clicks + 1, - ) - } - - async function after() { - const sample = current - if (!sample) { - return - } - try { - if (!sample.failed) { - assert.ok(sample.completed, 'Hydration sample was not completed') - validate() - } - } finally { - current = undefined - try { - sample.app.dispose() - // Unmount work and its scheduled effects stay outside the measure. - await turn() - await turn() - } finally { - for (const handle of sample.immediates) { - clearImmediate(handle) - } - sample.dom.window.close() - } - } - } - - return { - before, - run, - after, - snapshot, - schedulerTasks, - } -} diff --git a/benchmarks/client-nav/scenarios/hydration/react/speed.bench.ts b/benchmarks/client-nav/scenarios/hydration/react/speed.bench.ts deleted file mode 100644 index 643877760e..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { setup } from './setup' - -test('client-hydration', async ({ bench }) => { - const scenario = setup() - - await bench( - 'hydrate restored route state and mixed Links (react)', - { beforeEach: scenario.before, afterEach: scenario.after }, - async () => { - await scenario.run() - }, - ).run({ - time: 5000, - warmupTime: 1000, - warmupIterations: 20, - throws: true, - }) -}) diff --git a/benchmarks/client-nav/scenarios/hydration/react/src/app.tsx b/benchmarks/client-nav/scenarios/hydration/react/src/app.tsx deleted file mode 100644 index e9797f71fa..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/src/app.tsx +++ /dev/null @@ -1,216 +0,0 @@ -import { useEffect } from 'react' -import { - HeadContent, - Link, - Outlet, - Scripts, - createMemoryHistory, - createRootRoute, - createRoute, - createRouter, - useHydrated, -} from '@tanstack/react-router' -import { - clientUrl, - hashLinkCount, - ordinaryLinkCount, - serverUrl, -} from '../fixture' -import type { ReactNode } from 'react' -import type { Diagnostics } from '../fixture' - -export function createFixtureRouter( - server: boolean, - diagnostics: Diagnostics, - onHydrated: () => void = () => {}, -) { - function beforeLoad() { - diagnostics.beforeLoads++ - if (!server) { - throw new Error('Hydration reran beforeLoad instead of restoring context') - } - } - - function loader() { - diagnostics.loaders++ - if (!server) { - throw new Error('Hydration reran a loader instead of restoring data') - } - } - - const root = createRootRoute({ - beforeLoad: () => { - beforeLoad() - return { viewer: { id: 'viewer-3', name: 'Ada', role: 'editor' } } - }, - head: () => ({ - meta: [{ charSet: 'utf-8' }, { title: 'Hydration benchmark' }], - }), - shellComponent: Document, - }) - const team = createRoute({ - getParentRoute: () => root, - path: '/teams/$teamId', - beforeLoad: ({ context, params }) => { - beforeLoad() - return { team: { id: params.teamId, member: context.viewer.id } } - }, - loader: ({ context }) => { - loader() - return { - title: `Team ${context.team.id}`, - categories: ['open', 'closed'], - } - }, - component: Team, - }) - const items = createRoute({ - getParentRoute: () => team, - path: 'items/$itemId', - validateSearch: (search: Record) => ({ - view: search.view === 'details' ? 'details' : 'summary', - }), - beforeLoad: ({ context }) => { - beforeLoad() - return { permissions: { edit: context.viewer.role === 'editor' } } - }, - loader: ({ context, params }) => { - loader() - return { - selected: params.itemId, - owner: context.team.member, - rows: Array.from({ length: ordinaryLinkCount }, (_, index) => ({ - id: `item-${index}`, - label: `Item ${index}`, - details: { score: index * 3, open: index % 2 === 0 }, - })), - } - }, - component: Items, - }) - - function Document({ children }: { children: ReactNode }) { - return ( - - - - - - {children} - - - - ) - } - - function Team() { - const context = team.useRouteContext() - const data = team.useLoaderData() - return ( -
-

{data.title}

-

{context.viewer.name}

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

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

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

{data().title}

-

{context().viewer.name}

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

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

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

{detailMarker(params.id)}

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

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

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

{otherMarker}

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

{detailMarker(params().id)}

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

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

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

{otherMarker}

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

{detailMarker(params.value.id)}

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

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

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

{otherMarker}

-
- ) - }, -}) - -export const Route = createFileRoute('/other')({ - component: OtherPage, -}) diff --git a/benchmarks/client-nav/scenarios/link-churn/vue/tsconfig.json b/benchmarks/client-nav/scenarios/link-churn/vue/tsconfig.json deleted file mode 100644 index 7786fc3da9..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/vue/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/link-churn/vue/vite.config.ts b/benchmarks/client-nav/scenarios/link-churn/vue/vite.config.ts deleted file mode 100644 index 8f56734e04..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/vue/vite.config.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import vue from '@vitejs/plugin-vue' -import vueJsx from '@vitejs/plugin-vue-jsx' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'vue', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - vue(), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav link-churn (vue)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - }, -}) diff --git a/benchmarks/client-nav/scenarios/links/react/project.json b/benchmarks/client-nav/scenarios/links/react/project.json deleted file mode 100644 index 52c9df8a68..0000000000 --- a/benchmarks/client-nav/scenarios/links/react/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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 deleted file mode 100644 index 5409df903c..0000000000 --- a/benchmarks/client-nav/scenarios/links/react/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index 75f5f725d4..0000000000 --- a/benchmarks/client-nav/scenarios/links/react/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-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 deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/links/react/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/links/react/src/main.tsx b/benchmarks/client-nav/scenarios/links/react/src/main.tsx deleted file mode 100644 index 5febd6f795..0000000000 --- a/benchmarks/client-nav/scenarios/links/react/src/main.tsx +++ /dev/null @@ -1,37 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { RouterProvider, createRouter } from '@tanstack/react-router' -import { createRoot } from 'react-dom/client' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const reactRoot = createRoot(container) - reactRoot.render() - - return { - router, - unmount() { - reactRoot.unmount() - }, - } -} diff --git a/benchmarks/client-nav/scenarios/links/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/links/react/src/routeTree.gen.ts deleted file mode 100644 index 6e0c29ca88..0000000000 --- a/benchmarks/client-nav/scenarios/links/react/src/routeTree.gen.ts +++ /dev/null @@ -1,95 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 7a48510e8a..0000000000 --- a/benchmarks/client-nav/scenarios/links/react/src/routes/__root.tsx +++ /dev/null @@ -1,104 +0,0 @@ -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 deleted file mode 100644 index 0e4afc9297..0000000000 --- a/benchmarks/client-nav/scenarios/links/react/src/routes/about.tsx +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 2b8c83ebab..0000000000 --- a/benchmarks/client-nav/scenarios/links/react/src/routes/index.tsx +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 23121edb5c..0000000000 --- a/benchmarks/client-nav/scenarios/links/react/src/routes/items.$id.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 1d59cbb450..0000000000 --- a/benchmarks/client-nav/scenarios/links/react/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/links/react/vite.config.ts b/benchmarks/client-nav/scenarios/links/react/vite.config.ts deleted file mode 100644 index 69de10b5b7..0000000000 --- a/benchmarks/client-nav/scenarios/links/react/vite.config.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import react from '@vitejs/plugin-react' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'react', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav 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 deleted file mode 100644 index 6e75ea045c..0000000000 --- a/benchmarks/client-nav/scenarios/links/shared.ts +++ /dev/null @@ -1,133 +0,0 @@ -/** - * 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 deleted file mode 100644 index ef1dab4c50..0000000000 --- a/benchmarks/client-nav/scenarios/links/solid/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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 deleted file mode 100644 index 34270fe8a4..0000000000 --- a/benchmarks/client-nav/scenarios/links/solid/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index fc7f3e71e7..0000000000 --- a/benchmarks/client-nav/scenarios/links/solid/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-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 deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/links/solid/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/links/solid/src/main.tsx b/benchmarks/client-nav/scenarios/links/solid/src/main.tsx deleted file mode 100644 index fa9d239418..0000000000 --- a/benchmarks/client-nav/scenarios/links/solid/src/main.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { render } from 'solid-js/web' -import { RouterProvider, createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const unmount = render(() => , container) - - return { - router, - unmount, - } -} diff --git a/benchmarks/client-nav/scenarios/links/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/links/solid/src/routeTree.gen.ts deleted file mode 100644 index 0da70513e8..0000000000 --- a/benchmarks/client-nav/scenarios/links/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,95 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index a889a26854..0000000000 --- a/benchmarks/client-nav/scenarios/links/solid/src/routes/__root.tsx +++ /dev/null @@ -1,119 +0,0 @@ -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 deleted file mode 100644 index a2a71678b7..0000000000 --- a/benchmarks/client-nav/scenarios/links/solid/src/routes/about.tsx +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 72fbfe387a..0000000000 --- a/benchmarks/client-nav/scenarios/links/solid/src/routes/index.tsx +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 64d84f81f4..0000000000 --- a/benchmarks/client-nav/scenarios/links/solid/src/routes/items.$id.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 98d76ad6b8..0000000000 --- a/benchmarks/client-nav/scenarios/links/solid/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "solid-js", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/links/solid/vite.config.ts b/benchmarks/client-nav/scenarios/links/solid/vite.config.ts deleted file mode 100644 index e37342ffc3..0000000000 --- a/benchmarks/client-nav/scenarios/links/solid/vite.config.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import solid from 'vite-plugin-solid' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'solid', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - solid({ hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - resolve: { - conditions: ['solid', 'browser'], - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav 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 deleted file mode 100644 index fe1e68fad3..0000000000 --- a/benchmarks/client-nav/scenarios/links/vue/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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 deleted file mode 100644 index f70a154909..0000000000 --- a/benchmarks/client-nav/scenarios/links/vue/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index 2ace7a8409..0000000000 --- a/benchmarks/client-nav/scenarios/links/vue/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-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 deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/links/vue/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/links/vue/src/main.tsx b/benchmarks/client-nav/scenarios/links/vue/src/main.tsx deleted file mode 100644 index cae9b54f1d..0000000000 --- a/benchmarks/client-nav/scenarios/links/vue/src/main.tsx +++ /dev/null @@ -1,41 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import * as Vue from 'vue' -import { RouterProvider, createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const component = - const app = Vue.createApp({ - render: () => component, - }) - - app.mount(container) - - return { - router, - unmount() { - app.unmount() - }, - } -} diff --git a/benchmarks/client-nav/scenarios/links/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/links/vue/src/routeTree.gen.ts deleted file mode 100644 index 7d2b1e9bbb..0000000000 --- a/benchmarks/client-nav/scenarios/links/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,95 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 04f99677fd..0000000000 --- a/benchmarks/client-nav/scenarios/links/vue/src/routes/__root.tsx +++ /dev/null @@ -1,120 +0,0 @@ -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 deleted file mode 100644 index 5cc1473bff..0000000000 --- a/benchmarks/client-nav/scenarios/links/vue/src/routes/about.tsx +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index f04a9f5796..0000000000 --- a/benchmarks/client-nav/scenarios/links/vue/src/routes/index.tsx +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index 0dc5efa3d3..0000000000 --- a/benchmarks/client-nav/scenarios/links/vue/src/routes/items.$id.tsx +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index 7786fc3da9..0000000000 --- a/benchmarks/client-nav/scenarios/links/vue/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/links/vue/vite.config.ts b/benchmarks/client-nav/scenarios/links/vue/vite.config.ts deleted file mode 100644 index ad89a49d70..0000000000 --- a/benchmarks/client-nav/scenarios/links/vue/vite.config.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import vue from '@vitejs/plugin-vue' -import vueJsx from '@vitejs/plugin-vue-jsx' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'vue', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - vue(), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav 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 deleted file mode 100644 index d3dbe585d4..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/react/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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 deleted file mode 100644 index 130583b190..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/react/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index 8bcc53b88e..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/react/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-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 deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/react/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/loaders/react/src/main.tsx b/benchmarks/client-nav/scenarios/loaders/react/src/main.tsx deleted file mode 100644 index 5febd6f795..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/react/src/main.tsx +++ /dev/null @@ -1,37 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { RouterProvider, createRouter } from '@tanstack/react-router' -import { createRoot } from 'react-dom/client' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const reactRoot = createRoot(container) - reactRoot.render() - - return { - router, - unmount() { - reactRoot.unmount() - }, - } -} diff --git a/benchmarks/client-nav/scenarios/loaders/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/loaders/react/src/routeTree.gen.ts deleted file mode 100644 index 35908a225f..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/react/src/routeTree.gen.ts +++ /dev/null @@ -1,113 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 6309763cf3..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/react/src/routes/__root.tsx +++ /dev/null @@ -1,70 +0,0 @@ -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 deleted file mode 100644 index 9b954185cc..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/react/src/routes/cached.$id.tsx +++ /dev/null @@ -1,55 +0,0 @@ -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 deleted file mode 100644 index 92afe04a21..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/react/src/routes/deps.tsx +++ /dev/null @@ -1,65 +0,0 @@ -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 deleted file mode 100644 index fb7cbf2f00..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/react/src/routes/fresh.$id.tsx +++ /dev/null @@ -1,55 +0,0 @@ -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 deleted file mode 100644 index 9203c00841..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/react/src/routes/index.tsx +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 1d59cbb450..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/react/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/loaders/react/vite.config.ts b/benchmarks/client-nav/scenarios/loaders/react/vite.config.ts deleted file mode 100644 index 818b224130..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/react/vite.config.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import react from '@vitejs/plugin-react' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'react', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav 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 deleted file mode 100644 index f744246160..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/shared.ts +++ /dev/null @@ -1,134 +0,0 @@ -/** - * 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 deleted file mode 100644 index 071e6bc385..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/solid/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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 deleted file mode 100644 index 6a46971603..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/solid/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index 953a17b31a..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/solid/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-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 deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/solid/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/loaders/solid/src/main.tsx b/benchmarks/client-nav/scenarios/loaders/solid/src/main.tsx deleted file mode 100644 index fa9d239418..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/solid/src/main.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { render } from 'solid-js/web' -import { RouterProvider, createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const unmount = render(() => , container) - - return { - router, - unmount, - } -} diff --git a/benchmarks/client-nav/scenarios/loaders/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/loaders/solid/src/routeTree.gen.ts deleted file mode 100644 index fa5d032141..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,113 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 30350f7907..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/solid/src/routes/__root.tsx +++ /dev/null @@ -1,66 +0,0 @@ -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 deleted file mode 100644 index aab6be74dc..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/solid/src/routes/cached.$id.tsx +++ /dev/null @@ -1,62 +0,0 @@ -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 deleted file mode 100644 index 2f23f2d3da..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/solid/src/routes/deps.tsx +++ /dev/null @@ -1,72 +0,0 @@ -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 deleted file mode 100644 index acd6a9aa27..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/solid/src/routes/fresh.$id.tsx +++ /dev/null @@ -1,62 +0,0 @@ -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 deleted file mode 100644 index 7287d47d0a..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/solid/src/routes/index.tsx +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 98d76ad6b8..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/solid/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "solid-js", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/loaders/solid/vite.config.ts b/benchmarks/client-nav/scenarios/loaders/solid/vite.config.ts deleted file mode 100644 index 90584d3b7e..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/solid/vite.config.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import solid from 'vite-plugin-solid' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'solid', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - solid({ hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - resolve: { - conditions: ['solid', 'browser'], - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav 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 deleted file mode 100644 index 69bd95837d..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/vue/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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 deleted file mode 100644 index 97b74b3892..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/vue/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index 1ae2f89a56..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/vue/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-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 deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/vue/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/loaders/vue/src/main.tsx b/benchmarks/client-nav/scenarios/loaders/vue/src/main.tsx deleted file mode 100644 index cae9b54f1d..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/vue/src/main.tsx +++ /dev/null @@ -1,41 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import * as Vue from 'vue' -import { RouterProvider, createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const component = - const app = Vue.createApp({ - render: () => component, - }) - - app.mount(container) - - return { - router, - unmount() { - app.unmount() - }, - } -} diff --git a/benchmarks/client-nav/scenarios/loaders/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/loaders/vue/src/routeTree.gen.ts deleted file mode 100644 index 10cb8f2aca..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,113 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index b9102a92c4..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/vue/src/routes/__root.tsx +++ /dev/null @@ -1,69 +0,0 @@ -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 deleted file mode 100644 index a426e35765..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/vue/src/routes/cached.$id.tsx +++ /dev/null @@ -1,68 +0,0 @@ -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 deleted file mode 100644 index f987d15d34..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/vue/src/routes/deps.tsx +++ /dev/null @@ -1,78 +0,0 @@ -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 deleted file mode 100644 index 64eec85cfa..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/vue/src/routes/fresh.$id.tsx +++ /dev/null @@ -1,68 +0,0 @@ -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 deleted file mode 100644 index c9724c90a4..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/vue/src/routes/index.tsx +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index 7786fc3da9..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/vue/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/loaders/vue/vite.config.ts b/benchmarks/client-nav/scenarios/loaders/vue/vite.config.ts deleted file mode 100644 index ecf4cce139..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/vue/vite.config.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import vue from '@vitejs/plugin-vue' -import vueJsx from '@vitejs/plugin-vue-jsx' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'vue', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - vue(), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav 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 deleted file mode 100644 index 61839943b3..0000000000 --- a/benchmarks/client-nav/scenarios/mount/react/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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 deleted file mode 100644 index ed0426c696..0000000000 --- a/benchmarks/client-nav/scenarios/mount/react/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index 6c3a64b026..0000000000 --- a/benchmarks/client-nav/scenarios/mount/react/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-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 deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/mount/react/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/mount/react/src/main.tsx b/benchmarks/client-nav/scenarios/mount/react/src/main.tsx deleted file mode 100644 index 4e45ed7ef3..0000000000 --- a/benchmarks/client-nav/scenarios/mount/react/src/main.tsx +++ /dev/null @@ -1,38 +0,0 @@ -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 deleted file mode 100644 index f9b7e5c268..0000000000 --- a/benchmarks/client-nav/scenarios/mount/react/src/routeTree.gen.ts +++ /dev/null @@ -1,264 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 0deab171d8..0000000000 --- a/benchmarks/client-nav/scenarios/mount/react/src/routes/__root.tsx +++ /dev/null @@ -1,41 +0,0 @@ -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 deleted file mode 100644 index 3fedde283b..0000000000 --- a/benchmarks/client-nav/scenarios/mount/react/src/routes/about.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index f995d95d94..0000000000 --- a/benchmarks/client-nav/scenarios/mount/react/src/routes/blog.$slug.tsx +++ /dev/null @@ -1,13 +0,0 @@ -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 deleted file mode 100644 index 437187eb4f..0000000000 --- a/benchmarks/client-nav/scenarios/mount/react/src/routes/blog.index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index ab4fbeb482..0000000000 --- a/benchmarks/client-nav/scenarios/mount/react/src/routes/blog.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index dbc99d8f66..0000000000 --- a/benchmarks/client-nav/scenarios/mount/react/src/routes/index.tsx +++ /dev/null @@ -1,22 +0,0 @@ -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 deleted file mode 100644 index faba50fc72..0000000000 --- a/benchmarks/client-nav/scenarios/mount/react/src/routes/search.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 1f46d9d885..0000000000 --- a/benchmarks/client-nav/scenarios/mount/react/src/routes/settings.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 7b729a3dca..0000000000 --- a/benchmarks/client-nav/scenarios/mount/react/src/routes/shop.$productId.tsx +++ /dev/null @@ -1,13 +0,0 @@ -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 deleted file mode 100644 index dbca94357a..0000000000 --- a/benchmarks/client-nav/scenarios/mount/react/src/routes/shop.index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 5243d7bb0e..0000000000 --- a/benchmarks/client-nav/scenarios/mount/react/src/routes/shop.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 1d59cbb450..0000000000 --- a/benchmarks/client-nav/scenarios/mount/react/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/mount/react/vite.config.ts b/benchmarks/client-nav/scenarios/mount/react/vite.config.ts deleted file mode 100644 index e197d33a9e..0000000000 --- a/benchmarks/client-nav/scenarios/mount/react/vite.config.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import react from '@vitejs/plugin-react' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'react', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav 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 deleted file mode 100644 index a8f3d2c7bd..0000000000 --- a/benchmarks/client-nav/scenarios/mount/shared.ts +++ /dev/null @@ -1,75 +0,0 @@ -/** - * 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 deleted file mode 100644 index 4349570654..0000000000 --- a/benchmarks/client-nav/scenarios/mount/solid/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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 deleted file mode 100644 index 810ea38c91..0000000000 --- a/benchmarks/client-nav/scenarios/mount/solid/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index 236f875f57..0000000000 --- a/benchmarks/client-nav/scenarios/mount/solid/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-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 deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/mount/solid/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/mount/solid/src/main.tsx b/benchmarks/client-nav/scenarios/mount/solid/src/main.tsx deleted file mode 100644 index 2586872f5c..0000000000 --- a/benchmarks/client-nav/scenarios/mount/solid/src/main.tsx +++ /dev/null @@ -1,37 +0,0 @@ -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 deleted file mode 100644 index 30247636dd..0000000000 --- a/benchmarks/client-nav/scenarios/mount/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,264 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index f5c3be2641..0000000000 --- a/benchmarks/client-nav/scenarios/mount/solid/src/routes/__root.tsx +++ /dev/null @@ -1,41 +0,0 @@ -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 deleted file mode 100644 index f74d85aa06..0000000000 --- a/benchmarks/client-nav/scenarios/mount/solid/src/routes/about.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 82caee757a..0000000000 --- a/benchmarks/client-nav/scenarios/mount/solid/src/routes/blog.$slug.tsx +++ /dev/null @@ -1,13 +0,0 @@ -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 deleted file mode 100644 index 8e75108aca..0000000000 --- a/benchmarks/client-nav/scenarios/mount/solid/src/routes/blog.index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 1e2cfbd019..0000000000 --- a/benchmarks/client-nav/scenarios/mount/solid/src/routes/blog.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 30665ba224..0000000000 --- a/benchmarks/client-nav/scenarios/mount/solid/src/routes/index.tsx +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 3f8b2d9dd7..0000000000 --- a/benchmarks/client-nav/scenarios/mount/solid/src/routes/search.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index c6b95424d9..0000000000 --- a/benchmarks/client-nav/scenarios/mount/solid/src/routes/settings.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 71b0411d6b..0000000000 --- a/benchmarks/client-nav/scenarios/mount/solid/src/routes/shop.$productId.tsx +++ /dev/null @@ -1,13 +0,0 @@ -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 deleted file mode 100644 index e33c8779f9..0000000000 --- a/benchmarks/client-nav/scenarios/mount/solid/src/routes/shop.index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index ff2ca78653..0000000000 --- a/benchmarks/client-nav/scenarios/mount/solid/src/routes/shop.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 98d76ad6b8..0000000000 --- a/benchmarks/client-nav/scenarios/mount/solid/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "solid-js", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/mount/solid/vite.config.ts b/benchmarks/client-nav/scenarios/mount/solid/vite.config.ts deleted file mode 100644 index 5b586dd128..0000000000 --- a/benchmarks/client-nav/scenarios/mount/solid/vite.config.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import solid from 'vite-plugin-solid' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'solid', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - solid({ hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - resolve: { - conditions: ['solid', 'browser'], - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav 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 deleted file mode 100644 index f2dbd10440..0000000000 --- a/benchmarks/client-nav/scenarios/mount/vue/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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 deleted file mode 100644 index 3976e71c51..0000000000 --- a/benchmarks/client-nav/scenarios/mount/vue/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index d9268ba91b..0000000000 --- a/benchmarks/client-nav/scenarios/mount/vue/speed.bench.ts +++ /dev/null @@ -1,15 +0,0 @@ -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 deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/mount/vue/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/mount/vue/src/main.tsx b/benchmarks/client-nav/scenarios/mount/vue/src/main.tsx deleted file mode 100644 index fc493c10a5..0000000000 --- a/benchmarks/client-nav/scenarios/mount/vue/src/main.tsx +++ /dev/null @@ -1,42 +0,0 @@ -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 deleted file mode 100644 index cd27c917e1..0000000000 --- a/benchmarks/client-nav/scenarios/mount/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,264 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 5c2b7b52d0..0000000000 --- a/benchmarks/client-nav/scenarios/mount/vue/src/routes/__root.tsx +++ /dev/null @@ -1,44 +0,0 @@ -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 deleted file mode 100644 index 254ecca29c..0000000000 --- a/benchmarks/client-nav/scenarios/mount/vue/src/routes/about.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index 3b2e855a6e..0000000000 --- a/benchmarks/client-nav/scenarios/mount/vue/src/routes/blog.$slug.tsx +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index d3c2bd0305..0000000000 --- a/benchmarks/client-nav/scenarios/mount/vue/src/routes/blog.index.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index fe9532cc6f..0000000000 --- a/benchmarks/client-nav/scenarios/mount/vue/src/routes/blog.tsx +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index b0be4d78bb..0000000000 --- a/benchmarks/client-nav/scenarios/mount/vue/src/routes/index.tsx +++ /dev/null @@ -1,27 +0,0 @@ -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 deleted file mode 100644 index 09fdb29c1e..0000000000 --- a/benchmarks/client-nav/scenarios/mount/vue/src/routes/search.tsx +++ /dev/null @@ -1,21 +0,0 @@ -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 deleted file mode 100644 index 3fc0485606..0000000000 --- a/benchmarks/client-nav/scenarios/mount/vue/src/routes/settings.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index 897559599a..0000000000 --- a/benchmarks/client-nav/scenarios/mount/vue/src/routes/shop.$productId.tsx +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index 1040520f03..0000000000 --- a/benchmarks/client-nav/scenarios/mount/vue/src/routes/shop.index.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index 184807cfa0..0000000000 --- a/benchmarks/client-nav/scenarios/mount/vue/src/routes/shop.tsx +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index 7786fc3da9..0000000000 --- a/benchmarks/client-nav/scenarios/mount/vue/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/mount/vue/vite.config.ts b/benchmarks/client-nav/scenarios/mount/vue/vite.config.ts deleted file mode 100644 index 8d4005f339..0000000000 --- a/benchmarks/client-nav/scenarios/mount/vue/vite.config.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import vue from '@vitejs/plugin-vue' -import vueJsx from '@vitejs/plugin-vue-jsx' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'vue', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - vue(), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav 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 deleted file mode 100644 index 800f8af9a8..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/react/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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 deleted file mode 100644 index 130583b190..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/react/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index fa5809c1fd..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/react/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-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 deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/react/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/src/main.tsx b/benchmarks/client-nav/scenarios/nested-params/react/src/main.tsx deleted file mode 100644 index 5febd6f795..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/react/src/main.tsx +++ /dev/null @@ -1,37 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { RouterProvider, createRouter } from '@tanstack/react-router' -import { createRoot } from 'react-dom/client' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const reactRoot = createRoot(container) - reactRoot.render() - - return { - router, - unmount() { - reactRoot.unmount() - }, - } -} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/nested-params/react/src/routeTree.gen.ts deleted file mode 100644 index 95d4b46623..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/react/src/routeTree.gen.ts +++ /dev/null @@ -1,291 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index ef2c7b1b18..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/__root.tsx +++ /dev/null @@ -1,50 +0,0 @@ -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 deleted file mode 100644 index 24e856ea15..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 9789e28040..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.$e.$f.$g.$h.tsx +++ /dev/null @@ -1,63 +0,0 @@ -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 deleted file mode 100644 index 650b32ce96..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.$e.$f.$g.tsx +++ /dev/null @@ -1,51 +0,0 @@ -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 deleted file mode 100644 index ca18e3ccd2..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.$e.$f.tsx +++ /dev/null @@ -1,51 +0,0 @@ -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 deleted file mode 100644 index 782c1808c7..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.$e.tsx +++ /dev/null @@ -1,51 +0,0 @@ -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 deleted file mode 100644 index a874bbcb63..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.tsx +++ /dev/null @@ -1,55 +0,0 @@ -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 deleted file mode 100644 index 94aba79453..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.tsx +++ /dev/null @@ -1,51 +0,0 @@ -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 deleted file mode 100644 index 1960b68276..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.tsx +++ /dev/null @@ -1,51 +0,0 @@ -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 deleted file mode 100644 index 85d1de6f68..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.tsx +++ /dev/null @@ -1,51 +0,0 @@ -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 deleted file mode 100644 index 1d59cbb450..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/react/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/vite.config.ts b/benchmarks/client-nav/scenarios/nested-params/react/vite.config.ts deleted file mode 100644 index a99060bf1c..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/react/vite.config.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import react from '@vitejs/plugin-react' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'react', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav 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 deleted file mode 100644 index 06c968bb18..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/shared.ts +++ /dev/null @@ -1,143 +0,0 @@ -/** - * 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 deleted file mode 100644 index eb0b91bd6c..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/solid/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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 deleted file mode 100644 index 6a46971603..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/solid/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index 2c64d9a221..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/solid/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-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 deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/solid/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/src/main.tsx b/benchmarks/client-nav/scenarios/nested-params/solid/src/main.tsx deleted file mode 100644 index fa9d239418..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/solid/src/main.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { render } from 'solid-js/web' -import { RouterProvider, createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const unmount = render(() => , container) - - return { - router, - unmount, - } -} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/nested-params/solid/src/routeTree.gen.ts deleted file mode 100644 index 9065c9294f..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,291 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 6fe7ab3e3d..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/__root.tsx +++ /dev/null @@ -1,50 +0,0 @@ -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 deleted file mode 100644 index cc46764de5..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 7dc55db0e4..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.$e.$f.$g.$h.tsx +++ /dev/null @@ -1,72 +0,0 @@ -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 deleted file mode 100644 index d9c6c9429b..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.$e.$f.$g.tsx +++ /dev/null @@ -1,60 +0,0 @@ -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 deleted file mode 100644 index 010f89bc4d..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.$e.$f.tsx +++ /dev/null @@ -1,60 +0,0 @@ -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 deleted file mode 100644 index 08c107f0c6..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.$e.tsx +++ /dev/null @@ -1,60 +0,0 @@ -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 deleted file mode 100644 index 1b64edd58b..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.tsx +++ /dev/null @@ -1,64 +0,0 @@ -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 deleted file mode 100644 index e509ea82c6..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.tsx +++ /dev/null @@ -1,60 +0,0 @@ -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 deleted file mode 100644 index ada853b845..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.tsx +++ /dev/null @@ -1,60 +0,0 @@ -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 deleted file mode 100644 index 5ecf004fae..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.tsx +++ /dev/null @@ -1,60 +0,0 @@ -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 deleted file mode 100644 index 98d76ad6b8..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/solid/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "solid-js", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/vite.config.ts b/benchmarks/client-nav/scenarios/nested-params/solid/vite.config.ts deleted file mode 100644 index 9897e2c199..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/solid/vite.config.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import solid from 'vite-plugin-solid' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'solid', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - solid({ hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - resolve: { - conditions: ['solid', 'browser'], - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav 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 deleted file mode 100644 index 83c234382c..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/vue/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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 deleted file mode 100644 index 97b74b3892..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/vue/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index bd3e82e070..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/vue/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-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 deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/vue/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/src/main.tsx b/benchmarks/client-nav/scenarios/nested-params/vue/src/main.tsx deleted file mode 100644 index cae9b54f1d..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/vue/src/main.tsx +++ /dev/null @@ -1,41 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import * as Vue from 'vue' -import { RouterProvider, createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const component = - const app = Vue.createApp({ - render: () => component, - }) - - app.mount(container) - - return { - router, - unmount() { - app.unmount() - }, - } -} diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/nested-params/vue/src/routeTree.gen.ts deleted file mode 100644 index a7d1049b49..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,291 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 28dd4e847a..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/__root.tsx +++ /dev/null @@ -1,53 +0,0 @@ -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 deleted file mode 100644 index f3ffc58610..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/index.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index 756c31e1a9..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.$e.$f.$g.$h.tsx +++ /dev/null @@ -1,86 +0,0 @@ -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 deleted file mode 100644 index d6b9ccde83..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.$e.$f.$g.tsx +++ /dev/null @@ -1,74 +0,0 @@ -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 deleted file mode 100644 index 76ed24904c..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.$e.$f.tsx +++ /dev/null @@ -1,74 +0,0 @@ -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 deleted file mode 100644 index e24d3dc373..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.$e.tsx +++ /dev/null @@ -1,74 +0,0 @@ -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 deleted file mode 100644 index 7785638ee7..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.tsx +++ /dev/null @@ -1,83 +0,0 @@ -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 deleted file mode 100644 index 0d0adc65ff..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.tsx +++ /dev/null @@ -1,74 +0,0 @@ -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 deleted file mode 100644 index f013d865af..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.tsx +++ /dev/null @@ -1,74 +0,0 @@ -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 deleted file mode 100644 index d5764c0985..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.tsx +++ /dev/null @@ -1,74 +0,0 @@ -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 deleted file mode 100644 index 7786fc3da9..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/vue/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/vite.config.ts b/benchmarks/client-nav/scenarios/nested-params/vue/vite.config.ts deleted file mode 100644 index 0d74eb7a7c..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/vue/vite.config.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import vue from '@vitejs/plugin-vue' -import vueJsx from '@vitejs/plugin-vue-jsx' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'vue', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - vue(), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav 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 deleted file mode 100644 index f095228746..0000000000 --- a/benchmarks/client-nav/scenarios/preload/react/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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 deleted file mode 100644 index 5409df903c..0000000000 --- a/benchmarks/client-nav/scenarios/preload/react/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index 5c210b2fd7..0000000000 --- a/benchmarks/client-nav/scenarios/preload/react/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-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 deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/preload/react/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/preload/react/src/main.tsx b/benchmarks/client-nav/scenarios/preload/react/src/main.tsx deleted file mode 100644 index 395867f674..0000000000 --- a/benchmarks/client-nav/scenarios/preload/react/src/main.tsx +++ /dev/null @@ -1,40 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { RouterProvider, createRouter } from '@tanstack/react-router' -import { createRoot } from 'react-dom/client' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - 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 deleted file mode 100644 index 20619341c0..0000000000 --- a/benchmarks/client-nav/scenarios/preload/react/src/routeTree.gen.ts +++ /dev/null @@ -1,95 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index b659fe4d26..0000000000 --- a/benchmarks/client-nav/scenarios/preload/react/src/routes/__root.tsx +++ /dev/null @@ -1,32 +0,0 @@ -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 deleted file mode 100644 index 1f87530bac..0000000000 --- a/benchmarks/client-nav/scenarios/preload/react/src/routes/docs.tsx +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 2b8c83ebab..0000000000 --- a/benchmarks/client-nav/scenarios/preload/react/src/routes/index.tsx +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 42962b8be7..0000000000 --- a/benchmarks/client-nav/scenarios/preload/react/src/routes/sections.$section.tsx +++ /dev/null @@ -1,32 +0,0 @@ -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 deleted file mode 100644 index 1d59cbb450..0000000000 --- a/benchmarks/client-nav/scenarios/preload/react/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/preload/react/vite.config.ts b/benchmarks/client-nav/scenarios/preload/react/vite.config.ts deleted file mode 100644 index 8a41fc8707..0000000000 --- a/benchmarks/client-nav/scenarios/preload/react/vite.config.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import react from '@vitejs/plugin-react' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'react', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav 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 deleted file mode 100644 index d061f99451..0000000000 --- a/benchmarks/client-nav/scenarios/preload/shared.ts +++ /dev/null @@ -1,119 +0,0 @@ -/** - * 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 deleted file mode 100644 index a186879335..0000000000 --- a/benchmarks/client-nav/scenarios/preload/solid/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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 deleted file mode 100644 index 34270fe8a4..0000000000 --- a/benchmarks/client-nav/scenarios/preload/solid/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index f835b4a7b9..0000000000 --- a/benchmarks/client-nav/scenarios/preload/solid/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-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 deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/preload/solid/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/preload/solid/src/main.tsx b/benchmarks/client-nav/scenarios/preload/solid/src/main.tsx deleted file mode 100644 index 3791156c64..0000000000 --- a/benchmarks/client-nav/scenarios/preload/solid/src/main.tsx +++ /dev/null @@ -1,37 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { render } from 'solid-js/web' -import { RouterProvider, createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - 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 deleted file mode 100644 index 97e215b6da..0000000000 --- a/benchmarks/client-nav/scenarios/preload/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,95 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index a805ed0feb..0000000000 --- a/benchmarks/client-nav/scenarios/preload/solid/src/routes/__root.tsx +++ /dev/null @@ -1,34 +0,0 @@ -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 deleted file mode 100644 index b077cfd18f..0000000000 --- a/benchmarks/client-nav/scenarios/preload/solid/src/routes/docs.tsx +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 72fbfe387a..0000000000 --- a/benchmarks/client-nav/scenarios/preload/solid/src/routes/index.tsx +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 2a7fb2ad1b..0000000000 --- a/benchmarks/client-nav/scenarios/preload/solid/src/routes/sections.$section.tsx +++ /dev/null @@ -1,33 +0,0 @@ -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 deleted file mode 100644 index 98d76ad6b8..0000000000 --- a/benchmarks/client-nav/scenarios/preload/solid/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "solid-js", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/preload/solid/vite.config.ts b/benchmarks/client-nav/scenarios/preload/solid/vite.config.ts deleted file mode 100644 index 07014e6124..0000000000 --- a/benchmarks/client-nav/scenarios/preload/solid/vite.config.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import solid from 'vite-plugin-solid' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'solid', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - solid({ hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - resolve: { - conditions: ['solid', 'browser'], - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav 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 deleted file mode 100644 index 404476723d..0000000000 --- a/benchmarks/client-nav/scenarios/preload/vue/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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 deleted file mode 100644 index f70a154909..0000000000 --- a/benchmarks/client-nav/scenarios/preload/vue/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index e0ec83619b..0000000000 --- a/benchmarks/client-nav/scenarios/preload/vue/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-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 deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/preload/vue/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/preload/vue/src/main.tsx b/benchmarks/client-nav/scenarios/preload/vue/src/main.tsx deleted file mode 100644 index 3da20b2cbf..0000000000 --- a/benchmarks/client-nav/scenarios/preload/vue/src/main.tsx +++ /dev/null @@ -1,44 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import * as Vue from 'vue' -import { RouterProvider, createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - 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 deleted file mode 100644 index 5f95d09da0..0000000000 --- a/benchmarks/client-nav/scenarios/preload/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,95 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index bf91ba3770..0000000000 --- a/benchmarks/client-nav/scenarios/preload/vue/src/routes/__root.tsx +++ /dev/null @@ -1,35 +0,0 @@ -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 deleted file mode 100644 index 07d0a989ad..0000000000 --- a/benchmarks/client-nav/scenarios/preload/vue/src/routes/docs.tsx +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index f04a9f5796..0000000000 --- a/benchmarks/client-nav/scenarios/preload/vue/src/routes/index.tsx +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index aeb617a86f..0000000000 --- a/benchmarks/client-nav/scenarios/preload/vue/src/routes/sections.$section.tsx +++ /dev/null @@ -1,37 +0,0 @@ -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 deleted file mode 100644 index 7786fc3da9..0000000000 --- a/benchmarks/client-nav/scenarios/preload/vue/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/preload/vue/vite.config.ts b/benchmarks/client-nav/scenarios/preload/vue/vite.config.ts deleted file mode 100644 index 8d00e66378..0000000000 --- a/benchmarks/client-nav/scenarios/preload/vue/vite.config.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import vue from '@vitejs/plugin-vue' -import vueJsx from '@vitejs/plugin-vue-jsx' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'vue', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - vue(), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav 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 deleted file mode 100644 index d98c6e1412..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/react/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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 deleted file mode 100644 index 0c5df273ed..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/react/setup.ts +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index dd1b6f3686..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/react/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-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 deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/react/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/rewrites/react/src/main.tsx b/benchmarks/client-nav/scenarios/rewrites/react/src/main.tsx deleted file mode 100644 index 28020ce373..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/react/src/main.tsx +++ /dev/null @@ -1,40 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { RouterProvider, createRouter } from '@tanstack/react-router' -import { createRoot } from 'react-dom/client' -import { routeTree } from './routeTree.gen' -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 deleted file mode 100644 index b6ab8c8be4..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/react/src/routeTree.gen.ts +++ /dev/null @@ -1,103 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index ad14ff51f1..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/react/src/routes/__root.tsx +++ /dev/null @@ -1,61 +0,0 @@ -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 deleted file mode 100644 index 821cfe4a7c..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/react/src/routes/index.tsx +++ /dev/null @@ -1,13 +0,0 @@ -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 deleted file mode 100644 index ec1163e5c2..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/react/src/routes/p.$a.$b.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index f4937494f0..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/react/src/routes/p.$a.tsx +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index 1d59cbb450..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/react/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/rewrites/react/vite.config.ts b/benchmarks/client-nav/scenarios/rewrites/react/vite.config.ts deleted file mode 100644 index e79e8522e9..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/react/vite.config.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import react from '@vitejs/plugin-react' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'react', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav 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 deleted file mode 100644 index 0ca0a7ceb9..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/shared.ts +++ /dev/null @@ -1,106 +0,0 @@ -/** - * 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 deleted file mode 100644 index 4b2f763032..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/solid/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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 deleted file mode 100644 index 5796df712d..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/solid/setup.ts +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index 9c4313e2ff..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/solid/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-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 deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/solid/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/rewrites/solid/src/main.tsx b/benchmarks/client-nav/scenarios/rewrites/solid/src/main.tsx deleted file mode 100644 index 31f1d07650..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/solid/src/main.tsx +++ /dev/null @@ -1,37 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { render } from 'solid-js/web' -import { RouterProvider, createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' -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 deleted file mode 100644 index 2d35f899c9..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,103 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 3a78f2c3cf..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/solid/src/routes/__root.tsx +++ /dev/null @@ -1,61 +0,0 @@ -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 deleted file mode 100644 index 5ee381ff05..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/solid/src/routes/index.tsx +++ /dev/null @@ -1,13 +0,0 @@ -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 deleted file mode 100644 index febcad35e3..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/solid/src/routes/p.$a.$b.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index adfb7bc3b6..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/solid/src/routes/p.$a.tsx +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index 98d76ad6b8..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/solid/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "solid-js", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/rewrites/solid/vite.config.ts b/benchmarks/client-nav/scenarios/rewrites/solid/vite.config.ts deleted file mode 100644 index c9e99b7d60..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/solid/vite.config.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import solid from 'vite-plugin-solid' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'solid', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - solid({ hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - resolve: { - conditions: ['solid', 'browser'], - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav 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 deleted file mode 100644 index 9b7cb5d198..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/vue/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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 deleted file mode 100644 index e26b4d05ca..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/vue/setup.ts +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index e96aff39eb..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/vue/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-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 deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/vue/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/rewrites/vue/src/main.tsx b/benchmarks/client-nav/scenarios/rewrites/vue/src/main.tsx deleted file mode 100644 index 6695e82dbb..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/vue/src/main.tsx +++ /dev/null @@ -1,44 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import * as Vue from 'vue' -import { RouterProvider, createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' -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 deleted file mode 100644 index 6eca4e8ce5..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,103 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index ae89645005..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/vue/src/routes/__root.tsx +++ /dev/null @@ -1,64 +0,0 @@ -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 deleted file mode 100644 index d5405b52d2..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/vue/src/routes/index.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 062c0903b9..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/vue/src/routes/p.$a.$b.tsx +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index 552700d402..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/vue/src/routes/p.$a.tsx +++ /dev/null @@ -1,20 +0,0 @@ -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 deleted file mode 100644 index 7786fc3da9..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/vue/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/rewrites/vue/vite.config.ts b/benchmarks/client-nav/scenarios/rewrites/vue/vite.config.ts deleted file mode 100644 index 1a795a4e1d..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/vue/vite.config.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import vue from '@vitejs/plugin-vue' -import vueJsx from '@vitejs/plugin-vue-jsx' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'vue', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - vue(), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav 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 deleted file mode 100644 index 3291738f79..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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 deleted file mode 100644 index 130583b190..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index 6f4b448775..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-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 deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/main.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/main.tsx deleted file mode 100644 index 5febd6f795..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/main.tsx +++ /dev/null @@ -1,37 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { RouterProvider, createRouter } from '@tanstack/react-router' -import { createRoot } from 'react-dom/client' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const reactRoot = createRoot(container) - reactRoot.render() - - return { - router, - unmount() { - reactRoot.unmount() - }, - } -} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routeTree.gen.ts deleted file mode 100644 index f8eeb73dda..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routeTree.gen.ts +++ /dev/null @@ -1,881 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index ac2a376549..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/(marketing)/pricing.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index b71962254e..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/(marketing)/promo.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 7ed47da924..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/__root.tsx +++ /dev/null @@ -1,58 +0,0 @@ -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 deleted file mode 100644 index 893419cef5..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/_layout.alpha.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index d20c6007ee..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/_layout.beta.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 961feb50f1..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/_layout.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 028aa43d5a..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/files.$.tsx +++ /dev/null @@ -1,11 +0,0 @@ -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 deleted file mode 100644 index 8a7ffca9e7..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index dfe8e31905..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/release.v{$version}.tsx +++ /dev/null @@ -1,11 +0,0 @@ -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 deleted file mode 100644 index 8be053a040..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.$id.tsx +++ /dev/null @@ -1,11 +0,0 @@ -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 deleted file mode 100644 index 54c1b28618..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.about.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 3c793a94f5..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 0037f6463d..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.settings.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 846f96b67b..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 0dd7f94feb..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.$id.tsx +++ /dev/null @@ -1,11 +0,0 @@ -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 deleted file mode 100644 index fde4647472..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.about.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 51b69cf664..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 977b7438b1..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.settings.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 77d7e6475d..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index eb3be796c0..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.$id.tsx +++ /dev/null @@ -1,11 +0,0 @@ -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 deleted file mode 100644 index 7910acf332..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.about.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index f6ae102f2d..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index bf2be30788..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.settings.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 77ac5644c6..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index d34aee8972..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.$id.tsx +++ /dev/null @@ -1,11 +0,0 @@ -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 deleted file mode 100644 index 1f095cb2ff..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.about.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 8fc698a4d4..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 76c7a178ea..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.settings.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 5f3d281b5e..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 6e31d0c5d1..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.$id.tsx +++ /dev/null @@ -1,11 +0,0 @@ -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 deleted file mode 100644 index 5a2835917b..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.about.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 0f23b8d484..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index b566a1ffaa..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.settings.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index e573a71d98..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index a71c17f96e..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.$id.tsx +++ /dev/null @@ -1,11 +0,0 @@ -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 deleted file mode 100644 index 06831063ad..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.about.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 4cd54b6a7f..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 92bdca5e44..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.settings.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 2fa27873e8..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 1d59cbb450..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/vite.config.ts b/benchmarks/client-nav/scenarios/route-tree-scale/react/vite.config.ts deleted file mode 100644 index 0f588fda53..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/vite.config.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import react from '@vitejs/plugin-react' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'react', - // 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 deleted file mode 100644 index 8af5996804..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/shared.ts +++ /dev/null @@ -1,64 +0,0 @@ -/** - * 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 deleted file mode 100644 index c568e41196..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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 deleted file mode 100644 index 6a46971603..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index 9244ef1350..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-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 deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/main.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/main.tsx deleted file mode 100644 index fa9d239418..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/main.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { render } from 'solid-js/web' -import { RouterProvider, createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const unmount = render(() => , container) - - return { - router, - unmount, - } -} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routeTree.gen.ts deleted file mode 100644 index e6f3596562..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,881 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 0965507de6..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/(marketing)/pricing.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 220bd06a68..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/(marketing)/promo.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index a4e4113d9a..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/__root.tsx +++ /dev/null @@ -1,58 +0,0 @@ -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 deleted file mode 100644 index 234b8488a9..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/_layout.alpha.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 39bc716efa..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/_layout.beta.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index f1e499d3b3..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/_layout.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 47b1a5eea9..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/files.$.tsx +++ /dev/null @@ -1,11 +0,0 @@ -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 deleted file mode 100644 index 25b1c03c1a..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 0dbcee35ca..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/release.v{$version}.tsx +++ /dev/null @@ -1,11 +0,0 @@ -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 deleted file mode 100644 index 18731a2844..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.$id.tsx +++ /dev/null @@ -1,11 +0,0 @@ -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 deleted file mode 100644 index 1699360a1c..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.about.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index e71e525d07..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 49d470190e..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.settings.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 2861169fb9..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 86fe71d7c0..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.$id.tsx +++ /dev/null @@ -1,11 +0,0 @@ -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 deleted file mode 100644 index 586b829cd0..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.about.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 7098416658..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index c2e0f47650..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.settings.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index f2905da9ca..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 3e07e8033a..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.$id.tsx +++ /dev/null @@ -1,11 +0,0 @@ -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 deleted file mode 100644 index 86ed5043a3..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.about.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index aa9ed2dc6c..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index d0dd3e952c..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.settings.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index fa53825238..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 3722012d7c..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.$id.tsx +++ /dev/null @@ -1,11 +0,0 @@ -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 deleted file mode 100644 index 860d2b9e5b..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.about.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index ec7b8eaf2c..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index d83e3885fd..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.settings.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index e71391e2a3..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index e58d9d77ac..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.$id.tsx +++ /dev/null @@ -1,11 +0,0 @@ -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 deleted file mode 100644 index 3ef4d2c763..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.about.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 88bf7ca271..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 8a9945926d..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.settings.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 8b5ef24519..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 2b81ef96ff..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.$id.tsx +++ /dev/null @@ -1,11 +0,0 @@ -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 deleted file mode 100644 index 1c4e3a5474..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.about.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 65803ee848..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 5761138262..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.settings.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index c7f25eecdd..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 98d76ad6b8..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "solid-js", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/vite.config.ts b/benchmarks/client-nav/scenarios/route-tree-scale/solid/vite.config.ts deleted file mode 100644 index 542ede131b..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/vite.config.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import solid from 'vite-plugin-solid' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'solid', - // 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 deleted file mode 100644 index f613070038..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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 deleted file mode 100644 index 97b74b3892..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index 331e8e008f..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-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 deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/main.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/main.tsx deleted file mode 100644 index cae9b54f1d..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/main.tsx +++ /dev/null @@ -1,41 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import * as Vue from 'vue' -import { RouterProvider, createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const component = - const app = Vue.createApp({ - render: () => component, - }) - - app.mount(container) - - return { - router, - unmount() { - app.unmount() - }, - } -} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routeTree.gen.ts deleted file mode 100644 index a12f981bb4..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,881 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index f606c10b4b..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/(marketing)/pricing.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index 61c3eb3ec9..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/(marketing)/promo.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index d2e1483106..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/__root.tsx +++ /dev/null @@ -1,61 +0,0 @@ -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 deleted file mode 100644 index ff6ad5350e..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/_layout.alpha.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index 2f7cab6c0a..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/_layout.beta.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index e8221f0f65..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/_layout.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index 221fae01be..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/files.$.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index b3e94f37c4..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/index.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index 86b1a2c8f0..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/release.v{$version}.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 864074940d..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.$id.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 715ab9548c..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.about.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index baef08547c..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.index.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index 9e6a56b913..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.settings.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index a9fb557aea..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index 9a03a8fe01..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.$id.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 2ef1100995..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.about.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index 652e5f895c..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.index.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index e8fa36377e..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.settings.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index ba31612633..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index 7f0407d84e..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.$id.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index d26776d439..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.about.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index 1835eff9b7..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.index.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index 1bf85fd6d9..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.settings.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index 009f814b93..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index ff5aab05e3..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.$id.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 25a8078626..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.about.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index cd9b89664a..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.index.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index 8e4309de32..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.settings.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index 6b12b514da..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index 4525051967..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.$id.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 71a32bd36b..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.about.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index 9b467ca53e..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.index.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index a01066488c..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.settings.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index 38f4da91fb..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index c740f9d223..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.$id.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 229dab22a2..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.about.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index 14e3f46a13..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.index.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index da2c7483b9..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.settings.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index 3b389c8144..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index 7786fc3da9..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/vite.config.ts b/benchmarks/client-nav/scenarios/route-tree-scale/vue/vite.config.ts deleted file mode 100644 index 189ba1de99..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/vite.config.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import vue from '@vitejs/plugin-vue' -import vueJsx from '@vitejs/plugin-vue-jsx' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'vue', - // 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 deleted file mode 100644 index f2d743f5f9..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/react/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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 deleted file mode 100644 index 130583b190..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/react/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index 0b38f7bddb..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/react/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-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 deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/react/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/search-params/react/src/main.tsx b/benchmarks/client-nav/scenarios/search-params/react/src/main.tsx deleted file mode 100644 index b10d53554b..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/react/src/main.tsx +++ /dev/null @@ -1,38 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { RouterProvider, createRouter } from '@tanstack/react-router' -import { createRoot } from 'react-dom/client' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - 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 deleted file mode 100644 index cff9dca167..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/react/src/routeTree.gen.ts +++ /dev/null @@ -1,95 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 86399d0175..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/react/src/routes/__root.tsx +++ /dev/null @@ -1,116 +0,0 @@ -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 deleted file mode 100644 index 73f59c13b0..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/react/src/routes/catalog.tsx +++ /dev/null @@ -1,42 +0,0 @@ -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 deleted file mode 100644 index 5879ad518d..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/react/src/routes/index.tsx +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index d22e99c4bf..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/react/src/routes/products.tsx +++ /dev/null @@ -1,91 +0,0 @@ -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 deleted file mode 100644 index 1d59cbb450..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/react/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/search-params/react/vite.config.ts b/benchmarks/client-nav/scenarios/search-params/react/vite.config.ts deleted file mode 100644 index 0318a10815..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/react/vite.config.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import react from '@vitejs/plugin-react' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'react', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav 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 deleted file mode 100644 index 343e319ded..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/shared.ts +++ /dev/null @@ -1,200 +0,0 @@ -/** - * 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 deleted file mode 100644 index af48217e03..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/solid/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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 deleted file mode 100644 index 6a46971603..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/solid/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index caa626c596..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/solid/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-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 deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/solid/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/search-params/solid/src/main.tsx b/benchmarks/client-nav/scenarios/search-params/solid/src/main.tsx deleted file mode 100644 index 25071f7979..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/solid/src/main.tsx +++ /dev/null @@ -1,35 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { render } from 'solid-js/web' -import { RouterProvider, createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - 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 deleted file mode 100644 index b15beed09b..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,95 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 30c042f9c5..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/solid/src/routes/__root.tsx +++ /dev/null @@ -1,120 +0,0 @@ -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 deleted file mode 100644 index 60cf8e7896..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/solid/src/routes/catalog.tsx +++ /dev/null @@ -1,50 +0,0 @@ -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 deleted file mode 100644 index 0bbb913d83..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/solid/src/routes/index.tsx +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 8b2a252155..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/solid/src/routes/products.tsx +++ /dev/null @@ -1,97 +0,0 @@ -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 deleted file mode 100644 index 98d76ad6b8..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/solid/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "solid-js", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/search-params/solid/vite.config.ts b/benchmarks/client-nav/scenarios/search-params/solid/vite.config.ts deleted file mode 100644 index 511fd49466..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/solid/vite.config.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import solid from 'vite-plugin-solid' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'solid', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - solid({ hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - resolve: { - conditions: ['solid', 'browser'], - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav 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 deleted file mode 100644 index 47b9712a2c..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/vue/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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 deleted file mode 100644 index 97b74b3892..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/vue/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index 728d2779e8..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/vue/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-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 deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/vue/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/search-params/vue/src/main.tsx b/benchmarks/client-nav/scenarios/search-params/vue/src/main.tsx deleted file mode 100644 index 65bade775c..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/vue/src/main.tsx +++ /dev/null @@ -1,42 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import * as Vue from 'vue' -import { RouterProvider, createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - 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 deleted file mode 100644 index f73b84ebe7..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,95 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index b4cb07f2ae..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/vue/src/routes/__root.tsx +++ /dev/null @@ -1,114 +0,0 @@ -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 deleted file mode 100644 index 6a09efdd4a..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/vue/src/routes/catalog.tsx +++ /dev/null @@ -1,49 +0,0 @@ -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 deleted file mode 100644 index 081aa7b4fd..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/vue/src/routes/index.tsx +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index 8be1683e14..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/vue/src/routes/products.tsx +++ /dev/null @@ -1,108 +0,0 @@ -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 deleted file mode 100644 index 7786fc3da9..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/vue/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/search-params/vue/vite.config.ts b/benchmarks/client-nav/scenarios/search-params/vue/vite.config.ts deleted file mode 100644 index 27490b276a..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/vue/vite.config.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import vue from '@vitejs/plugin-vue' -import vueJsx from '@vitejs/plugin-vue-jsx' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'vue', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - vue(), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav 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 deleted file mode 100644 index c070018743..0000000000 --- a/benchmarks/client-nav/setup-helpers.ts +++ /dev/null @@ -1,43 +0,0 @@ -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 index ef90130f5e..42bc383d46 100644 --- a/benchmarks/client-nav/solid/app.tsx +++ b/benchmarks/client-nav/solid/app.tsx @@ -1,5 +1,5 @@ -import { For, createRenderEffect } from 'solid-js' -import { render } from 'solid-js/web' +import { For, createEffect } from 'solid-js' +import { render } from '@solidjs/web' import { Link, Outlet, @@ -15,353 +15,84 @@ import { function runPerfSelectorComputation(seed: number) { let value = Math.trunc(seed) | 0 - for (let index = 0; index < 40; index++) { + for (let index = 0; index < 100; 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 -} +const selectors = Array.from({ length: 20 }, (_, index) => index) -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() { +function Params() { const params = useParams({ strict: false, select: (params) => runPerfSelectorComputation(Number(params.id ?? 0)), }) - return runPerfSelectorComputation(params())} /> + createEffect( + () => params(), + () => {}, + ) + + return null } -function RootSearchSubscriber() { +function Search() { const search = useSearch({ strict: false, - select: (search) => runPerfSelectorComputation(Number(search.page ?? 0)), + select: (search) => runPerfSelectorComputation(Number(search.id ?? 0)), }) - return runPerfSelectorComputation(search())} /> + createEffect( + () => search(), + () => {}, + ) + + return null } -function LinkPanel() { +function Links() { 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}` - } - -
- ) - }} -
- + + Link + ) } function Root() { return ( <> - {() => } - {() => } - + {() => } + {() => } + {() => } ) } -const rootRoute = createRootRoute({ +const root = 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}`, - }), +const route = createRoute({ + getParentRoute: () => root, + path: '/$id', + component: () => { + return
}, - 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'], + initialEntries: ['/0'], }), scrollRestoration: true, - routeTree: rootRoute.addChildren([ - itemsRoute.addChildren([itemDetailsRoute]), - searchRoute, - contextRoute, - ]), + routeTree: root.addChildren([route]), }) const unmount = render(() => , container) - return { - router, - unmount, - } + return { router, unmount } } diff --git a/benchmarks/client-nav/solid/setup.ts b/benchmarks/client-nav/solid/setup.ts index 9b532a466a..6c73350cf1 100644 --- a/benchmarks/client-nav/solid/setup.ts +++ b/benchmarks/client-nav/solid/setup.ts @@ -1,11 +1,8 @@ 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 +const { mountTestApp } = (await import(appModulePath)) as typeof App export function setup() { if (process.env.NODE_ENV !== 'production') { @@ -14,20 +11,19 @@ export function setup() { ) } + let id = 0 + let dispose: (() => void) | undefined = undefined 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 + id = 0 container = document.createElement('div') document.body.append(container) - const { router, unmount: dispose } = mountTestApp(container) - unmount = dispose - + const { router, unmount } = mountTestApp(container) + dispose = unmount let resolveRendered: () => void = () => {} unsub = router.subscribe('onRendered', () => { resolveRendered() @@ -39,63 +35,22 @@ export function setup() { 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() + const nextId = id++ + + return navigate({ + to: '/$id', + params: { id: nextId }, + // update search every 2 navigations, to still test them, but also measure the impact of granular re-rendering + search: { id: Math.floor(nextId / 2) }, + replace: true, + }) } + await router.load() } function after() { - unmount?.() + dispose?.() container?.remove() unsub() } diff --git a/benchmarks/client-nav/solid/speed.bench.ts b/benchmarks/client-nav/solid/speed.bench.ts index d629da17a8..34791180ce 100644 --- a/benchmarks/client-nav/solid/speed.bench.ts +++ b/benchmarks/client-nav/solid/speed.bench.ts @@ -1,19 +1,34 @@ -import { test } from 'vitest' +import { afterAll, beforeAll, bench, describe } from 'vitest' import { setup } from './setup' -test('client-nav', async ({ bench }) => { - const scenario = setup() +describe('client-nav', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, + * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. + * + * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, + * but it does support `beforeAll` and `afterAll`. + * + * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. + */ + + beforeAll(test.before) + afterAll(test.after) + + bench( 'client-side navigation loop (solid)', - { beforeAll: scenario.before, afterAll: scenario.after }, async () => { for (let i = 0; i < 10; i++) { - await scenario.tick() + await test.tick() } }, - ).run({ - warmupIterations: 100, - time: 10_000, - }) + { + warmupIterations: 100, + time: 10_000, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/solid/vite.config.ts b/benchmarks/client-nav/solid/vite.config.ts index 0c26b32f5f..8102b26747 100644 --- a/benchmarks/client-nav/solid/vite.config.ts +++ b/benchmarks/client-nav/solid/vite.config.ts @@ -1,18 +1,8 @@ -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(), @@ -32,12 +22,10 @@ export default defineConfig({ conditions: ['solid', 'browser'], }, test: { - execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav (solid)', watch: false, environment: 'jsdom', - setupFiles: [`${rootDir}vitest.setup.ts`], - benchmark: { include: ['solid/speed.bench.ts'] }, + setupFiles: ['./vitest.setup.ts'], server: { deps: { inline: [/@solidjs/, /@tanstack\/solid-store/], diff --git a/benchmarks/client-nav/vitest.config.ts b/benchmarks/client-nav/vitest.config.ts index 808e7fc724..14776452ed 100644 --- a/benchmarks/client-nav/vitest.config.ts +++ b/benchmarks/client-nav/vitest.config.ts @@ -7,9 +7,6 @@ export default defineConfig({ './react/vite.config.ts', './solid/vite.config.ts', './vue/vite.config.ts', - './scenarios/*/react/vite.config.ts', - './scenarios/*/solid/vite.config.ts', - './scenarios/*/vue/vite.config.ts', ], }, }) diff --git a/benchmarks/client-nav/vitest.react.config.ts b/benchmarks/client-nav/vitest.react.config.ts deleted file mode 100644 index a397ad929e..0000000000 --- a/benchmarks/client-nav/vitest.react.config.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { defineConfig } from 'vitest/config' - -export default defineConfig({ - test: { - watch: false, - projects: ['./react/vite.config.ts', './scenarios/*/react/vite.config.ts'], - }, -}) diff --git a/benchmarks/client-nav/vitest.solid.config.ts b/benchmarks/client-nav/vitest.solid.config.ts deleted file mode 100644 index b8827b86aa..0000000000 --- a/benchmarks/client-nav/vitest.solid.config.ts +++ /dev/null @@ -1,8 +0,0 @@ -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 deleted file mode 100644 index 17960d7569..0000000000 --- a/benchmarks/client-nav/vitest.vue.config.ts +++ /dev/null @@ -1,8 +0,0 @@ -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 index f88eee8129..cf6c864380 100644 --- a/benchmarks/client-nav/vue/app.tsx +++ b/benchmarks/client-nav/vue/app.tsx @@ -14,28 +14,16 @@ import { function runPerfSelectorComputation(seed: number) { let value = Math.trunc(seed) | 0 - for (let index = 0; index < 40; index++) { + for (let index = 0; index < 100; 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 -} +const selectors = Array.from({ length: 20 }, (_, index) => index) -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({ +const Params = Vue.defineComponent({ setup() { const params = useParams({ strict: false, @@ -43,97 +31,32 @@ const RootParamsSubscriber = Vue.defineComponent({ }) return () => { - void runPerfSelectorComputation(params.value) + void params.value return null } }, }) -const RootSearchSubscriber = Vue.defineComponent({ +const Search = Vue.defineComponent({ setup() { const search = useSearch({ strict: false, - select: (search) => runPerfSelectorComputation(Number(search.page ?? 0)), + select: (search) => runPerfSelectorComputation(Number(search.id ?? 0)), }) return () => { - void runPerfSelectorComputation(search.value) + void search.value return null } }, }) -const LinkPanel = Vue.defineComponent({ +const Links = 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}` - } - -
- ) - })} - + + Link + ) }, }) @@ -142,279 +65,38 @@ const Root = Vue.defineComponent({ setup() { return () => ( <> - {rootSelectors.map((selector) => ( - + {selectors.map((selector) => ( + ))} - {rootSelectors.map((selector) => ( - + {selectors.map((selector) => ( + + ))} + {selectors.map((selector) => ( + ))} - ) }, }) -const rootRoute = createRootRoute({ +const root = 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, +const route = createRoute({ + getParentRoute: () => root, + path: '/$id', + component: () =>
, }) export function mountTestApp(container: Element) { const router = createRouter({ history: createMemoryHistory({ - initialEntries: ['/items/0'], + initialEntries: ['/0'], }), scrollRestoration: true, - routeTree: rootRoute.addChildren([ - itemsRoute.addChildren([itemDetailsRoute]), - searchRoute, - contextRoute, - ]), + routeTree: root.addChildren([route]), }) const component = diff --git a/benchmarks/client-nav/vue/setup.ts b/benchmarks/client-nav/vue/setup.ts index 75a633f629..5b4a91cb05 100644 --- a/benchmarks/client-nav/vue/setup.ts +++ b/benchmarks/client-nav/vue/setup.ts @@ -1,11 +1,8 @@ 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 +const { mountTestApp } = (await import(appModulePath)) as typeof App export function setup() { if (process.env.NODE_ENV !== 'production') { @@ -14,20 +11,19 @@ export function setup() { ) } - let container: HTMLDivElement | undefined = undefined + let id = 0 let unmount: (() => void) | undefined = undefined + let container: HTMLDivElement | undefined = undefined let unsub = () => {} - let stepIndex = 0 let next: () => Promise = () => Promise.reject('Test not initialized') async function before() { - stepIndex = 0 + id = 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() @@ -39,59 +35,18 @@ export function setup() { 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() + const nextId = id++ + + return navigate({ + to: '/$id', + params: { id: nextId }, + // update search every 2 navigations, to still test them, but also measure the impact of granular re-rendering + search: { id: Math.floor(nextId / 2) }, + replace: true, + }) } + await router.load() } function after() { diff --git a/benchmarks/client-nav/vue/speed.bench.ts b/benchmarks/client-nav/vue/speed.bench.ts index 503e91e7b7..f9e532f5ba 100644 --- a/benchmarks/client-nav/vue/speed.bench.ts +++ b/benchmarks/client-nav/vue/speed.bench.ts @@ -1,19 +1,34 @@ -import { test } from 'vitest' +import { afterAll, beforeAll, bench, describe } from 'vitest' import { setup } from './setup' -test('client-nav', async ({ bench }) => { - const scenario = setup() +describe('client-nav', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, + * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. + * + * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, + * but it does support `beforeAll` and `afterAll`. + * + * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. + */ + + beforeAll(test.before) + afterAll(test.after) + + bench( 'client-side navigation loop (vue)', - { beforeAll: scenario.before, afterAll: scenario.after }, async () => { for (let i = 0; i < 10; i++) { - await scenario.tick() + await test.tick() } }, - ).run({ - warmupIterations: 100, - time: 10_000, - }) + { + warmupIterations: 100, + time: 10_000, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/vue/vite.config.ts b/benchmarks/client-nav/vue/vite.config.ts index 78d8ae5638..d917c82e2d 100644 --- a/benchmarks/client-nav/vue/vite.config.ts +++ b/benchmarks/client-nav/vue/vite.config.ts @@ -1,16 +1,9 @@ -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'), }, @@ -31,11 +24,9 @@ export default defineConfig({ }, }, test: { - execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav (vue)', watch: false, environment: 'jsdom', - setupFiles: [`${rootDir}vitest.setup.ts`], - benchmark: { include: ['vue/speed.bench.ts'] }, + setupFiles: ['./vitest.setup.ts'], }, }) diff --git a/benchmarks/cpu-simulation.ts b/benchmarks/cpu-simulation.ts deleted file mode 100644 index 9b8859f74d..0000000000 --- a/benchmarks/cpu-simulation.ts +++ /dev/null @@ -1,53 +0,0 @@ -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 deleted file mode 100644 index 18b68768f9..0000000000 --- a/benchmarks/memory/README.md +++ /dev/null @@ -1,273 +0,0 @@ -# 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 deleted file mode 100644 index 785e8fac7f..0000000000 --- a/benchmarks/memory/client/bench-utils.ts +++ /dev/null @@ -1,22 +0,0 @@ -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 deleted file mode 100644 index 463047f4d9..0000000000 --- a/benchmarks/memory/client/benchmark.ts +++ /dev/null @@ -1,11 +0,0 @@ -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 deleted file mode 100644 index 04941fda67..0000000000 --- a/benchmarks/memory/client/flame-runner.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 4df480df68..0000000000 --- a/benchmarks/memory/client/jsdom.ts +++ /dev/null @@ -1,51 +0,0 @@ -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 deleted file mode 100644 index c4a62f0f96..0000000000 --- a/benchmarks/memory/client/lifecycle.ts +++ /dev/null @@ -1,46 +0,0 @@ -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 deleted file mode 100644 index 4dc6246183..0000000000 --- a/benchmarks/memory/client/package.json +++ /dev/null @@ -1,274 +0,0 @@ -{ - "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 deleted file mode 100644 index 43ab822de3..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/react/memory.bench.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 952fd9a62c..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/react/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index 0ed437c9ca..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/react/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "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 deleted file mode 100644 index 6e072ad5f3..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/react/setup.ts +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index bd605a78ee..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/app.tsx +++ /dev/null @@ -1,37 +0,0 @@ -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 deleted file mode 100644 index 475085a433..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/routeTree.gen.ts +++ /dev/null @@ -1,95 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index ac27b20f79..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/router.tsx +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index 889395056b..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/routes/__root.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index d5fd7ade46..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/routes/fast.$id.tsx +++ /dev/null @@ -1,21 +0,0 @@ -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 deleted file mode 100644 index a425ac79c4..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 61bbf328b7..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/routes/slow.$id.tsx +++ /dev/null @@ -1,21 +0,0 @@ -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 deleted file mode 100644 index ea566061d9..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/react/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "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 deleted file mode 100644 index 0f05cedf40..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/react/vite.config.ts +++ /dev/null @@ -1,35 +0,0 @@ -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 deleted file mode 100644 index 80f234f0c8..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/shared.ts +++ /dev/null @@ -1,297 +0,0 @@ -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 deleted file mode 100644 index c70ccac3da..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/slow-loaders.ts +++ /dev/null @@ -1,54 +0,0 @@ -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 deleted file mode 100644 index 43ab822de3..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/memory.bench.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 952fd9a62c..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index 4aff39500e..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "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 deleted file mode 100644 index e736111663..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/setup.ts +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index 6288b5fab1..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/app.tsx +++ /dev/null @@ -1,35 +0,0 @@ -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 deleted file mode 100644 index f42255963c..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,95 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 884aa3438f..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/router.tsx +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index cb8d5a688d..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/routes/__root.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 511e4712b7..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/routes/fast.$id.tsx +++ /dev/null @@ -1,21 +0,0 @@ -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 deleted file mode 100644 index 592b2d666e..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 9aaaef5568..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/routes/slow.$id.tsx +++ /dev/null @@ -1,21 +0,0 @@ -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 deleted file mode 100644 index b12dcb7ade..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "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 deleted file mode 100644 index 26ff0b5c8c..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/vite.config.ts +++ /dev/null @@ -1,35 +0,0 @@ -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 deleted file mode 100644 index 43ab822de3..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/memory.bench.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 952fd9a62c..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index 01288cb235..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "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 deleted file mode 100644 index 260e45b64b..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/setup.ts +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index 1abb4410dc..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/app.tsx +++ /dev/null @@ -1,42 +0,0 @@ -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 deleted file mode 100644 index 5ea61a89a3..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,95 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 4655fe8424..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/router.tsx +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index 91296e6f84..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routes/__root.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index f6dc9ac3bd..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routes/fast.$id.tsx +++ /dev/null @@ -1,24 +0,0 @@ -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 deleted file mode 100644 index c30a51e1e5..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 3b5bb75ede..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routes/slow.$id.tsx +++ /dev/null @@ -1,24 +0,0 @@ -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 deleted file mode 100644 index 9a5872a4c0..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "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 deleted file mode 100644 index 02574908d2..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -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 deleted file mode 100644 index 3bd59c82ef..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/loader-data.ts +++ /dev/null @@ -1,48 +0,0 @@ -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 deleted file mode 100644 index 43ab822de3..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/react/memory.bench.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 952fd9a62c..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/react/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index 713038e20f..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/react/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "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 deleted file mode 100644 index fafaf13e6f..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/react/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 5eef150c2c..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/react/src/app.tsx +++ /dev/null @@ -1,33 +0,0 @@ -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 deleted file mode 100644 index ea96d809c8..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/react/src/routeTree.gen.ts +++ /dev/null @@ -1,102 +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 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 deleted file mode 100644 index 5a5c8210d9..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/react/src/router.tsx +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index 889395056b..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/react/src/routes/__root.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 63af9ed429..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/react/src/routes/page.$id.tsx +++ /dev/null @@ -1,21 +0,0 @@ -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 deleted file mode 100644 index d78bb8bfb9..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/react/src/routes/shell.index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 024a58c243..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/react/src/routes/shell.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index ea566061d9..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/react/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "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 deleted file mode 100644 index 8630417936..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/react/vite.config.ts +++ /dev/null @@ -1,35 +0,0 @@ -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 deleted file mode 100644 index bd90c023f0..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/shared.ts +++ /dev/null @@ -1,187 +0,0 @@ -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 deleted file mode 100644 index 43ab822de3..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/solid/memory.bench.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 952fd9a62c..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/solid/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index 6c85f51896..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/solid/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "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 deleted file mode 100644 index b7c80a3e49..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/solid/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 4315a4b15c..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/app.tsx +++ /dev/null @@ -1,31 +0,0 @@ -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 deleted file mode 100644 index a1946d187d..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,102 +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 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 deleted file mode 100644 index 06afdb10d3..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/router.tsx +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index cb8d5a688d..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/routes/__root.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index fb6c438fa5..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/routes/page.$id.tsx +++ /dev/null @@ -1,21 +0,0 @@ -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 deleted file mode 100644 index 2f4f5daee2..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/routes/shell.index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index c1e38a1aaf..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/routes/shell.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index b12dcb7ade..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/solid/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "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 deleted file mode 100644 index 5dfd5b53fe..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/solid/vite.config.ts +++ /dev/null @@ -1,35 +0,0 @@ -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 deleted file mode 100644 index 43ab822de3..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/vue/memory.bench.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 952fd9a62c..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/vue/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index 22504c906f..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/vue/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "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 deleted file mode 100644 index a83a1f70d1..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/vue/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index c843b4feb5..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/app.tsx +++ /dev/null @@ -1,38 +0,0 @@ -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 deleted file mode 100644 index 5b09d365e7..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,102 +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 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 deleted file mode 100644 index 84286e1dae..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/router.tsx +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index 91296e6f84..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/routes/__root.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 38f1d2614c..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/routes/page.$id.tsx +++ /dev/null @@ -1,25 +0,0 @@ -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 deleted file mode 100644 index 640ffeeb5c..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/routes/shell.index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index f8a598bc34..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/routes/shell.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 9a5872a4c0..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/vue/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "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 deleted file mode 100644 index 006636eaa0..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/vue/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -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 deleted file mode 100644 index 43ab822de3..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/react/memory.bench.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 952fd9a62c..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/react/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index 05d8aaa4bf..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/react/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "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 deleted file mode 100644 index 70603b5c34..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/react/setup.ts +++ /dev/null @@ -1,13 +0,0 @@ -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 deleted file mode 100644 index bdf76eaa24..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/react/src/app.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index 5efcb2cf72..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/react/src/routeTree.gen.ts +++ /dev/null @@ -1,59 +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 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 deleted file mode 100644 index 9cb85c5a1b..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/react/src/router.tsx +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index 889395056b..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/react/src/routes/__root.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 1e268d3c42..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/react/src/routes/a.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index ea566061d9..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/react/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "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 deleted file mode 100644 index a08352a837..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/react/vite.config.ts +++ /dev/null @@ -1,35 +0,0 @@ -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 deleted file mode 100644 index 01cfe8c46a..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/shared.ts +++ /dev/null @@ -1,74 +0,0 @@ -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 deleted file mode 100644 index 43ab822de3..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/solid/memory.bench.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 952fd9a62c..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/solid/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index 63e8e950db..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/solid/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "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 deleted file mode 100644 index 493425c6a2..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/solid/setup.ts +++ /dev/null @@ -1,13 +0,0 @@ -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 deleted file mode 100644 index b23bc126d5..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/solid/src/app.tsx +++ /dev/null @@ -1,27 +0,0 @@ -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 deleted file mode 100644 index a3f9739290..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,59 +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 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 deleted file mode 100644 index e8c14f12f6..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/solid/src/router.tsx +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index cb8d5a688d..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/solid/src/routes/__root.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 36c4be538c..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/solid/src/routes/a.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index b12dcb7ade..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/solid/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "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 deleted file mode 100644 index 33699639de..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/solid/vite.config.ts +++ /dev/null @@ -1,35 +0,0 @@ -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 deleted file mode 100644 index 43ab822de3..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/vue/memory.bench.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 952fd9a62c..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/vue/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index 157673cf16..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/vue/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "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 deleted file mode 100644 index a38df04788..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/vue/setup.ts +++ /dev/null @@ -1,13 +0,0 @@ -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 deleted file mode 100644 index 27b82fcbe1..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/vue/src/app.tsx +++ /dev/null @@ -1,34 +0,0 @@ -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 deleted file mode 100644 index 1a54b81033..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,59 +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 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 deleted file mode 100644 index e083495cd2..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/vue/src/router.tsx +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index 91296e6f84..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/vue/src/routes/__root.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 0dd650e1dd..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/vue/src/routes/a.tsx +++ /dev/null @@ -1,15 +0,0 @@ -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 deleted file mode 100644 index 9a5872a4c0..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/vue/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "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 deleted file mode 100644 index a3f0eeaa8c..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/vue/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -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 deleted file mode 100644 index 43ab822de3..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/react/memory.bench.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 952fd9a62c..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/react/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index b424277bc6..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/react/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "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 deleted file mode 100644 index 70603b5c34..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/react/setup.ts +++ /dev/null @@ -1,13 +0,0 @@ -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 deleted file mode 100644 index d714e7bfdd..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/react/src/app.tsx +++ /dev/null @@ -1,31 +0,0 @@ -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 deleted file mode 100644 index 3cca81cabb..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/react/src/routeTree.gen.ts +++ /dev/null @@ -1,77 +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 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 deleted file mode 100644 index 9cb85c5a1b..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/react/src/router.tsx +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index 889395056b..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/react/src/routes/__root.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index bdd32d0b81..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/react/src/routes/a.tsx +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 05deef729d..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/react/src/routes/b.tsx +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index ea566061d9..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/react/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "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 deleted file mode 100644 index eef60a658e..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/react/vite.config.ts +++ /dev/null @@ -1,35 +0,0 @@ -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 deleted file mode 100644 index 7eaf1a8b66..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/shared.ts +++ /dev/null @@ -1,129 +0,0 @@ -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 deleted file mode 100644 index 43ab822de3..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/solid/memory.bench.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 952fd9a62c..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/solid/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index 2c581e6188..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/solid/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "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 deleted file mode 100644 index 493425c6a2..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/solid/setup.ts +++ /dev/null @@ -1,13 +0,0 @@ -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 deleted file mode 100644 index 16000c90a1..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/solid/src/app.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index 59d7fad058..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,77 +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 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 deleted file mode 100644 index e8c14f12f6..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/solid/src/router.tsx +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index cb8d5a688d..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/solid/src/routes/__root.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 0b7838fdbe..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/solid/src/routes/a.tsx +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index ec9b513ba9..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/solid/src/routes/b.tsx +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index b12dcb7ade..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/solid/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "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 deleted file mode 100644 index 7dfb186b2e..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/solid/vite.config.ts +++ /dev/null @@ -1,35 +0,0 @@ -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 deleted file mode 100644 index 43ab822de3..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/vue/memory.bench.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 952fd9a62c..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/vue/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index f96d03d7d3..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/vue/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "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 deleted file mode 100644 index a38df04788..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/vue/setup.ts +++ /dev/null @@ -1,13 +0,0 @@ -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 deleted file mode 100644 index fad2251cc0..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/vue/src/app.tsx +++ /dev/null @@ -1,36 +0,0 @@ -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 deleted file mode 100644 index 12c9640358..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,77 +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 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 deleted file mode 100644 index e083495cd2..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/vue/src/router.tsx +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index 91296e6f84..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/vue/src/routes/__root.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index c1a9cfb244..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/vue/src/routes/a.tsx +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index 3a20799f3b..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/vue/src/routes/b.tsx +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index 9a5872a4c0..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/vue/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "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 deleted file mode 100644 index b3bdd39dd2..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/vue/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -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 deleted file mode 100644 index 4a86ea7244..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/item-payload.ts +++ /dev/null @@ -1,51 +0,0 @@ -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 deleted file mode 100644 index 43ab822de3..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/react/memory.bench.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 952fd9a62c..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/react/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index 238d98c816..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/react/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "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 deleted file mode 100644 index 31cd97d135..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/react/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index b75d1fe34d..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/react/src/app.tsx +++ /dev/null @@ -1,33 +0,0 @@ -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 deleted file mode 100644 index 84aaebb9c9..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/react/src/routeTree.gen.ts +++ /dev/null @@ -1,77 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 69e3180173..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/react/src/router.tsx +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index 889395056b..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/react/src/routes/__root.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index af735d705b..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/react/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 2f52acd528..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/react/src/routes/items.$id.tsx +++ /dev/null @@ -1,20 +0,0 @@ -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 deleted file mode 100644 index ea566061d9..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/react/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "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 deleted file mode 100644 index c12995f68e..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/react/vite.config.ts +++ /dev/null @@ -1,35 +0,0 @@ -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 deleted file mode 100644 index 68fdfedd3f..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/shared.ts +++ /dev/null @@ -1,216 +0,0 @@ -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 deleted file mode 100644 index 43ab822de3..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/solid/memory.bench.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 952fd9a62c..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/solid/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index 16ef8af968..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/solid/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "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 deleted file mode 100644 index 4db457f561..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/solid/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 18ad5b97e4..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/solid/src/app.tsx +++ /dev/null @@ -1,31 +0,0 @@ -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 deleted file mode 100644 index 27749ab2af..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,77 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index faed87f1f4..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/solid/src/router.tsx +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index cb8d5a688d..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/solid/src/routes/__root.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index b870b8bfd5..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/solid/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 15fa2a34ab..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/solid/src/routes/items.$id.tsx +++ /dev/null @@ -1,20 +0,0 @@ -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 deleted file mode 100644 index b12dcb7ade..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/solid/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "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 deleted file mode 100644 index efc75d2b93..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/solid/vite.config.ts +++ /dev/null @@ -1,35 +0,0 @@ -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 deleted file mode 100644 index 43ab822de3..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/vue/memory.bench.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 952fd9a62c..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/vue/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index e13388890f..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/vue/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "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 deleted file mode 100644 index 4aad4af31e..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/vue/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 890447d88b..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/vue/src/app.tsx +++ /dev/null @@ -1,38 +0,0 @@ -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 deleted file mode 100644 index a2216f2b67..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,77 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 86534112d7..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/vue/src/router.tsx +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index 91296e6f84..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/vue/src/routes/__root.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index b4f871306c..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/vue/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 08254e173e..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/vue/src/routes/items.$id.tsx +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 9a5872a4c0..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/vue/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "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 deleted file mode 100644 index 3d56089ba7..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/vue/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -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 deleted file mode 100644 index 43ab822de3..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/react/memory.bench.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 952fd9a62c..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/react/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index 1572552650..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/react/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "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 deleted file mode 100644 index 70603b5c34..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/react/setup.ts +++ /dev/null @@ -1,13 +0,0 @@ -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 deleted file mode 100644 index d714e7bfdd..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/react/src/app.tsx +++ /dev/null @@ -1,31 +0,0 @@ -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 deleted file mode 100644 index 1165f57523..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/react/src/routeTree.gen.ts +++ /dev/null @@ -1,59 +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 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 deleted file mode 100644 index 50ad269060..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/react/src/router.tsx +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index 889395056b..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/react/src/routes/__root.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index c9e823f6c2..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/react/src/routes/items.$id.tsx +++ /dev/null @@ -1,28 +0,0 @@ -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 deleted file mode 100644 index ea566061d9..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/react/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "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 deleted file mode 100644 index 7ee67bfe30..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/react/vite.config.ts +++ /dev/null @@ -1,35 +0,0 @@ -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 deleted file mode 100644 index 3b36c7811e..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/shared.ts +++ /dev/null @@ -1,149 +0,0 @@ -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 deleted file mode 100644 index 43ab822de3..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/solid/memory.bench.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 952fd9a62c..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/solid/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index 5be22de7a4..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/solid/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "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 deleted file mode 100644 index 493425c6a2..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/solid/setup.ts +++ /dev/null @@ -1,13 +0,0 @@ -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 deleted file mode 100644 index 16000c90a1..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/solid/src/app.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index 4a451735ff..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,59 +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 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 deleted file mode 100644 index 2969b06914..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/solid/src/router.tsx +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index cb8d5a688d..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/solid/src/routes/__root.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 9724922b8d..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/solid/src/routes/items.$id.tsx +++ /dev/null @@ -1,28 +0,0 @@ -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 deleted file mode 100644 index b12dcb7ade..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/solid/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "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 deleted file mode 100644 index 4db90da2d2..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/solid/vite.config.ts +++ /dev/null @@ -1,35 +0,0 @@ -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 deleted file mode 100644 index 43ab822de3..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/vue/memory.bench.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 952fd9a62c..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/vue/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index 6c05cf80b0..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/vue/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "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 deleted file mode 100644 index a38df04788..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/vue/setup.ts +++ /dev/null @@ -1,13 +0,0 @@ -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 deleted file mode 100644 index fad2251cc0..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/vue/src/app.tsx +++ /dev/null @@ -1,36 +0,0 @@ -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 deleted file mode 100644 index d3e9db0345..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,59 +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 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 deleted file mode 100644 index 72f9ab565b..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/vue/src/router.tsx +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index 91296e6f84..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/vue/src/routes/__root.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index e796ee14d1..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/vue/src/routes/items.$id.tsx +++ /dev/null @@ -1,37 +0,0 @@ -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 deleted file mode 100644 index 9a5872a4c0..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/vue/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "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 deleted file mode 100644 index d074d571b9..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/vue/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -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 deleted file mode 100644 index eefc5c581e..0000000000 --- a/benchmarks/memory/client/tsconfig.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "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 deleted file mode 100644 index 44643b4d60..0000000000 --- a/benchmarks/memory/client/vitest.react.config.ts +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index ce3127275a..0000000000 --- a/benchmarks/memory/client/vitest.setup.ts +++ /dev/null @@ -1,9 +0,0 @@ -// @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 deleted file mode 100644 index 5c8185cdd9..0000000000 --- a/benchmarks/memory/client/vitest.solid.config.ts +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 01768185ee..0000000000 --- a/benchmarks/memory/client/vitest.vue.config.ts +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 0d6f42df33..0000000000 --- a/benchmarks/memory/flame-control.ts +++ /dev/null @@ -1,123 +0,0 @@ -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 deleted file mode 100644 index cc568f3f77..0000000000 --- a/benchmarks/memory/run-flame.mjs +++ /dev/null @@ -1,117 +0,0 @@ -#!/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 deleted file mode 100644 index 010149b4df..0000000000 --- a/benchmarks/memory/runtime.ts +++ /dev/null @@ -1,36 +0,0 @@ -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 deleted file mode 100644 index 9caaf63384..0000000000 --- a/benchmarks/memory/server/bench-utils.ts +++ /dev/null @@ -1,99 +0,0 @@ -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 deleted file mode 100644 index 9b8dc2c76f..0000000000 --- a/benchmarks/memory/server/benchmark.ts +++ /dev/null @@ -1,13 +0,0 @@ -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 deleted file mode 100644 index 1930085aad..0000000000 --- a/benchmarks/memory/server/flame-runner.ts +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index d09343c7b6..0000000000 --- a/benchmarks/memory/server/package.json +++ /dev/null @@ -1,283 +0,0 @@ -{ - "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 deleted file mode 100644 index 7a1cd6d254..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/deferred-records.ts +++ /dev/null @@ -1,57 +0,0 @@ -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 deleted file mode 100644 index 8b5f16ad63..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/react/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/react/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index bea90c8766..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/react/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "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 deleted file mode 100644 index 0c98f54ddd..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/react/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index fbbc25ecfb..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/react/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 7c4eb0babe..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/react/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index c5f9de6922..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/react/src/routes/__root.tsx +++ /dev/null @@ -1,27 +0,0 @@ -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 deleted file mode 100644 index 08d534a779..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/react/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index ecd9ef524d..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/react/src/routes/stream.$id.tsx +++ /dev/null @@ -1,66 +0,0 @@ -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 deleted file mode 100644 index 11ddcce4ea..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/react/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "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 deleted file mode 100644 index eff0d0e043..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/react/vite.config.ts +++ /dev/null @@ -1,31 +0,0 @@ -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 deleted file mode 100644 index 29eca99e00..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/shared.ts +++ /dev/null @@ -1,235 +0,0 @@ -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 deleted file mode 100644 index 8b5f16ad63..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/solid/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/solid/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index 345fcc0720..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/solid/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "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 deleted file mode 100644 index 4fe85c3f00..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/solid/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 04ebed80f0..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 038ec0ab5e..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/solid/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index aaf7dfdd89..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/solid/src/routes/__root.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index 3aac56e824..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/solid/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index bf6af17f31..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/solid/src/routes/stream.$id.tsx +++ /dev/null @@ -1,69 +0,0 @@ -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 deleted file mode 100644 index 4b61264e11..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/solid/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "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 deleted file mode 100644 index d7fd3459ee..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/solid/vite.config.ts +++ /dev/null @@ -1,36 +0,0 @@ -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 deleted file mode 100644 index 8b5f16ad63..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/vue/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/vue/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index 8ca7d84660..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/vue/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "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 deleted file mode 100644 index 6683dafe6b..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/vue/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 192f1d6dc7..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 4290e7cdd3..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/vue/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index de29ee1612..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/vue/src/routes/__root.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index af662b29f7..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/vue/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index e41af03c16..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/vue/src/routes/stream.$id.tsx +++ /dev/null @@ -1,65 +0,0 @@ -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 deleted file mode 100644 index 9ad6481342..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/vue/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "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 deleted file mode 100644 index e4e1eb66d4..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/vue/vite.config.ts +++ /dev/null @@ -1,31 +0,0 @@ -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 deleted file mode 100644 index a6f07b97be..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/react/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 89071137c3..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/react/memory.error.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/react/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index fa6a6693ed..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/react/memory.not-found.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index b2c3d24200..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/react/memory.unmatched.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 6a399fe41e..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/react/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "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 deleted file mode 100644 index 0c98f54ddd..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/react/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 4e8e4ce0e4..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/react/src/routeTree.gen.ts +++ /dev/null @@ -1,146 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index e31bd0abf7..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/react/src/router.tsx +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index c5f9de6922..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/react/src/routes/__root.tsx +++ /dev/null @@ -1,27 +0,0 @@ -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 deleted file mode 100644 index fafa81a9bb..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/react/src/routes/boom.$id.tsx +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index 4c45e76c92..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/react/src/routes/from.$id.tsx +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index c5492486b4..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/react/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 84640e9712..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/react/src/routes/missing.$id.tsx +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index 1c13394cb2..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/react/src/routes/target.$id.tsx +++ /dev/null @@ -1,11 +0,0 @@ -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 deleted file mode 100644 index 2dba47fc99..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/react/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "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 deleted file mode 100644 index c00de7727a..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/react/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -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 deleted file mode 100644 index 11ed293d22..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/shared.ts +++ /dev/null @@ -1,192 +0,0 @@ -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 deleted file mode 100644 index a6f07b97be..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/solid/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 89071137c3..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/solid/memory.error.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/solid/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index fa6a6693ed..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/solid/memory.not-found.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index b2c3d24200..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/solid/memory.unmatched.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 77fcfaf578..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/solid/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "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 deleted file mode 100644 index 4fe85c3f00..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/solid/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 32a4d56d3a..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,146 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index ae51f8b5e9..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/solid/src/router.tsx +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index aaf7dfdd89..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/__root.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index bebc638caa..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/boom.$id.tsx +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index e96b7864f2..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/from.$id.tsx +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 43282af801..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 1b9ec5e29d..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/missing.$id.tsx +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index 4196fc1183..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/target.$id.tsx +++ /dev/null @@ -1,11 +0,0 @@ -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 deleted file mode 100644 index 1e8103127a..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/solid/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "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 deleted file mode 100644 index d7a0bb51b0..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/solid/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -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 deleted file mode 100644 index a6f07b97be..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/vue/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 89071137c3..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/vue/memory.error.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/vue/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index fa6a6693ed..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/vue/memory.not-found.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index b2c3d24200..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/vue/memory.unmatched.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 8472470bde..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/vue/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "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 deleted file mode 100644 index 6683dafe6b..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/vue/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index ea5bafa386..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,146 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 4290e7cdd3..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/vue/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index de29ee1612..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/__root.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index d933b93df2..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/boom.$id.tsx +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index 6ffba96bce..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/from.$id.tsx +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 53fb604c60..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 0e4972f5c6..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/missing.$id.tsx +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index 0bbf4a3dc6..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/target.$id.tsx +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index af8b83005c..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/vue/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "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 deleted file mode 100644 index 3dc0762aa0..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/vue/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -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 deleted file mode 100644 index 8f77c58731..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/large-page-data.ts +++ /dev/null @@ -1,111 +0,0 @@ -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 deleted file mode 100644 index 8b5f16ad63..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/react/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/react/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index 699a243a03..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/react/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "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 deleted file mode 100644 index 0c98f54ddd..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/react/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 6004590f9b..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routeTree.gen.ts +++ /dev/null @@ -1,305 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 7c4eb0babe..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/react/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index c5f9de6922..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/__root.tsx +++ /dev/null @@ -1,27 +0,0 @@ -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 deleted file mode 100644 index 25099720e4..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 0651ba886d..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.l4.l5.l6.l7.l8.tsx +++ /dev/null @@ -1,28 +0,0 @@ -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 deleted file mode 100644 index 1f89e6f454..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.l4.l5.l6.l7.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index 1a8c98ceb2..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.l4.l5.l6.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index 3e9afad0b9..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.l4.l5.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index 73c29bc402..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.l4.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index e5b57463ad..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index 18999233cc..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index 8fa7a5e0dc..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index 11ddcce4ea..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/react/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "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 deleted file mode 100644 index dcfcf1f92b..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/react/vite.config.ts +++ /dev/null @@ -1,31 +0,0 @@ -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 deleted file mode 100644 index 085e576244..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/shared.ts +++ /dev/null @@ -1,68 +0,0 @@ -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 deleted file mode 100644 index 8b5f16ad63..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/solid/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/solid/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index 85e8f83224..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/solid/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "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 deleted file mode 100644 index 4fe85c3f00..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/solid/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index c3ccdaaa0e..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,305 +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 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 deleted file mode 100644 index 038ec0ab5e..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index aaf7dfdd89..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/__root.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index 111ffaa36a..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index b0f94893fb..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.l4.l5.l6.l7.l8.tsx +++ /dev/null @@ -1,28 +0,0 @@ -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 deleted file mode 100644 index f8a3819c85..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.l4.l5.l6.l7.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index 7a438ddbd2..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.l4.l5.l6.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index 2e05985ac5..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.l4.l5.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index 4f38f0cb76..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.l4.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index 3f1f113fe3..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index bd338fd53f..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index 9dcfd7448a..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index 4b61264e11..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/solid/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "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 deleted file mode 100644 index 15b8c3a571..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/solid/vite.config.ts +++ /dev/null @@ -1,36 +0,0 @@ -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 deleted file mode 100644 index 8b5f16ad63..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index f424a2134f..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "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 deleted file mode 100644 index 6683dafe6b..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 26cc9f6058..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,305 +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 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 deleted file mode 100644 index 4290e7cdd3..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index de29ee1612..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/__root.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index e9a57d46fd..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 7f7a42d645..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.l6.l7.l8.tsx +++ /dev/null @@ -1,34 +0,0 @@ -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 deleted file mode 100644 index a99c56e529..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.l6.l7.tsx +++ /dev/null @@ -1,35 +0,0 @@ -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 deleted file mode 100644 index 3de3f03427..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.l6.tsx +++ /dev/null @@ -1,35 +0,0 @@ -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 deleted file mode 100644 index 5d936f83b5..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.tsx +++ /dev/null @@ -1,35 +0,0 @@ -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 deleted file mode 100644 index 8e10331f2d..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.tsx +++ /dev/null @@ -1,35 +0,0 @@ -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 deleted file mode 100644 index d69529c50c..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.tsx +++ /dev/null @@ -1,35 +0,0 @@ -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 deleted file mode 100644 index d04bc7f827..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.tsx +++ /dev/null @@ -1,35 +0,0 @@ -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 deleted file mode 100644 index a95ae7f9b0..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.tsx +++ /dev/null @@ -1,35 +0,0 @@ -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 deleted file mode 100644 index 9ad6481342..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "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 deleted file mode 100644 index 3fab2aff9e..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/vite.config.ts +++ /dev/null @@ -1,31 +0,0 @@ -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 deleted file mode 100644 index 8b5f16ad63..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/react/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/react/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index d997054b95..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/react/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "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 deleted file mode 100644 index 0c98f54ddd..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/react/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index d22f1bee18..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/react/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 7c4eb0babe..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/react/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index c5f9de6922..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/react/src/routes/__root.tsx +++ /dev/null @@ -1,27 +0,0 @@ -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 deleted file mode 100644 index e6335b0d83..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/react/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 5fd86ee5fb..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/react/src/routes/items.$id.tsx +++ /dev/null @@ -1,40 +0,0 @@ -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 deleted file mode 100644 index 11ddcce4ea..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/react/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "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 deleted file mode 100644 index 35adf6a249..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/react/vite.config.ts +++ /dev/null @@ -1,31 +0,0 @@ -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 deleted file mode 100644 index b200c96ed6..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/shared.ts +++ /dev/null @@ -1,82 +0,0 @@ -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 deleted file mode 100644 index 8b5f16ad63..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/solid/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/solid/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index 3f3434ee24..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/solid/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "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 deleted file mode 100644 index 4fe85c3f00..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/solid/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 8f49ec5d1f..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 038ec0ab5e..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/solid/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index aaf7dfdd89..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/solid/src/routes/__root.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index d32d31f301..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/solid/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index e687e22741..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/solid/src/routes/items.$id.tsx +++ /dev/null @@ -1,40 +0,0 @@ -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 deleted file mode 100644 index 4b61264e11..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/solid/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "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 deleted file mode 100644 index 6601309a74..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/solid/vite.config.ts +++ /dev/null @@ -1,36 +0,0 @@ -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 deleted file mode 100644 index 8b5f16ad63..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/vue/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/vue/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index 11eb1d868b..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/vue/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "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 deleted file mode 100644 index 6683dafe6b..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/vue/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 86ccc14a0c..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 4290e7cdd3..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/vue/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index de29ee1612..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/vue/src/routes/__root.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index 30751100a4..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/vue/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 570561f2a8..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/vue/src/routes/items.$id.tsx +++ /dev/null @@ -1,43 +0,0 @@ -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 deleted file mode 100644 index 9ad6481342..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/vue/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "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 deleted file mode 100644 index 7f15c5c7af..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/vue/vite.config.ts +++ /dev/null @@ -1,31 +0,0 @@ -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 deleted file mode 100644 index 8b5f16ad63..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/react/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/react/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index 467b40d734..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/react/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "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 deleted file mode 100644 index 0c98f54ddd..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/react/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 7e370fd84c..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/react/src/routeTree.gen.ts +++ /dev/null @@ -1,68 +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 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 deleted file mode 100644 index 7c4eb0babe..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/react/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index c5f9de6922..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/react/src/routes/__root.tsx +++ /dev/null @@ -1,27 +0,0 @@ -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 deleted file mode 100644 index cfba0dbd62..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/react/src/routes/data.$id.tsx +++ /dev/null @@ -1,15 +0,0 @@ -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 deleted file mode 100644 index 11ddcce4ea..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/react/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "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 deleted file mode 100644 index 1ed3bcc335..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/react/vite.config.ts +++ /dev/null @@ -1,31 +0,0 @@ -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 deleted file mode 100644 index b6f401640e..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/serialization-payload.ts +++ /dev/null @@ -1,115 +0,0 @@ -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 deleted file mode 100644 index 14ec8f7e0a..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/shared.ts +++ /dev/null @@ -1,75 +0,0 @@ -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 deleted file mode 100644 index 8b5f16ad63..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/solid/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/solid/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index 6f381ef389..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/solid/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "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 deleted file mode 100644 index 4fe85c3f00..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/solid/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 082cbb290c..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,68 +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 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 deleted file mode 100644 index 038ec0ab5e..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/solid/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index aaf7dfdd89..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/solid/src/routes/__root.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index 8cdbdb9046..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/solid/src/routes/data.$id.tsx +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index 4b61264e11..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/solid/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "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 deleted file mode 100644 index a2d04b986c..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/solid/vite.config.ts +++ /dev/null @@ -1,36 +0,0 @@ -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 deleted file mode 100644 index 8b5f16ad63..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/vue/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/vue/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index 425b50a0d5..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/vue/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "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 deleted file mode 100644 index 6683dafe6b..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/vue/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 8adce01d75..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,68 +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 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 deleted file mode 100644 index 4290e7cdd3..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/vue/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index de29ee1612..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/vue/src/routes/__root.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index 37b1a590e4..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/vue/src/routes/data.$id.tsx +++ /dev/null @@ -1,20 +0,0 @@ -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 deleted file mode 100644 index 9ad6481342..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/vue/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "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 deleted file mode 100644 index b63a561228..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/vue/vite.config.ts +++ /dev/null @@ -1,31 +0,0 @@ -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 deleted file mode 100644 index 8b5f16ad63..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/react/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/react/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index 841bbedca0..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/react/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "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 deleted file mode 100644 index 0c98f54ddd..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/react/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 22770278cd..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/react/src/fns.ts +++ /dev/null @@ -1,24 +0,0 @@ -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 deleted file mode 100644 index 10e933da3d..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/react/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 7c4eb0babe..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/react/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index c5f9de6922..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/react/src/routes/__root.tsx +++ /dev/null @@ -1,27 +0,0 @@ -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 deleted file mode 100644 index da74a20f62..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/react/src/routes/api.fn-urls.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index de0acfc2b3..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/react/src/routes/index.tsx +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index 11ddcce4ea..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/react/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "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 deleted file mode 100644 index f72cc53d6f..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/react/vite.config.ts +++ /dev/null @@ -1,31 +0,0 @@ -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 deleted file mode 100644 index 0f23390a6c..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/server-fn-payload.ts +++ /dev/null @@ -1,33 +0,0 @@ -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 deleted file mode 100644 index 167b24d3b6..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/shared.ts +++ /dev/null @@ -1,232 +0,0 @@ -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 deleted file mode 100644 index 8b5f16ad63..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/solid/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/solid/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index 53aca0cea6..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/solid/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "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 deleted file mode 100644 index 4fe85c3f00..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/solid/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 31669dff50..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/solid/src/fns.ts +++ /dev/null @@ -1,24 +0,0 @@ -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 deleted file mode 100644 index 298ac3168d..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 038ec0ab5e..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/solid/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index aaf7dfdd89..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/solid/src/routes/__root.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index 2063684034..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/solid/src/routes/api.fn-urls.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 99fea371f8..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/solid/src/routes/index.tsx +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index 4b61264e11..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/solid/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "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 deleted file mode 100644 index 4fba196bd2..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/solid/vite.config.ts +++ /dev/null @@ -1,36 +0,0 @@ -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 deleted file mode 100644 index 8b5f16ad63..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/vue/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/vue/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index c5809a259b..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/vue/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "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 deleted file mode 100644 index 6683dafe6b..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/vue/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 0fa679f76f..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/vue/src/fns.ts +++ /dev/null @@ -1,24 +0,0 @@ -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 deleted file mode 100644 index b226f0a25a..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 4290e7cdd3..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/vue/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index de29ee1612..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/vue/src/routes/__root.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index ff99e89e4c..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/vue/src/routes/api.fn-urls.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 0a39b9301c..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/vue/src/routes/index.tsx +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index 9ad6481342..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/vue/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "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 deleted file mode 100644 index 5ab5ec37e3..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/vue/vite.config.ts +++ /dev/null @@ -1,31 +0,0 @@ -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 deleted file mode 100644 index b30352ef39..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/deferred-section-data.ts +++ /dev/null @@ -1,37 +0,0 @@ -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 deleted file mode 100644 index 8b5f16ad63..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/react/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/react/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index 6fc1dcdda0..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/react/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "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 deleted file mode 100644 index 0c98f54ddd..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/react/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index fbbc25ecfb..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/react/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 7c4eb0babe..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/react/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index c5f9de6922..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/react/src/routes/__root.tsx +++ /dev/null @@ -1,27 +0,0 @@ -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 deleted file mode 100644 index 669fdef2e1..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/react/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 886cb64d45..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/react/src/routes/stream.$id.tsx +++ /dev/null @@ -1,98 +0,0 @@ -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 deleted file mode 100644 index 11ddcce4ea..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/react/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "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 deleted file mode 100644 index 5d555441b6..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/react/vite.config.ts +++ /dev/null @@ -1,31 +0,0 @@ -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 deleted file mode 100644 index c027047408..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/shared.ts +++ /dev/null @@ -1,117 +0,0 @@ -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 deleted file mode 100644 index 8b5f16ad63..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/solid/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/solid/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index 80f44d1063..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/solid/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "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 deleted file mode 100644 index 4fe85c3f00..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/solid/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 04ebed80f0..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 038ec0ab5e..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/solid/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index aaf7dfdd89..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/solid/src/routes/__root.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index 5815e36b3d..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/solid/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 977f43061e..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/solid/src/routes/stream.$id.tsx +++ /dev/null @@ -1,91 +0,0 @@ -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 deleted file mode 100644 index 4b61264e11..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/solid/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "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 deleted file mode 100644 index 5fbdb48c23..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/solid/vite.config.ts +++ /dev/null @@ -1,36 +0,0 @@ -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 deleted file mode 100644 index 8b5f16ad63..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/vue/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/vue/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index 55771aebe3..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/vue/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "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 deleted file mode 100644 index 6683dafe6b..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/vue/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 192f1d6dc7..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 4290e7cdd3..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/vue/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index de29ee1612..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/vue/src/routes/__root.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index bc55b49adc..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/vue/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 750d1cb47d..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/vue/src/routes/stream.$id.tsx +++ /dev/null @@ -1,103 +0,0 @@ -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 deleted file mode 100644 index 9ad6481342..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/vue/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "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 deleted file mode 100644 index cd848584a5..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/vue/vite.config.ts +++ /dev/null @@ -1,31 +0,0 @@ -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 deleted file mode 100644 index 86d36f047a..0000000000 --- a/benchmarks/memory/server/tsconfig.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "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 deleted file mode 100644 index 44643b4d60..0000000000 --- a/benchmarks/memory/server/vitest.react.config.ts +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 5c8185cdd9..0000000000 --- a/benchmarks/memory/server/vitest.solid.config.ts +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 01768185ee..0000000000 --- a/benchmarks/memory/server/vitest.vue.config.ts +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 5a325f3b6c..0000000000 --- a/benchmarks/memory/tsconfig.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "../../tsconfig.json", - "compilerOptions": { - "types": ["node"] - }, - "include": ["runtime.ts"] -} diff --git a/benchmarks/memory/turn.ts b/benchmarks/memory/turn.ts deleted file mode 100644 index 08729685fe..0000000000 --- a/benchmarks/memory/turn.ts +++ /dev/null @@ -1,34 +0,0 @@ -export function isMemoryInstrumented() { - return ( - process.env.CODSPEED_ENV !== undefined && - process.env.CODSPEED_RUNNER_MODE === 'memory' - ) -} - -// CodSpeed calls beforeEach before its forced GC and measurement marker. End -// the previous warmup's job so WeakRef targets can be released by that GC. -export function endMemoryTurn() { - return new Promise((resolve) => setImmediate(resolve)) -} - -/** - * Per-invocation bench hooks. CodSpeed runs them around every warmup - * invocation and the measured one, outside the measurement marker: the turn - * ends first, then the workload prepares fresh state before the forced GC. - */ -export function memoryBenchHooks( - workload: { - before?: () => Promise | void - after?: () => Promise | void - } = {}, -) { - return { - async beforeEach() { - if (isMemoryInstrumented()) { - await endMemoryTurn() - } - await workload.before?.() - }, - afterEach: workload.after, - } -} diff --git a/benchmarks/ssr/README.md b/benchmarks/ssr/README.md index 3d90af1598..9fb429ecfe 100644 --- a/benchmarks/ssr/README.md +++ b/benchmarks/ssr/README.md @@ -10,106 +10,28 @@ Each benchmark builds a Start app with file-based routes and runs Vitest benches ## 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. | +- `react/` - React Start benchmark + Vitest config +- `solid/` - Solid Start benchmark + Vitest config +- `vue/` - Vue Start benchmark + Vitest config ## 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 +CI=1 NX_DAEMON=false 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 +CI=1 NX_DAEMON=false pnpm nx run @benchmarks/ssr:test:perf:react --outputStyle=stream --skipRemoteCache +CI=1 NX_DAEMON=false pnpm nx run @benchmarks/ssr:test:perf:solid --outputStyle=stream --skipRemoteCache +CI=1 NX_DAEMON=false pnpm nx run @benchmarks/ssr:test:perf:vue --outputStyle=stream --skipRemoteCache ``` Typecheck benchmark sources: ```bash -pnpm nx run @benchmarks/ssr:test:types --outputStyle=stream --skipRemoteCache +CI=1 NX_DAEMON=false 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 deleted file mode 100644 index c6a520447b..0000000000 --- a/benchmarks/ssr/bench-utils.test.ts +++ /dev/null @@ -1,145 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { buildRequestSequences, runRequestLoop } from './bench-utils' -import type { StartRequestHandler } from './bench-utils' - -function deferred() { - let resolve = () => {} - const promise = new Promise((resolvePromise) => { - resolve = resolvePromise - }) - return { promise, resolve } -} - -describe('runRequestLoop', () => { - it('caps fixed concurrency and waits for every streaming body', async () => { - const concurrency = 4 - const totalRequests = 20 - const firstWaveStarted = deferred() - let builtRequests = 0 - let executedRequests = 0 - let validatedResponses = 0 - let finishedBodies = 0 - let inFlightRequests = 0 - let maximumInFlightRequests = 0 - - const handler: StartRequestHandler = { - fetch() { - expect(builtRequests).toBe(totalRequests) - executedRequests += 1 - inFlightRequests += 1 - maximumInFlightRequests = Math.max( - maximumInFlightRequests, - inFlightRequests, - ) - - if (inFlightRequests === concurrency) { - firstWaveStarted.resolve() - } - - const body = new ReadableStream({ - async start(controller) { - await firstWaveStarted.promise - controller.enqueue(new Uint8Array([1])) - controller.close() - finishedBodies += 1 - inFlightRequests -= 1 - }, - }) - - return new Response(body) - }, - } - - await runRequestLoop(handler, { - seed: 123, - concurrency, - totalRequests, - buildRequest: (_random, index) => { - builtRequests += 1 - return new Request(`http://localhost/request/${index}`) - }, - validateResponse: () => { - validatedResponses += 1 - }, - }) - - expect(builtRequests).toBe(totalRequests) - expect(executedRequests).toBe(totalRequests) - expect(validatedResponses).toBe(totalRequests) - expect(maximumInFlightRequests).toBe(concurrency) - expect(inFlightRequests).toBe(0) - expect(finishedBodies).toBe(totalRequests) - }) - - it('builds identical predetermined worker sequences from identical seeds', () => { - const buildSequences = (seed: number) => - buildRequestSequences({ - seed, - concurrency: 4, - totalRequests: 12, - buildRequest: (random, index) => - new Request( - `http://localhost/request/${index}?value=${random().toString(36)}`, - ), - }).map((requests) => requests.map((request) => request.url)) - - const first = buildSequences(456) - const second = buildSequences(456) - - expect(second).toEqual(first) - expect(first.map((requests) => requests.map(requestIndex))).toEqual([ - [0, 4, 8], - [1, 5, 9], - [2, 6, 10], - [3, 7, 11], - ]) - }) - - it('drains every started body before reporting a worker failure', async () => { - const concurrency = 4 - const firstWaveStarted = deferred() - let executedRequests = 0 - let finishedBodies = 0 - let inFlightRequests = 0 - - const handler: StartRequestHandler = { - fetch(request) { - executedRequests += 1 - inFlightRequests += 1 - if (inFlightRequests === concurrency) { - firstWaveStarted.resolve() - } - - const body = new ReadableStream({ - async start(controller) { - await firstWaveStarted.promise - controller.close() - finishedBodies += 1 - inFlightRequests -= 1 - }, - }) - - return new Response(body, { - status: request.url.endsWith('/0') ? 500 : 200, - }) - }, - } - - await expect( - runRequestLoop(handler, { - seed: 789, - concurrency, - totalRequests: 12, - buildRequest: (_random, index) => - new Request(`http://localhost/request/${index}`), - }), - ).rejects.toThrow('non-200 status 500') - - expect(finishedBodies).toBe(executedRequests) - expect(inFlightRequests).toBe(0) - }) -}) - -function requestIndex(url: string) { - return Number(new URL(url).pathname.split('/').at(-1)) -} diff --git a/benchmarks/ssr/bench-utils.ts b/benchmarks/ssr/bench-utils.ts index 7a54fce897..14f8a56ddb 100644 --- a/benchmarks/ssr/bench-utils.ts +++ b/benchmarks/ssr/bench-utils.ts @@ -7,14 +7,6 @@ export interface RunSsrRequestLoopOptions { 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: { @@ -35,28 +27,6 @@ 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)}` } @@ -90,116 +60,8 @@ export async function runSsrRequestLoop( ) } - pendingBodyReads.push(drainResponse(response)) + pendingBodyReads.push(response.text().then(() => undefined)) } 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 index 20c1837468..1e986c31b6 100644 --- a/benchmarks/ssr/package.json +++ b/benchmarks/ssr/package.json @@ -2,6 +2,19 @@ "name": "@benchmarks/ssr", "private": true, "type": "module", + "scripts": { + "build:react": "vite build --config ./react/vite.config.ts", + "build:solid": "vite build --config ./solid/vite.config.ts", + "build:vue": "vite build --config ./vue/vite.config.ts", + "test:perf": "vitest bench", + "test:perf:react": "vitest bench --config ./react/vite.config.ts ./react/speed.bench.ts", + "test:perf:solid": "vitest bench --config ./solid/vite.config.ts ./solid/speed.bench.ts", + "test:perf:vue": "vitest bench --config ./vue/vite.config.ts ./vue/speed.bench.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/react-router": "workspace:^", "@tanstack/react-start": "workspace:^", @@ -11,219 +24,84 @@ "@tanstack/vue-start": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "solid-js": "^1.9.10", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", "vue": "^3.5.16" }, "devDependencies": { - "@codspeed/vitest-plugin": "^6.0.1", + "@codspeed/vitest-plugin": "^5.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:" + "typescript": "^5.7.2", + "vite": "^8.0.0", + "vite-plugin-solid": "3.0.0-next.3", + "vitest": "^4.0.17" }, "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" + "@tanstack/react-start" ], - "target": "build:ssr" + "target": "build" } ] }, "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" + "@tanstack/solid-start" ], - "target": "build:ssr" + "target": "build" } ] }, "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" + "@tanstack/vue-start" ], - "target": "build:ssr" + "target": "build" } ] }, "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" - }, + "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", - "@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" + "^build" ] } } diff --git a/benchmarks/ssr/react/project.json b/benchmarks/ssr/react/project.json deleted file mode 100644 index d7f674cc83..0000000000 --- a/benchmarks/ssr/react/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 index 6825a7ddfb..89bfd54318 100644 --- a/benchmarks/ssr/react/speed.bench.ts +++ b/benchmarks/ssr/react/speed.bench.ts @@ -1,22 +1,50 @@ -import { test } from 'vitest' +import { afterAll, beforeAll, bench, describe } 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 appModulePath = './dist/server/server.js' const benchmarkSeed = 0xdecafbad -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler +const uninitializedHandler: StartRequestHandler = { + fetch: () => Promise.reject(new Error('Benchmark not initialized')), } -test('ssr', async ({ bench }) => { - await bench('ssr request loop (react)', async () => - runSsrRequestLoop(handler, { seed: benchmarkSeed }), - ).run({ - warmupIterations: 100, - time: 10_000, - throws: true, - }) +let handler = uninitializedHandler + +async function setup() { + const module = (await import(appModulePath)) as { + default: StartRequestHandler + } + + handler = module.default +} + +function teardown() { + handler = uninitializedHandler +} + +describe('ssr', () => { + /** + * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, + * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. + * + * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, + * but it does support `beforeAll` and `afterAll`. + * + * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. + */ + beforeAll(setup) + afterAll(teardown) + + bench( + 'ssr request loop (react)', + () => runSsrRequestLoop(handler, { seed: benchmarkSeed }), + { + warmupIterations: 100, + time: 10_000, + setup, + teardown, + throws: true, + }, + ) }) diff --git a/benchmarks/ssr/react/vite.config.ts b/benchmarks/ssr/react/vite.config.ts index e607db366b..04f15c3959 100644 --- a/benchmarks/ssr/react/vite.config.ts +++ b/benchmarks/ssr/react/vite.config.ts @@ -3,7 +3,6 @@ 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)) @@ -23,8 +22,6 @@ export default defineConfig({ minify: false, }, test: { - execArgv: cpuSimulationExecArgv(), - isolate: true, name: '@benchmarks/ssr (react)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/assets/react/project.json b/benchmarks/ssr/scenarios/assets/react/project.json deleted file mode 100644 index a2d5a6c8ba..0000000000 --- a/benchmarks/ssr/scenarios/assets/react/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 deleted file mode 100644 index 0496613afb..0000000000 --- a/benchmarks/ssr/scenarios/assets/react/speed.assets-linked-css-control.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 7dc57d89f1..0000000000 --- a/benchmarks/ssr/scenarios/assets/react/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 201df5fd3b..0000000000 --- a/benchmarks/ssr/scenarios/assets/react/src/routeTree.gen.ts +++ /dev/null @@ -1,94 +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 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 deleted file mode 100644 index 7c4eb0babe..0000000000 --- a/benchmarks/ssr/scenarios/assets/react/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 8c46c7060a..0000000000 --- a/benchmarks/ssr/scenarios/assets/react/src/routes/__root.tsx +++ /dev/null @@ -1,31 +0,0 @@ -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 deleted file mode 100644 index be709e53e6..0000000000 --- a/benchmarks/ssr/scenarios/assets/react/src/routes/a.$x.$y.tsx +++ /dev/null @@ -1,26 +0,0 @@ -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 deleted file mode 100644 index ecc7de680a..0000000000 --- a/benchmarks/ssr/scenarios/assets/react/src/routes/a.$x.tsx +++ /dev/null @@ -1,25 +0,0 @@ -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 deleted file mode 100644 index 64fb21708c..0000000000 --- a/benchmarks/ssr/scenarios/assets/react/src/server.ts +++ /dev/null @@ -1,45 +0,0 @@ -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 deleted file mode 100644 index d3511ddd85..0000000000 --- a/benchmarks/ssr/scenarios/assets/react/src/styles/assets-a.css +++ /dev/null @@ -1,8 +0,0 @@ -.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 deleted file mode 100644 index 55e051b9a5..0000000000 --- a/benchmarks/ssr/scenarios/assets/react/src/styles/assets-leaf.css +++ /dev/null @@ -1,8 +0,0 @@ -.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 deleted file mode 100644 index cf14e1d440..0000000000 --- a/benchmarks/ssr/scenarios/assets/react/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "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 deleted file mode 100644 index 5990bba6d3..0000000000 --- a/benchmarks/ssr/scenarios/assets/react/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -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 deleted file mode 100644 index ec811794e3..0000000000 --- a/benchmarks/ssr/scenarios/assets/shared.ts +++ /dev/null @@ -1,88 +0,0 @@ -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 deleted file mode 100644 index 47f483df11..0000000000 --- a/benchmarks/ssr/scenarios/assets/solid/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index f6f7ffe57e..0000000000 --- a/benchmarks/ssr/scenarios/assets/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,94 +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 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 deleted file mode 100644 index 038ec0ab5e..0000000000 --- a/benchmarks/ssr/scenarios/assets/solid/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index ca760406ce..0000000000 --- a/benchmarks/ssr/scenarios/assets/solid/src/routes/__root.tsx +++ /dev/null @@ -1,31 +0,0 @@ -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 deleted file mode 100644 index 2a3d35cb68..0000000000 --- a/benchmarks/ssr/scenarios/assets/solid/src/routes/a.$x.$y.tsx +++ /dev/null @@ -1,26 +0,0 @@ -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 deleted file mode 100644 index 2209addcbe..0000000000 --- a/benchmarks/ssr/scenarios/assets/solid/src/routes/a.$x.tsx +++ /dev/null @@ -1,25 +0,0 @@ -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 deleted file mode 100644 index 541e776a79..0000000000 --- a/benchmarks/ssr/scenarios/assets/solid/src/server.ts +++ /dev/null @@ -1,45 +0,0 @@ -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 deleted file mode 100644 index d3511ddd85..0000000000 --- a/benchmarks/ssr/scenarios/assets/solid/src/styles/assets-a.css +++ /dev/null @@ -1,8 +0,0 @@ -.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 deleted file mode 100644 index 55e051b9a5..0000000000 --- a/benchmarks/ssr/scenarios/assets/solid/src/styles/assets-leaf.css +++ /dev/null @@ -1,8 +0,0 @@ -.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 deleted file mode 100644 index 42c3a2160f..0000000000 --- a/benchmarks/ssr/scenarios/assets/solid/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "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 deleted file mode 100644 index 3ee54e5ae2..0000000000 --- a/benchmarks/ssr/scenarios/assets/solid/vite.config.ts +++ /dev/null @@ -1,42 +0,0 @@ -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 deleted file mode 100644 index 9667ff902c..0000000000 --- a/benchmarks/ssr/scenarios/assets/vue/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 deleted file mode 100644 index e56d41df6b..0000000000 --- a/benchmarks/ssr/scenarios/assets/vue/speed.assets-linked-css-control.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 3f77a0dcc1..0000000000 --- a/benchmarks/ssr/scenarios/assets/vue/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 2a6eb91f50..0000000000 --- a/benchmarks/ssr/scenarios/assets/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,94 +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 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 deleted file mode 100644 index 4290e7cdd3..0000000000 --- a/benchmarks/ssr/scenarios/assets/vue/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 760545d248..0000000000 --- a/benchmarks/ssr/scenarios/assets/vue/src/routes/__root.tsx +++ /dev/null @@ -1,33 +0,0 @@ -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 deleted file mode 100644 index a29fe59f22..0000000000 --- a/benchmarks/ssr/scenarios/assets/vue/src/routes/a.$x.$y.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index e1fe0418e4..0000000000 --- a/benchmarks/ssr/scenarios/assets/vue/src/routes/a.$x.tsx +++ /dev/null @@ -1,28 +0,0 @@ -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 deleted file mode 100644 index fd1e83d6b8..0000000000 --- a/benchmarks/ssr/scenarios/assets/vue/src/server.ts +++ /dev/null @@ -1,45 +0,0 @@ -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 deleted file mode 100644 index d3511ddd85..0000000000 --- a/benchmarks/ssr/scenarios/assets/vue/src/styles/assets-a.css +++ /dev/null @@ -1,8 +0,0 @@ -.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 deleted file mode 100644 index 55e051b9a5..0000000000 --- a/benchmarks/ssr/scenarios/assets/vue/src/styles/assets-leaf.css +++ /dev/null @@ -1,8 +0,0 @@ -.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 deleted file mode 100644 index 08c94853f4..0000000000 --- a/benchmarks/ssr/scenarios/assets/vue/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "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 deleted file mode 100644 index e664b9b02b..0000000000 --- a/benchmarks/ssr/scenarios/assets/vue/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -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 deleted file mode 100644 index df2004f1f5..0000000000 --- a/benchmarks/ssr/scenarios/before-load/react/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 deleted file mode 100644 index 8a4355a168..0000000000 --- a/benchmarks/ssr/scenarios/before-load/react/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 068b5a5433..0000000000 --- a/benchmarks/ssr/scenarios/before-load/react/src/routeTree.gen.ts +++ /dev/null @@ -1,120 +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 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 deleted file mode 100644 index 7c4eb0babe..0000000000 --- a/benchmarks/ssr/scenarios/before-load/react/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 71719a4f88..0000000000 --- a/benchmarks/ssr/scenarios/before-load/react/src/routes/$a.$b.$c.tsx +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 1a148e05fa..0000000000 --- a/benchmarks/ssr/scenarios/before-load/react/src/routes/$a.$b.tsx +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index b5dcca33c3..0000000000 --- a/benchmarks/ssr/scenarios/before-load/react/src/routes/$a.tsx +++ /dev/null @@ -1,13 +0,0 @@ -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 deleted file mode 100644 index ff1da4c304..0000000000 --- a/benchmarks/ssr/scenarios/before-load/react/src/routes/__root.tsx +++ /dev/null @@ -1,24 +0,0 @@ -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 deleted file mode 100644 index 232763bbe1..0000000000 --- a/benchmarks/ssr/scenarios/before-load/react/tsconfig.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "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 deleted file mode 100644 index 3fd72c5f1d..0000000000 --- a/benchmarks/ssr/scenarios/before-load/react/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -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 deleted file mode 100644 index cf3a02f114..0000000000 --- a/benchmarks/ssr/scenarios/before-load/shared-bench.ts +++ /dev/null @@ -1,64 +0,0 @@ -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 deleted file mode 100644 index 3c895aca03..0000000000 --- a/benchmarks/ssr/scenarios/before-load/shared.ts +++ /dev/null @@ -1,10 +0,0 @@ -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 deleted file mode 100644 index 804cd9c1b0..0000000000 --- a/benchmarks/ssr/scenarios/before-load/solid/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 deleted file mode 100644 index 27e0d3a64c..0000000000 --- a/benchmarks/ssr/scenarios/before-load/solid/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 7b299cfcd1..0000000000 --- a/benchmarks/ssr/scenarios/before-load/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,120 +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 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 deleted file mode 100644 index 038ec0ab5e..0000000000 --- a/benchmarks/ssr/scenarios/before-load/solid/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 7966bcc4c2..0000000000 --- a/benchmarks/ssr/scenarios/before-load/solid/src/routes/$a.$b.$c.tsx +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 90656dc7a1..0000000000 --- a/benchmarks/ssr/scenarios/before-load/solid/src/routes/$a.$b.tsx +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index 6336f56640..0000000000 --- a/benchmarks/ssr/scenarios/before-load/solid/src/routes/$a.tsx +++ /dev/null @@ -1,13 +0,0 @@ -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 deleted file mode 100644 index e59de72236..0000000000 --- a/benchmarks/ssr/scenarios/before-load/solid/src/routes/__root.tsx +++ /dev/null @@ -1,24 +0,0 @@ -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 deleted file mode 100644 index 0995292743..0000000000 --- a/benchmarks/ssr/scenarios/before-load/solid/tsconfig.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "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 deleted file mode 100644 index a20e32742e..0000000000 --- a/benchmarks/ssr/scenarios/before-load/solid/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -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 deleted file mode 100644 index 92d724821e..0000000000 --- a/benchmarks/ssr/scenarios/before-load/vue/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 deleted file mode 100644 index 8684c159eb..0000000000 --- a/benchmarks/ssr/scenarios/before-load/vue/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 24ee6c3b9d..0000000000 --- a/benchmarks/ssr/scenarios/before-load/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,120 +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 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 deleted file mode 100644 index 4290e7cdd3..0000000000 --- a/benchmarks/ssr/scenarios/before-load/vue/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 178d4071eb..0000000000 --- a/benchmarks/ssr/scenarios/before-load/vue/src/routes/$a.$b.$c.tsx +++ /dev/null @@ -1,26 +0,0 @@ -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 deleted file mode 100644 index 43ea0dcf87..0000000000 --- a/benchmarks/ssr/scenarios/before-load/vue/src/routes/$a.$b.tsx +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index 7f036dceac..0000000000 --- a/benchmarks/ssr/scenarios/before-load/vue/src/routes/$a.tsx +++ /dev/null @@ -1,13 +0,0 @@ -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 deleted file mode 100644 index 49422aac38..0000000000 --- a/benchmarks/ssr/scenarios/before-load/vue/src/routes/__root.tsx +++ /dev/null @@ -1,26 +0,0 @@ -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 deleted file mode 100644 index 33e5cc442d..0000000000 --- a/benchmarks/ssr/scenarios/before-load/vue/tsconfig.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "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 deleted file mode 100644 index 093776869f..0000000000 --- a/benchmarks/ssr/scenarios/before-load/vue/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -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 deleted file mode 100644 index 80086788eb..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/react/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 deleted file mode 100644 index 899f400799..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/react/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 0a93c5eac3..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/react/speed.control-flow-error-500.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 53e09fd34e..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/react/speed.control-flow-route-headers.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 1cd7c1044c..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/react/speed.control-flow-unmatched-404.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 1e8abfd318..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/react/speed.not-found.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 4d4424c222..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/react/src/routeTree.gen.ts +++ /dev/null @@ -1,177 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 7c4eb0babe..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/react/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index e08ff06361..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/react/src/routes/__root.tsx +++ /dev/null @@ -1,30 +0,0 @@ -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 deleted file mode 100644 index eb47d34070..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/react/src/routes/boom.$id.tsx +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index e9289fce30..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/react/src/routes/from.$id.tsx +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 412d056d85..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/react/src/routes/headers.$id.tsx +++ /dev/null @@ -1,15 +0,0 @@ -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 deleted file mode 100644 index e9886f60c4..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/react/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index b7d760e562..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/react/src/routes/missing.$id.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index 1c13394cb2..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/react/src/routes/target.$id.tsx +++ /dev/null @@ -1,11 +0,0 @@ -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 deleted file mode 100644 index cf14e1d440..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/react/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "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 deleted file mode 100644 index 273d7d9d80..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/react/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -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 deleted file mode 100644 index 307665d59d..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/shared.ts +++ /dev/null @@ -1,230 +0,0 @@ -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 deleted file mode 100644 index 57a2f0fbe9..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/solid/speed.control-flow-error-500.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 6581e92b39..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/solid/speed.control-flow-route-headers.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 40f1679320..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/solid/speed.control-flow-unmatched-404.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index efcb7cc229..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/solid/speed.not-found.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 3cec17d9c8..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,177 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 038ec0ab5e..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/solid/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index dc8b783e76..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/solid/src/routes/__root.tsx +++ /dev/null @@ -1,30 +0,0 @@ -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 deleted file mode 100644 index 0bcc4dc02b..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/solid/src/routes/boom.$id.tsx +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index a319375db3..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/solid/src/routes/from.$id.tsx +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 9d87b4a354..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/solid/src/routes/headers.$id.tsx +++ /dev/null @@ -1,15 +0,0 @@ -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 deleted file mode 100644 index 96b26a2d6c..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/solid/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index e5c42b56dc..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/solid/src/routes/missing.$id.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index 4196fc1183..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/solid/src/routes/target.$id.tsx +++ /dev/null @@ -1,11 +0,0 @@ -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 deleted file mode 100644 index 42c3a2160f..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/solid/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "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 deleted file mode 100644 index c75c957466..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/solid/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -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 deleted file mode 100644 index e0e014e588..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/vue/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 deleted file mode 100644 index 0b95f426f2..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/vue/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 262ca951af..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/vue/speed.control-flow-error-500.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index bf8c90a8a1..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/vue/speed.control-flow-route-headers.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index d7f8ebeb9e..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/vue/speed.control-flow-unmatched-404.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 4b84fb594c..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/vue/speed.not-found.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 6dcf0d095e..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,177 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 4290e7cdd3..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/vue/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 815466918a..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/vue/src/routes/__root.tsx +++ /dev/null @@ -1,32 +0,0 @@ -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 deleted file mode 100644 index dfae636ae7..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/vue/src/routes/boom.$id.tsx +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index dfb90a51f8..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/vue/src/routes/from.$id.tsx +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 20c1bbe5ac..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/vue/src/routes/headers.$id.tsx +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index 51a503a1d1..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/vue/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index b15333f5a3..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/vue/src/routes/missing.$id.tsx +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index 0bbf4a3dc6..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/vue/src/routes/target.$id.tsx +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 08c94853f4..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/vue/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "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 deleted file mode 100644 index 1b77968d96..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/vue/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -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 deleted file mode 100644 index d2784aed38..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/bench.ts +++ /dev/null @@ -1,309 +0,0 @@ -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 deleted file mode 100644 index bded6925fd..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 deleted file mode 100644 index cb3f9f427c..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/speed.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -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 deleted file mode 100644 index 48c444de77..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-fn.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -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 deleted file mode 100644 index 22f53883ee..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-0-middleware.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { test } from 'vitest' -import { - assertGlobalMiddlewareScenario, - globalMiddlewareBenchOptions, - runGlobalMiddlewareServerRouteLoop, - setupGlobalMiddlewareBench, -} from '../bench' -import type { StartRequestHandler } from '../bench' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} -const context = await setupGlobalMiddlewareBench(handler) - -await assertGlobalMiddlewareScenario(handler, context) - -test('ssr', async ({ bench }) => { - await bench('ssr global-mw server-route 0 middleware (react)', async () => - runGlobalMiddlewareServerRouteLoop(handler, 0), - ).run(globalMiddlewareBenchOptions) -}) diff --git a/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-1-middleware.bench.ts b/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-1-middleware.bench.ts deleted file mode 100644 index f01b48d66e..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-1-middleware.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { test } from 'vitest' -import { - assertGlobalMiddlewareScenario, - globalMiddlewareBenchOptions, - runGlobalMiddlewareServerRouteLoop, - setupGlobalMiddlewareBench, -} from '../bench' -import type { StartRequestHandler } from '../bench' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} -const context = await setupGlobalMiddlewareBench(handler) - -await assertGlobalMiddlewareScenario(handler, context) - -test('ssr', async ({ bench }) => { - await bench('ssr global-mw server-route 1 middleware (react)', async () => - runGlobalMiddlewareServerRouteLoop(handler, 1), - ).run(globalMiddlewareBenchOptions) -}) diff --git a/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-2-middleware.bench.ts b/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-2-middleware.bench.ts deleted file mode 100644 index b01957f806..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-2-middleware.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { test } from 'vitest' -import { - assertGlobalMiddlewareScenario, - globalMiddlewareBenchOptions, - runGlobalMiddlewareServerRouteLoop, - setupGlobalMiddlewareBench, -} from '../bench' -import type { StartRequestHandler } from '../bench' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} -const context = await setupGlobalMiddlewareBench(handler) - -await assertGlobalMiddlewareScenario(handler, context) - -test('ssr', async ({ bench }) => { - await bench('ssr global-mw server-route 2 middlewares (react)', async () => - runGlobalMiddlewareServerRouteLoop(handler, 2), - ).run(globalMiddlewareBenchOptions) -}) diff --git a/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route.bench.ts b/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route.bench.ts deleted file mode 100644 index 08d97fcaf6..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { test } from 'vitest' -import { - assertGlobalMiddlewareScenario, - globalMiddlewareBenchOptions, - runGlobalMiddlewareServerRouteLoop, - setupGlobalMiddlewareBench, -} from '../bench' -import type { StartRequestHandler } from '../bench' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} -const context = await setupGlobalMiddlewareBench(handler) - -await assertGlobalMiddlewareScenario(handler, context) - -test('ssr', async ({ bench }) => { - await bench('ssr global-mw server-route 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 deleted file mode 100644 index 68cfd992c6..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/src/fns.ts +++ /dev/null @@ -1,34 +0,0 @@ -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 deleted file mode 100644 index 8dfaa80562..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/src/routeTree.gen.ts +++ /dev/null @@ -1,123 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 7c4eb0babe..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index ff1da4c304..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/src/routes/__root.tsx +++ /dev/null @@ -1,24 +0,0 @@ -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 deleted file mode 100644 index bcb2111930..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/src/routes/api.fn-urls.ts +++ /dev/null @@ -1,10 +0,0 @@ -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 deleted file mode 100644 index 434833f018..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/src/routes/api.ping.$id.ts +++ /dev/null @@ -1,22 +0,0 @@ -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 deleted file mode 100644 index a0d3aec869..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/src/routes/index.tsx +++ /dev/null @@ -1,10 +0,0 @@ -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 deleted file mode 100644 index 6b7a42c12e..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/src/routes/page.$id.tsx +++ /dev/null @@ -1,22 +0,0 @@ -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 deleted file mode 100644 index 8dfb2dd3c4..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/src/start.ts +++ /dev/null @@ -1,88 +0,0 @@ -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 deleted file mode 100644 index de4a3204b9..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/tsconfig.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "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 deleted file mode 100644 index 968a8a24e9..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -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 deleted file mode 100644 index 8fbe788911..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/shared.ts +++ /dev/null @@ -1,77 +0,0 @@ -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 deleted file mode 100644 index d325c15527..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 deleted file mode 100644 index 0e5f504090..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/speed.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -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 deleted file mode 100644 index 915507ef9f..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-fn.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -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 deleted file mode 100644 index a791145935..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-0-middleware.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { test } from 'vitest' -import { - assertGlobalMiddlewareScenario, - globalMiddlewareBenchOptions, - runGlobalMiddlewareServerRouteLoop, - setupGlobalMiddlewareBench, -} from '../bench' -import type { StartRequestHandler } from '../bench' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} -const context = await setupGlobalMiddlewareBench(handler) - -await assertGlobalMiddlewareScenario(handler, context) - -test('ssr', async ({ bench }) => { - await bench('ssr global-mw server-route 0 middleware (solid)', async () => - runGlobalMiddlewareServerRouteLoop(handler, 0), - ).run(globalMiddlewareBenchOptions) -}) diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-1-middleware.bench.ts b/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-1-middleware.bench.ts deleted file mode 100644 index 1baab0f344..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-1-middleware.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { test } from 'vitest' -import { - assertGlobalMiddlewareScenario, - globalMiddlewareBenchOptions, - runGlobalMiddlewareServerRouteLoop, - setupGlobalMiddlewareBench, -} from '../bench' -import type { StartRequestHandler } from '../bench' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} -const context = await setupGlobalMiddlewareBench(handler) - -await assertGlobalMiddlewareScenario(handler, context) - -test('ssr', async ({ bench }) => { - await bench('ssr global-mw server-route 1 middleware (solid)', async () => - runGlobalMiddlewareServerRouteLoop(handler, 1), - ).run(globalMiddlewareBenchOptions) -}) diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-2-middleware.bench.ts b/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-2-middleware.bench.ts deleted file mode 100644 index d6fde20764..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-2-middleware.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { test } from 'vitest' -import { - assertGlobalMiddlewareScenario, - globalMiddlewareBenchOptions, - runGlobalMiddlewareServerRouteLoop, - setupGlobalMiddlewareBench, -} from '../bench' -import type { StartRequestHandler } from '../bench' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} -const context = await setupGlobalMiddlewareBench(handler) - -await assertGlobalMiddlewareScenario(handler, context) - -test('ssr', async ({ bench }) => { - await bench('ssr global-mw server-route 2 middlewares (solid)', async () => - runGlobalMiddlewareServerRouteLoop(handler, 2), - ).run(globalMiddlewareBenchOptions) -}) diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route.bench.ts b/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route.bench.ts deleted file mode 100644 index 558ebeb9a4..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { test } from 'vitest' -import { - assertGlobalMiddlewareScenario, - globalMiddlewareBenchOptions, - runGlobalMiddlewareServerRouteLoop, - setupGlobalMiddlewareBench, -} from '../bench' -import type { StartRequestHandler } from '../bench' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} -const context = await setupGlobalMiddlewareBench(handler) - -await assertGlobalMiddlewareScenario(handler, context) - -test('ssr', async ({ bench }) => { - await bench('ssr global-mw server-route 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 deleted file mode 100644 index 667baf9f54..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/src/fns.ts +++ /dev/null @@ -1,34 +0,0 @@ -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 deleted file mode 100644 index 65f7fa5848..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,123 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 038ec0ab5e..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index e59de72236..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/src/routes/__root.tsx +++ /dev/null @@ -1,24 +0,0 @@ -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 deleted file mode 100644 index 7166ea3030..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/src/routes/api.fn-urls.ts +++ /dev/null @@ -1,10 +0,0 @@ -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 deleted file mode 100644 index b92bcea5b0..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/src/routes/api.ping.$id.ts +++ /dev/null @@ -1,22 +0,0 @@ -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 deleted file mode 100644 index c293004539..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/src/routes/index.tsx +++ /dev/null @@ -1,10 +0,0 @@ -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 deleted file mode 100644 index a5781b1a6a..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/src/routes/page.$id.tsx +++ /dev/null @@ -1,22 +0,0 @@ -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 deleted file mode 100644 index a6f6214b82..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/src/start.ts +++ /dev/null @@ -1,88 +0,0 @@ -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 deleted file mode 100644 index dce3ceae30..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/tsconfig.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "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 deleted file mode 100644 index f3597b25d5..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -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 deleted file mode 100644 index 6dbc003aae..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 deleted file mode 100644 index 9660f29d07..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/speed.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -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 deleted file mode 100644 index 297e8cee7b..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-fn.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -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 deleted file mode 100644 index d023dd458a..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-0-middleware.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { test } from 'vitest' -import { - assertGlobalMiddlewareScenario, - globalMiddlewareBenchOptions, - runGlobalMiddlewareServerRouteLoop, - setupGlobalMiddlewareBench, -} from '../bench' -import type { StartRequestHandler } from '../bench' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} -const context = await setupGlobalMiddlewareBench(handler) - -await assertGlobalMiddlewareScenario(handler, context) - -test('ssr', async ({ bench }) => { - await bench('ssr global-mw server-route 0 middleware (vue)', async () => - runGlobalMiddlewareServerRouteLoop(handler, 0), - ).run(globalMiddlewareBenchOptions) -}) diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-1-middleware.bench.ts b/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-1-middleware.bench.ts deleted file mode 100644 index 5018163631..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-1-middleware.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { test } from 'vitest' -import { - assertGlobalMiddlewareScenario, - globalMiddlewareBenchOptions, - runGlobalMiddlewareServerRouteLoop, - setupGlobalMiddlewareBench, -} from '../bench' -import type { StartRequestHandler } from '../bench' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} -const context = await setupGlobalMiddlewareBench(handler) - -await assertGlobalMiddlewareScenario(handler, context) - -test('ssr', async ({ bench }) => { - await bench('ssr global-mw server-route 1 middleware (vue)', async () => - runGlobalMiddlewareServerRouteLoop(handler, 1), - ).run(globalMiddlewareBenchOptions) -}) diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-2-middleware.bench.ts b/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-2-middleware.bench.ts deleted file mode 100644 index f9abd8eb60..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-2-middleware.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { test } from 'vitest' -import { - assertGlobalMiddlewareScenario, - globalMiddlewareBenchOptions, - runGlobalMiddlewareServerRouteLoop, - setupGlobalMiddlewareBench, -} from '../bench' -import type { StartRequestHandler } from '../bench' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} -const context = await setupGlobalMiddlewareBench(handler) - -await assertGlobalMiddlewareScenario(handler, context) - -test('ssr', async ({ bench }) => { - await bench('ssr global-mw server-route 2 middlewares (vue)', async () => - runGlobalMiddlewareServerRouteLoop(handler, 2), - ).run(globalMiddlewareBenchOptions) -}) diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route.bench.ts b/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route.bench.ts deleted file mode 100644 index adcec3019f..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { test } from 'vitest' -import { - assertGlobalMiddlewareScenario, - globalMiddlewareBenchOptions, - runGlobalMiddlewareServerRouteLoop, - setupGlobalMiddlewareBench, -} from '../bench' -import type { StartRequestHandler } from '../bench' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} -const context = await setupGlobalMiddlewareBench(handler) - -await assertGlobalMiddlewareScenario(handler, context) - -test('ssr', async ({ bench }) => { - await bench('ssr global-mw server-route 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 deleted file mode 100644 index 557f6ee849..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/src/fns.ts +++ /dev/null @@ -1,34 +0,0 @@ -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 deleted file mode 100644 index 3118848e4d..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,123 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 4290e7cdd3..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 49422aac38..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/src/routes/__root.tsx +++ /dev/null @@ -1,26 +0,0 @@ -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 deleted file mode 100644 index af51ea6aa3..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/src/routes/api.fn-urls.ts +++ /dev/null @@ -1,10 +0,0 @@ -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 deleted file mode 100644 index f599ce1e49..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/src/routes/api.ping.$id.ts +++ /dev/null @@ -1,22 +0,0 @@ -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 deleted file mode 100644 index 85d3de69a4..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/src/routes/index.tsx +++ /dev/null @@ -1,10 +0,0 @@ -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 deleted file mode 100644 index 6e837ef0a0..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/src/routes/page.$id.tsx +++ /dev/null @@ -1,25 +0,0 @@ -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 deleted file mode 100644 index 6e4eb2c5ef..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/src/start.ts +++ /dev/null @@ -1,88 +0,0 @@ -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 deleted file mode 100644 index 56800fd29e..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/tsconfig.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "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 deleted file mode 100644 index 8e29c5ee98..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -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 deleted file mode 100644 index 093046fe39..0000000000 --- a/benchmarks/ssr/scenarios/head/react/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 deleted file mode 100644 index f75008506e..0000000000 --- a/benchmarks/ssr/scenarios/head/react/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index 3786e2137d..0000000000 --- a/benchmarks/ssr/scenarios/head/react/src/routeTree.gen.ts +++ /dev/null @@ -1,120 +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 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 deleted file mode 100644 index 7c4eb0babe..0000000000 --- a/benchmarks/ssr/scenarios/head/react/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 93f68352ab..0000000000 --- a/benchmarks/ssr/scenarios/head/react/src/routes/__root.tsx +++ /dev/null @@ -1,35 +0,0 @@ -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 deleted file mode 100644 index ee39349452..0000000000 --- a/benchmarks/ssr/scenarios/head/react/src/routes/h.$a.$b.$c.tsx +++ /dev/null @@ -1,26 +0,0 @@ -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 deleted file mode 100644 index b0658c87eb..0000000000 --- a/benchmarks/ssr/scenarios/head/react/src/routes/h.$a.$b.tsx +++ /dev/null @@ -1,31 +0,0 @@ -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 deleted file mode 100644 index acd5f3c3ce..0000000000 --- a/benchmarks/ssr/scenarios/head/react/src/routes/h.$a.tsx +++ /dev/null @@ -1,31 +0,0 @@ -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 deleted file mode 100644 index 91027bfc88..0000000000 --- a/benchmarks/ssr/scenarios/head/react/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "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 deleted file mode 100644 index d24fc850a1..0000000000 --- a/benchmarks/ssr/scenarios/head/react/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -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 deleted file mode 100644 index 033ca47c22..0000000000 --- a/benchmarks/ssr/scenarios/head/shared.ts +++ /dev/null @@ -1,55 +0,0 @@ -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 deleted file mode 100644 index c6df39998b..0000000000 --- a/benchmarks/ssr/scenarios/head/solid/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 deleted file mode 100644 index 333e2f091b..0000000000 --- a/benchmarks/ssr/scenarios/head/solid/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index ceba45e94d..0000000000 --- a/benchmarks/ssr/scenarios/head/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,120 +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 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 deleted file mode 100644 index 038ec0ab5e..0000000000 --- a/benchmarks/ssr/scenarios/head/solid/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 2dde9d0ddf..0000000000 --- a/benchmarks/ssr/scenarios/head/solid/src/routes/__root.tsx +++ /dev/null @@ -1,35 +0,0 @@ -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 deleted file mode 100644 index 7ec132e9a6..0000000000 --- a/benchmarks/ssr/scenarios/head/solid/src/routes/h.$a.$b.$c.tsx +++ /dev/null @@ -1,26 +0,0 @@ -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 deleted file mode 100644 index 25d443ad4e..0000000000 --- a/benchmarks/ssr/scenarios/head/solid/src/routes/h.$a.$b.tsx +++ /dev/null @@ -1,31 +0,0 @@ -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 deleted file mode 100644 index 6c994ffed6..0000000000 --- a/benchmarks/ssr/scenarios/head/solid/src/routes/h.$a.tsx +++ /dev/null @@ -1,31 +0,0 @@ -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 deleted file mode 100644 index b1806caa67..0000000000 --- a/benchmarks/ssr/scenarios/head/solid/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "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 deleted file mode 100644 index 7a870bbd77..0000000000 --- a/benchmarks/ssr/scenarios/head/solid/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -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 deleted file mode 100644 index 62b17b1216..0000000000 --- a/benchmarks/ssr/scenarios/head/vue/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 deleted file mode 100644 index 936735a909..0000000000 --- a/benchmarks/ssr/scenarios/head/vue/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index 9ec1029664..0000000000 --- a/benchmarks/ssr/scenarios/head/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,120 +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 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 deleted file mode 100644 index 4290e7cdd3..0000000000 --- a/benchmarks/ssr/scenarios/head/vue/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 9b95d2c48e..0000000000 --- a/benchmarks/ssr/scenarios/head/vue/src/routes/__root.tsx +++ /dev/null @@ -1,37 +0,0 @@ -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 deleted file mode 100644 index 91b8f03f7d..0000000000 --- a/benchmarks/ssr/scenarios/head/vue/src/routes/h.$a.$b.$c.tsx +++ /dev/null @@ -1,26 +0,0 @@ -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 deleted file mode 100644 index e92a619435..0000000000 --- a/benchmarks/ssr/scenarios/head/vue/src/routes/h.$a.$b.tsx +++ /dev/null @@ -1,31 +0,0 @@ -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 deleted file mode 100644 index ddf407e9ae..0000000000 --- a/benchmarks/ssr/scenarios/head/vue/src/routes/h.$a.tsx +++ /dev/null @@ -1,31 +0,0 @@ -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 deleted file mode 100644 index 4fe3ccecb1..0000000000 --- a/benchmarks/ssr/scenarios/head/vue/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "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 deleted file mode 100644 index 1434d26069..0000000000 --- a/benchmarks/ssr/scenarios/head/vue/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -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 deleted file mode 100644 index 0455f80c87..0000000000 --- a/benchmarks/ssr/scenarios/loaders/react/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 deleted file mode 100644 index 7acd43c635..0000000000 --- a/benchmarks/ssr/scenarios/loaders/react/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 068b5a5433..0000000000 --- a/benchmarks/ssr/scenarios/loaders/react/src/routeTree.gen.ts +++ /dev/null @@ -1,120 +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 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 deleted file mode 100644 index 7c4eb0babe..0000000000 --- a/benchmarks/ssr/scenarios/loaders/react/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 746a26aeb6..0000000000 --- a/benchmarks/ssr/scenarios/loaders/react/src/routes/$a.$b.$c.tsx +++ /dev/null @@ -1,32 +0,0 @@ -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 deleted file mode 100644 index 79c10c06b0..0000000000 --- a/benchmarks/ssr/scenarios/loaders/react/src/routes/$a.$b.tsx +++ /dev/null @@ -1,33 +0,0 @@ -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 deleted file mode 100644 index 980a495c32..0000000000 --- a/benchmarks/ssr/scenarios/loaders/react/src/routes/$a.tsx +++ /dev/null @@ -1,33 +0,0 @@ -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 deleted file mode 100644 index 001639cb39..0000000000 --- a/benchmarks/ssr/scenarios/loaders/react/src/routes/__root.tsx +++ /dev/null @@ -1,28 +0,0 @@ -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 deleted file mode 100644 index 8800818162..0000000000 --- a/benchmarks/ssr/scenarios/loaders/react/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "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 deleted file mode 100644 index e761426c84..0000000000 --- a/benchmarks/ssr/scenarios/loaders/react/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -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 deleted file mode 100644 index f52c51dccd..0000000000 --- a/benchmarks/ssr/scenarios/loaders/shared-bench.ts +++ /dev/null @@ -1,75 +0,0 @@ -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 deleted file mode 100644 index d907f7d66c..0000000000 --- a/benchmarks/ssr/scenarios/loaders/shared-data.ts +++ /dev/null @@ -1,54 +0,0 @@ -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 deleted file mode 100644 index 2cb0e92acd..0000000000 --- a/benchmarks/ssr/scenarios/loaders/solid/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 deleted file mode 100644 index 7fc8d88389..0000000000 --- a/benchmarks/ssr/scenarios/loaders/solid/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 7b299cfcd1..0000000000 --- a/benchmarks/ssr/scenarios/loaders/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,120 +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 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 deleted file mode 100644 index 038ec0ab5e..0000000000 --- a/benchmarks/ssr/scenarios/loaders/solid/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 9ead32440a..0000000000 --- a/benchmarks/ssr/scenarios/loaders/solid/src/routes/$a.$b.$c.tsx +++ /dev/null @@ -1,34 +0,0 @@ -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 deleted file mode 100644 index c0abf3da87..0000000000 --- a/benchmarks/ssr/scenarios/loaders/solid/src/routes/$a.$b.tsx +++ /dev/null @@ -1,35 +0,0 @@ -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 deleted file mode 100644 index d4608523b8..0000000000 --- a/benchmarks/ssr/scenarios/loaders/solid/src/routes/$a.tsx +++ /dev/null @@ -1,35 +0,0 @@ -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 deleted file mode 100644 index 2f4b1de410..0000000000 --- a/benchmarks/ssr/scenarios/loaders/solid/src/routes/__root.tsx +++ /dev/null @@ -1,28 +0,0 @@ -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 deleted file mode 100644 index 47f264ba4f..0000000000 --- a/benchmarks/ssr/scenarios/loaders/solid/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "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 deleted file mode 100644 index 64f52159c3..0000000000 --- a/benchmarks/ssr/scenarios/loaders/solid/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -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 deleted file mode 100644 index 2a98cb57f9..0000000000 --- a/benchmarks/ssr/scenarios/loaders/vue/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 deleted file mode 100644 index 321350d98c..0000000000 --- a/benchmarks/ssr/scenarios/loaders/vue/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 24ee6c3b9d..0000000000 --- a/benchmarks/ssr/scenarios/loaders/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,120 +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 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 deleted file mode 100644 index 4290e7cdd3..0000000000 --- a/benchmarks/ssr/scenarios/loaders/vue/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 0a52b9c542..0000000000 --- a/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.$b.$c.tsx +++ /dev/null @@ -1,35 +0,0 @@ -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 deleted file mode 100644 index f3943d58e7..0000000000 --- a/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.$b.tsx +++ /dev/null @@ -1,36 +0,0 @@ -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 deleted file mode 100644 index 63bb36949f..0000000000 --- a/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.tsx +++ /dev/null @@ -1,36 +0,0 @@ -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 deleted file mode 100644 index 0479fb1af4..0000000000 --- a/benchmarks/ssr/scenarios/loaders/vue/src/routes/__root.tsx +++ /dev/null @@ -1,30 +0,0 @@ -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 deleted file mode 100644 index c302f63770..0000000000 --- a/benchmarks/ssr/scenarios/loaders/vue/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "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 deleted file mode 100644 index 92bf3e60f0..0000000000 --- a/benchmarks/ssr/scenarios/loaders/vue/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -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 deleted file mode 100644 index 84d4846ec5..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/react/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 deleted file mode 100644 index 920186c5db..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/react/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index f5d09089a6..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/react/speed.rewrite-passthrough.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index e893d06a57..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/react/src/routeTree.gen.ts +++ /dev/null @@ -1,94 +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 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 deleted file mode 100644 index e9e0b2ce9a..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/react/src/router.tsx +++ /dev/null @@ -1,42 +0,0 @@ -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 deleted file mode 100644 index 7cdcfe1a37..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/react/src/routes/__root.tsx +++ /dev/null @@ -1,27 +0,0 @@ -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 deleted file mode 100644 index 756109b844..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/react/src/routes/p.$a.$b.tsx +++ /dev/null @@ -1,39 +0,0 @@ -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 deleted file mode 100644 index 7b0a778a18..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/react/src/routes/p.$a.tsx +++ /dev/null @@ -1,27 +0,0 @@ -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 deleted file mode 100644 index cf14e1d440..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/react/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "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 deleted file mode 100644 index 7b20340ec6..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/react/vite.config.ts +++ /dev/null @@ -1,35 +0,0 @@ -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 deleted file mode 100644 index 9b29bc0249..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/shared.ts +++ /dev/null @@ -1,91 +0,0 @@ -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 deleted file mode 100644 index 7c993a1404..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/solid/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 deleted file mode 100644 index 488fb2ca52..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/solid/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 7b86e2ba11..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/solid/speed.rewrite-passthrough.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index b3b6b24a38..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,94 +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 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 deleted file mode 100644 index 9806e59d0e..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/solid/src/router.tsx +++ /dev/null @@ -1,42 +0,0 @@ -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 deleted file mode 100644 index 1a9cd6c423..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/solid/src/routes/__root.tsx +++ /dev/null @@ -1,27 +0,0 @@ -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 deleted file mode 100644 index eacb45a841..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/solid/src/routes/p.$a.$b.tsx +++ /dev/null @@ -1,39 +0,0 @@ -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 deleted file mode 100644 index 1845e3ebba..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/solid/src/routes/p.$a.tsx +++ /dev/null @@ -1,27 +0,0 @@ -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 deleted file mode 100644 index 42c3a2160f..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/solid/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "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 deleted file mode 100644 index 963fe7132b..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/solid/vite.config.ts +++ /dev/null @@ -1,40 +0,0 @@ -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 deleted file mode 100644 index 10fd6f4f34..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/vue/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 deleted file mode 100644 index 5fd4da9d3e..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/vue/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index f3664b5f21..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/vue/speed.rewrite-passthrough.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 4440c1cfda..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,94 +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 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 deleted file mode 100644 index 3a7389a5be..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/vue/src/router.tsx +++ /dev/null @@ -1,42 +0,0 @@ -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 deleted file mode 100644 index ed4cf1300d..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/vue/src/routes/__root.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index 3c9de1806e..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/vue/src/routes/p.$a.$b.tsx +++ /dev/null @@ -1,46 +0,0 @@ -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 deleted file mode 100644 index 9702ebedd7..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/vue/src/routes/p.$a.tsx +++ /dev/null @@ -1,30 +0,0 @@ -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 deleted file mode 100644 index 08c94853f4..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/vue/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "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 deleted file mode 100644 index 22399ec6b2..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/vue/vite.config.ts +++ /dev/null @@ -1,35 +0,0 @@ -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 deleted file mode 100644 index 77858e2246..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/react/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 deleted file mode 100644 index ba6bd4a61d..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/react/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 95395c294e..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/react/src/routeTree.gen.ts +++ /dev/null @@ -1,120 +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 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 deleted file mode 100644 index 7c4eb0babe..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/react/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 1973ca20bb..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/react/src/routes/__root.tsx +++ /dev/null @@ -1,25 +0,0 @@ -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 deleted file mode 100644 index e3df06149d..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/react/src/routes/mix.$a.$b.$c.tsx +++ /dev/null @@ -1,25 +0,0 @@ -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 deleted file mode 100644 index 3fe26dd70e..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/react/src/routes/mix.$a.$b.tsx +++ /dev/null @@ -1,26 +0,0 @@ -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 deleted file mode 100644 index a06c9ad1b9..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/react/src/routes/mix.$a.tsx +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 399fe944f9..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/react/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "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 deleted file mode 100644 index 70c67cff81..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/react/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -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 deleted file mode 100644 index 5b2530ccab..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/shared-bench.ts +++ /dev/null @@ -1,95 +0,0 @@ -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 deleted file mode 100644 index 358cc97323..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/solid/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 deleted file mode 100644 index 76265397ab..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/solid/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 22560063f6..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,120 +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 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 deleted file mode 100644 index 038ec0ab5e..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/solid/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 15de858e78..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/solid/src/routes/__root.tsx +++ /dev/null @@ -1,25 +0,0 @@ -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 deleted file mode 100644 index f6a85bfdc2..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/solid/src/routes/mix.$a.$b.$c.tsx +++ /dev/null @@ -1,25 +0,0 @@ -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 deleted file mode 100644 index f735b1395f..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/solid/src/routes/mix.$a.$b.tsx +++ /dev/null @@ -1,26 +0,0 @@ -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 deleted file mode 100644 index c8c80a7a6d..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/solid/src/routes/mix.$a.tsx +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index f386c3f996..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/solid/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "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 deleted file mode 100644 index 2c0042c1ed..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/solid/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -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 deleted file mode 100644 index 9ff4d99323..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/vue/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 deleted file mode 100644 index ff60341b27..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/vue/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index b77209b48b..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,120 +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 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 deleted file mode 100644 index 4290e7cdd3..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/vue/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 4b03519823..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/__root.tsx +++ /dev/null @@ -1,27 +0,0 @@ -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 deleted file mode 100644 index 8ae7d468f1..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/mix.$a.$b.$c.tsx +++ /dev/null @@ -1,28 +0,0 @@ -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 deleted file mode 100644 index c10751489e..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/mix.$a.$b.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index c96165c6d6..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/mix.$a.tsx +++ /dev/null @@ -1,26 +0,0 @@ -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 deleted file mode 100644 index 3f2809bd5a..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/vue/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "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 deleted file mode 100644 index 09bb36cb0b..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/vue/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -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 deleted file mode 100644 index 652f87cb44..0000000000 --- a/benchmarks/ssr/scenarios/serialization/react/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 deleted file mode 100644 index 8be07d2643..0000000000 --- a/benchmarks/ssr/scenarios/serialization/react/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index c70fddc6c4..0000000000 --- a/benchmarks/ssr/scenarios/serialization/react/speed.dehydrate-plain-control.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 49bdbd036b..0000000000 --- a/benchmarks/ssr/scenarios/serialization/react/src/routeTree.gen.ts +++ /dev/null @@ -1,87 +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 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 deleted file mode 100644 index 7c4eb0babe..0000000000 --- a/benchmarks/ssr/scenarios/serialization/react/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index ff1da4c304..0000000000 --- a/benchmarks/ssr/scenarios/serialization/react/src/routes/__root.tsx +++ /dev/null @@ -1,24 +0,0 @@ -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 deleted file mode 100644 index 88a8a0e11f..0000000000 --- a/benchmarks/ssr/scenarios/serialization/react/src/routes/plain.$id.tsx +++ /dev/null @@ -1,26 +0,0 @@ -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 deleted file mode 100644 index a9bb264c48..0000000000 --- a/benchmarks/ssr/scenarios/serialization/react/src/routes/rich.$id.tsx +++ /dev/null @@ -1,26 +0,0 @@ -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 deleted file mode 100644 index 0a73c69be1..0000000000 --- a/benchmarks/ssr/scenarios/serialization/react/src/serialization.ts +++ /dev/null @@ -1,10 +0,0 @@ -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 deleted file mode 100644 index ea4513df4d..0000000000 --- a/benchmarks/ssr/scenarios/serialization/react/src/start.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 59499356d6..0000000000 --- a/benchmarks/ssr/scenarios/serialization/react/tsconfig.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "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 deleted file mode 100644 index 64568ccb7e..0000000000 --- a/benchmarks/ssr/scenarios/serialization/react/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -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 deleted file mode 100644 index 25ed478f03..0000000000 --- a/benchmarks/ssr/scenarios/serialization/shared-bench.ts +++ /dev/null @@ -1,107 +0,0 @@ -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 deleted file mode 100644 index dc1dc90b1f..0000000000 --- a/benchmarks/ssr/scenarios/serialization/shared-data.ts +++ /dev/null @@ -1,101 +0,0 @@ -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 deleted file mode 100644 index 80a4b146ac..0000000000 --- a/benchmarks/ssr/scenarios/serialization/solid/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 deleted file mode 100644 index 70bda8c7af..0000000000 --- a/benchmarks/ssr/scenarios/serialization/solid/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index d7ccb16f6f..0000000000 --- a/benchmarks/ssr/scenarios/serialization/solid/speed.dehydrate-plain-control.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index b9e25f918e..0000000000 --- a/benchmarks/ssr/scenarios/serialization/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,87 +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 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 deleted file mode 100644 index 038ec0ab5e..0000000000 --- a/benchmarks/ssr/scenarios/serialization/solid/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index e59de72236..0000000000 --- a/benchmarks/ssr/scenarios/serialization/solid/src/routes/__root.tsx +++ /dev/null @@ -1,24 +0,0 @@ -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 deleted file mode 100644 index c16f73dc3f..0000000000 --- a/benchmarks/ssr/scenarios/serialization/solid/src/routes/plain.$id.tsx +++ /dev/null @@ -1,26 +0,0 @@ -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 deleted file mode 100644 index e08b1e4834..0000000000 --- a/benchmarks/ssr/scenarios/serialization/solid/src/routes/rich.$id.tsx +++ /dev/null @@ -1,26 +0,0 @@ -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 deleted file mode 100644 index ae84f12c9f..0000000000 --- a/benchmarks/ssr/scenarios/serialization/solid/src/serialization.ts +++ /dev/null @@ -1,10 +0,0 @@ -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 deleted file mode 100644 index a539f2b168..0000000000 --- a/benchmarks/ssr/scenarios/serialization/solid/src/start.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 3ea91b977f..0000000000 --- a/benchmarks/ssr/scenarios/serialization/solid/tsconfig.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "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 deleted file mode 100644 index db81e2ab74..0000000000 --- a/benchmarks/ssr/scenarios/serialization/solid/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -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 deleted file mode 100644 index 728b5c15cc..0000000000 --- a/benchmarks/ssr/scenarios/serialization/vue/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 deleted file mode 100644 index 7f733dd601..0000000000 --- a/benchmarks/ssr/scenarios/serialization/vue/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 8efdeb6c79..0000000000 --- a/benchmarks/ssr/scenarios/serialization/vue/speed.dehydrate-plain-control.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index cd7b0b449b..0000000000 --- a/benchmarks/ssr/scenarios/serialization/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,87 +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 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 deleted file mode 100644 index 4290e7cdd3..0000000000 --- a/benchmarks/ssr/scenarios/serialization/vue/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 49422aac38..0000000000 --- a/benchmarks/ssr/scenarios/serialization/vue/src/routes/__root.tsx +++ /dev/null @@ -1,26 +0,0 @@ -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 deleted file mode 100644 index 47fdeb971f..0000000000 --- a/benchmarks/ssr/scenarios/serialization/vue/src/routes/plain.$id.tsx +++ /dev/null @@ -1,27 +0,0 @@ -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 deleted file mode 100644 index 1ee86cefd3..0000000000 --- a/benchmarks/ssr/scenarios/serialization/vue/src/routes/rich.$id.tsx +++ /dev/null @@ -1,27 +0,0 @@ -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 deleted file mode 100644 index f8b2d8cb43..0000000000 --- a/benchmarks/ssr/scenarios/serialization/vue/src/serialization.ts +++ /dev/null @@ -1,10 +0,0 @@ -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 deleted file mode 100644 index ee27feb084..0000000000 --- a/benchmarks/ssr/scenarios/serialization/vue/src/start.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 5d8c7b5b62..0000000000 --- a/benchmarks/ssr/scenarios/serialization/vue/tsconfig.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "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 deleted file mode 100644 index b89537fa18..0000000000 --- a/benchmarks/ssr/scenarios/serialization/vue/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -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 deleted file mode 100644 index 4274c724ca..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/bench.ts +++ /dev/null @@ -1,556 +0,0 @@ -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 deleted file mode 100644 index a3012549ca..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/react/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 deleted file mode 100644 index fa80cdb690..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/react/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index fd535ee313..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/react/speed.server-fn-raw-response.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 8fbce405dd..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/react/speed.server-fn-raw-stream.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 79ecb50e87..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/react/src/fns.ts +++ /dev/null @@ -1,101 +0,0 @@ -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 deleted file mode 100644 index 10e933da3d..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/react/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 7c4eb0babe..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/react/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index ff1da4c304..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/react/src/routes/__root.tsx +++ /dev/null @@ -1,24 +0,0 @@ -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 deleted file mode 100644 index 02260e5098..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/react/src/routes/api.fn-urls.ts +++ /dev/null @@ -1,15 +0,0 @@ -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 deleted file mode 100644 index baa0026378..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/react/src/routes/index.tsx +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index 4f3cc314af..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/react/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "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 deleted file mode 100644 index c37fde0c4b..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/react/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -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 deleted file mode 100644 index 16fc151b11..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/solid/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 deleted file mode 100644 index adac07cb22..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 843a4c97ce..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.server-fn-raw-response.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index aa24d55e79..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.server-fn-raw-stream.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 3c586fa2ee..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/solid/src/fns.ts +++ /dev/null @@ -1,101 +0,0 @@ -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 deleted file mode 100644 index 298ac3168d..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 038ec0ab5e..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/solid/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index e59de72236..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/solid/src/routes/__root.tsx +++ /dev/null @@ -1,24 +0,0 @@ -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 deleted file mode 100644 index 353a732637..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/solid/src/routes/api.fn-urls.ts +++ /dev/null @@ -1,15 +0,0 @@ -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 deleted file mode 100644 index 6e0e5d8d6b..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/solid/src/routes/index.tsx +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index 0af78df33d..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/solid/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "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 deleted file mode 100644 index a8af4a6b50..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/solid/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -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 deleted file mode 100644 index abdd85c6b7..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/vue/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 deleted file mode 100644 index 24305cf1bc..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 2eeb9a4f6b..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.server-fn-raw-response.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index a73905004d..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.server-fn-raw-stream.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index f7e1a1217a..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/vue/src/fns.ts +++ /dev/null @@ -1,101 +0,0 @@ -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 deleted file mode 100644 index b226f0a25a..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 4290e7cdd3..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/vue/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 49422aac38..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/vue/src/routes/__root.tsx +++ /dev/null @@ -1,26 +0,0 @@ -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 deleted file mode 100644 index 2db00972bb..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/vue/src/routes/api.fn-urls.ts +++ /dev/null @@ -1,15 +0,0 @@ -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 deleted file mode 100644 index d53731eb23..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/vue/src/routes/index.tsx +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index 5b7742b414..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/vue/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "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 deleted file mode 100644 index 0f3e2ce84d..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/vue/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -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 deleted file mode 100644 index 1461ce2bfd..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/bench.ts +++ /dev/null @@ -1,533 +0,0 @@ -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 deleted file mode 100644 index 8858309f35..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/react/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 deleted file mode 100644 index c876772ad1..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/react/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 6a0cb55f78..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-during-document-ssr.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 96f1160078..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-not-found.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index e85d5debd3..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-post.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 5dae598549..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-redirect.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 40d6961206..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-send-context.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index ce2ba48c5b..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/react/src/fns.ts +++ /dev/null @@ -1,87 +0,0 @@ -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 deleted file mode 100644 index 4daa5f03b0..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/react/src/routeTree.gen.ts +++ /dev/null @@ -1,104 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 7c4eb0babe..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/react/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index ff1da4c304..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/react/src/routes/__root.tsx +++ /dev/null @@ -1,24 +0,0 @@ -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 deleted file mode 100644 index ed3d9a9b7b..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/react/src/routes/api.fn-urls.ts +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index 45636ef30e..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/react/src/routes/index.tsx +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 0f8a39f69d..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/react/src/routes/ssr-call.$id.tsx +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index cf14e1d440..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/react/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "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 deleted file mode 100644 index cd56edda95..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/react/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -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 deleted file mode 100644 index f1e9581897..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/solid/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 deleted file mode 100644 index f6bbdc9e73..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/solid/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 933f61b59c..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-during-document-ssr.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 513b69f4ba..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-not-found.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index e2ce8ad9ee..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-post.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 14353f1290..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-redirect.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 76d3a554bd..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-send-context.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index e9a81ad06e..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/solid/src/fns.ts +++ /dev/null @@ -1,87 +0,0 @@ -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 deleted file mode 100644 index 3d0bd34eaa..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,104 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 038ec0ab5e..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/solid/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index e59de72236..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/solid/src/routes/__root.tsx +++ /dev/null @@ -1,24 +0,0 @@ -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 deleted file mode 100644 index 7e18f6a03b..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/solid/src/routes/api.fn-urls.ts +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index 83e7b22372..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/solid/src/routes/index.tsx +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index abc5571a59..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/solid/src/routes/ssr-call.$id.tsx +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 42c3a2160f..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/solid/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "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 deleted file mode 100644 index 2f2f78b75c..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/solid/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -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 deleted file mode 100644 index ad6f053838..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/vue/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 deleted file mode 100644 index 3f67c1a500..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/vue/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 56c9addca5..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-during-document-ssr.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index e9a6e31617..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-not-found.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index df9312ccd1..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-post.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 67c4611644..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-redirect.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 6f51ef4bab..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-send-context.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index fc08b2b9bf..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/vue/src/fns.ts +++ /dev/null @@ -1,87 +0,0 @@ -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 deleted file mode 100644 index 0e24cd9c15..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,104 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 4290e7cdd3..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/vue/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 49422aac38..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/vue/src/routes/__root.tsx +++ /dev/null @@ -1,26 +0,0 @@ -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 deleted file mode 100644 index 0199e7f1d3..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/vue/src/routes/api.fn-urls.ts +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index e72e667bc5..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/vue/src/routes/index.tsx +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 45fad23dc0..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/vue/src/routes/ssr-call.$id.tsx +++ /dev/null @@ -1,28 +0,0 @@ -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 deleted file mode 100644 index 08c94853f4..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/vue/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "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 deleted file mode 100644 index 5f3e3ca4b5..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/vue/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -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 deleted file mode 100644 index e5f11d0a57..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/react/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 deleted file mode 100644 index 6331216522..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/react/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 1e8c428696..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/react/src/middleware.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 7a63a799a1..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/react/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 7c4eb0babe..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/react/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index ff1da4c304..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/react/src/routes/__root.tsx +++ /dev/null @@ -1,24 +0,0 @@ -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 deleted file mode 100644 index 5a9f5d5035..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/react/src/routes/api.chain.$id.ts +++ /dev/null @@ -1,24 +0,0 @@ -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 deleted file mode 100644 index 9fe98b6851..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/react/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 91027bfc88..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/react/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "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 deleted file mode 100644 index f6998c2ac8..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/react/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -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 deleted file mode 100644 index 663ca09294..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/shared.ts +++ /dev/null @@ -1,58 +0,0 @@ -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 deleted file mode 100644 index 0bde91f794..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/solid/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 deleted file mode 100644 index 77d58e7b19..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/solid/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index fcaf3d08f7..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/solid/src/middleware.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index b8c91b9134..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 038ec0ab5e..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/solid/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index e59de72236..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/solid/src/routes/__root.tsx +++ /dev/null @@ -1,24 +0,0 @@ -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 deleted file mode 100644 index fabdb9de85..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/solid/src/routes/api.chain.$id.ts +++ /dev/null @@ -1,24 +0,0 @@ -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 deleted file mode 100644 index e2357b558d..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/solid/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index b1806caa67..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/solid/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "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 deleted file mode 100644 index 800cf9db9f..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/solid/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -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 deleted file mode 100644 index 2a21b81bf9..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/vue/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 deleted file mode 100644 index 3d03b9c1fa..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/vue/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 05e7a86be9..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/vue/src/middleware.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index db4f072a69..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 4290e7cdd3..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/vue/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 49422aac38..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/vue/src/routes/__root.tsx +++ /dev/null @@ -1,26 +0,0 @@ -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 deleted file mode 100644 index d643a339c5..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/vue/src/routes/api.chain.$id.ts +++ /dev/null @@ -1,24 +0,0 @@ -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 deleted file mode 100644 index 60e9d08e6d..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/vue/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 4fe3ccecb1..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/vue/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "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 deleted file mode 100644 index 909b7cca50..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/vue/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -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 deleted file mode 100644 index a16cb3e537..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/react/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 deleted file mode 100644 index 631314148a..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/react/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 6615cc0611..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/react/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 7c4eb0babe..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/react/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index ff1da4c304..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/react/src/routes/__root.tsx +++ /dev/null @@ -1,24 +0,0 @@ -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 deleted file mode 100644 index b43275a5c6..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/react/src/routes/api.users.$id.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index f5a19839f9..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/react/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 91027bfc88..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/react/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "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 deleted file mode 100644 index 2c723c749c..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/react/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -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 deleted file mode 100644 index ce33faaefe..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/shared.ts +++ /dev/null @@ -1,56 +0,0 @@ -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 deleted file mode 100644 index 9c4bf7e230..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/solid/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 deleted file mode 100644 index 4788d31854..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/solid/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 1d7fee0d2b..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 038ec0ab5e..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/solid/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index e59de72236..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/solid/src/routes/__root.tsx +++ /dev/null @@ -1,24 +0,0 @@ -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 deleted file mode 100644 index 516af1cc15..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/solid/src/routes/api.users.$id.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 87eb6a178f..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/solid/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index b1806caa67..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/solid/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "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 deleted file mode 100644 index 994e04f1d6..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/solid/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -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 deleted file mode 100644 index a92a9ad40e..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/vue/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 deleted file mode 100644 index 09c0bbe90b..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/vue/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index b12a446b9f..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 4290e7cdd3..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/vue/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 49422aac38..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/vue/src/routes/__root.tsx +++ /dev/null @@ -1,26 +0,0 @@ -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 deleted file mode 100644 index 7766b52acc..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/vue/src/routes/api.users.$id.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 39d1e2f935..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/vue/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 4fe3ccecb1..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/vue/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "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 deleted file mode 100644 index 0457453532..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/vue/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -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 deleted file mode 100644 index a905aa3474..0000000000 --- a/benchmarks/ssr/scenarios/streaming/react/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 deleted file mode 100644 index eb4c9dc1d6..0000000000 --- a/benchmarks/ssr/scenarios/streaming/react/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index eb1af78a41..0000000000 --- a/benchmarks/ssr/scenarios/streaming/react/src/routeTree.gen.ts +++ /dev/null @@ -1,68 +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 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 deleted file mode 100644 index 7c4eb0babe..0000000000 --- a/benchmarks/ssr/scenarios/streaming/react/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 1973ca20bb..0000000000 --- a/benchmarks/ssr/scenarios/streaming/react/src/routes/__root.tsx +++ /dev/null @@ -1,25 +0,0 @@ -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 deleted file mode 100644 index 342f7ceb0c..0000000000 --- a/benchmarks/ssr/scenarios/streaming/react/src/routes/stream.$id.tsx +++ /dev/null @@ -1,39 +0,0 @@ -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 deleted file mode 100644 index 8800818162..0000000000 --- a/benchmarks/ssr/scenarios/streaming/react/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "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 deleted file mode 100644 index e1cc5f534b..0000000000 --- a/benchmarks/ssr/scenarios/streaming/react/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -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 deleted file mode 100644 index cc45062e1b..0000000000 --- a/benchmarks/ssr/scenarios/streaming/shared-bench.ts +++ /dev/null @@ -1,78 +0,0 @@ -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 deleted file mode 100644 index 695ed107c6..0000000000 --- a/benchmarks/ssr/scenarios/streaming/shared-data.ts +++ /dev/null @@ -1,69 +0,0 @@ -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 deleted file mode 100644 index 15e5f21103..0000000000 --- a/benchmarks/ssr/scenarios/streaming/solid/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 deleted file mode 100644 index 19d5817d32..0000000000 --- a/benchmarks/ssr/scenarios/streaming/solid/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index e015aee737..0000000000 --- a/benchmarks/ssr/scenarios/streaming/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,68 +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 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 deleted file mode 100644 index 038ec0ab5e..0000000000 --- a/benchmarks/ssr/scenarios/streaming/solid/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 15de858e78..0000000000 --- a/benchmarks/ssr/scenarios/streaming/solid/src/routes/__root.tsx +++ /dev/null @@ -1,25 +0,0 @@ -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 deleted file mode 100644 index 1a65fff950..0000000000 --- a/benchmarks/ssr/scenarios/streaming/solid/src/routes/stream.$id.tsx +++ /dev/null @@ -1,39 +0,0 @@ -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 deleted file mode 100644 index 47f264ba4f..0000000000 --- a/benchmarks/ssr/scenarios/streaming/solid/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "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 deleted file mode 100644 index 353c21f552..0000000000 --- a/benchmarks/ssr/scenarios/streaming/solid/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -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 deleted file mode 100644 index acaa7c460c..0000000000 --- a/benchmarks/ssr/scenarios/streaming/vue/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 deleted file mode 100644 index 42473fc694..0000000000 --- a/benchmarks/ssr/scenarios/streaming/vue/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 2ec10975f2..0000000000 --- a/benchmarks/ssr/scenarios/streaming/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,68 +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 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 deleted file mode 100644 index 4290e7cdd3..0000000000 --- a/benchmarks/ssr/scenarios/streaming/vue/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 4b03519823..0000000000 --- a/benchmarks/ssr/scenarios/streaming/vue/src/routes/__root.tsx +++ /dev/null @@ -1,27 +0,0 @@ -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 deleted file mode 100644 index d627fa56c9..0000000000 --- a/benchmarks/ssr/scenarios/streaming/vue/src/routes/stream.$id.tsx +++ /dev/null @@ -1,56 +0,0 @@ -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 deleted file mode 100644 index c302f63770..0000000000 --- a/benchmarks/ssr/scenarios/streaming/vue/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "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 deleted file mode 100644 index a09a30076f..0000000000 --- a/benchmarks/ssr/scenarios/streaming/vue/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -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 deleted file mode 100644 index 0f19144d3b..0000000000 --- a/benchmarks/ssr/solid/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 index 2f72977612..05eb8e2ca1 100644 --- a/benchmarks/ssr/solid/speed.bench.ts +++ b/benchmarks/ssr/solid/speed.bench.ts @@ -1,22 +1,50 @@ -import { test } from 'vitest' +import { afterAll, beforeAll, bench, describe } 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 appModulePath = './dist/server/server.js' const benchmarkSeed = 0xcafebabe -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler +const uninitializedHandler: StartRequestHandler = { + fetch: () => Promise.reject(new Error('Benchmark not initialized')), } -test('ssr', async ({ bench }) => { - await bench('ssr request loop (solid)', async () => - runSsrRequestLoop(handler, { seed: benchmarkSeed }), - ).run({ - warmupIterations: 100, - time: 10_000, - throws: true, - }) +let handler = uninitializedHandler + +async function setup() { + const module = (await import(appModulePath)) as { + default: StartRequestHandler + } + + handler = module.default +} + +function teardown() { + handler = uninitializedHandler +} + +describe('ssr', () => { + /** + * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, + * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. + * + * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, + * but it does support `beforeAll` and `afterAll`. + * + * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. + */ + beforeAll(setup) + afterAll(teardown) + + bench( + 'ssr request loop (solid)', + () => runSsrRequestLoop(handler, { seed: benchmarkSeed }), + { + warmupIterations: 100, + time: 10_000, + setup, + teardown, + throws: true, + }, + ) }) diff --git a/benchmarks/ssr/solid/src/workload.tsx b/benchmarks/ssr/solid/src/workload.tsx index 76fcae555a..eb65591ad5 100644 --- a/benchmarks/ssr/solid/src/workload.tsx +++ b/benchmarks/ssr/solid/src/workload.tsx @@ -29,9 +29,10 @@ function ParamsProbe(props: { salt: number }) { ), }) - createEffect(() => { - void params() - }) + createEffect( + () => params(), + () => {}, + ) return null } @@ -43,9 +44,10 @@ function SearchProbe(props: { salt: number }) { runSelectorWork(String(nextSearch.q ?? ''), props.salt), }) - createEffect(() => { - void search() - }) + createEffect( + () => search(), + () => {}, + ) return null } @@ -73,9 +75,9 @@ function LinkProbe(props: { salt: number }) { export function RouteWorkload() { return ( <> - {(probe) => } - {(probe) => } - {(probe) => } + {(probe) => } + {(probe) => } + {(probe) => } ) } diff --git a/benchmarks/ssr/solid/vite.config.ts b/benchmarks/ssr/solid/vite.config.ts index dfd82d9192..dc9cbf90e3 100644 --- a/benchmarks/ssr/solid/vite.config.ts +++ b/benchmarks/ssr/solid/vite.config.ts @@ -3,7 +3,6 @@ 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)) @@ -23,8 +22,6 @@ export default defineConfig({ minify: false, }, test: { - execArgv: cpuSimulationExecArgv(), - isolate: true, name: '@benchmarks/ssr (solid)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/tsconfig.json b/benchmarks/ssr/tsconfig.json index 7279177023..e3ed3ad08a 100644 --- a/benchmarks/ssr/tsconfig.json +++ b/benchmarks/ssr/tsconfig.json @@ -3,10 +3,5 @@ "compilerOptions": { "types": ["node", "vite/client", "vitest/globals"] }, - "include": [ - "bench-utils.ts", - "bench-utils.test.ts", - "scenarios/streaming/shared-data.ts", - "vitest.unit.config.ts" - ] + "include": ["bench-utils.ts"] } diff --git a/benchmarks/ssr/vitest.config.ts b/benchmarks/ssr/vitest.config.ts index a91eae4967..14776452ed 100644 --- a/benchmarks/ssr/vitest.config.ts +++ b/benchmarks/ssr/vitest.config.ts @@ -7,7 +7,6 @@ export default defineConfig({ './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 deleted file mode 100644 index a397ad929e..0000000000 --- a/benchmarks/ssr/vitest.react.config.ts +++ /dev/null @@ -1,8 +0,0 @@ -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 deleted file mode 100644 index b8827b86aa..0000000000 --- a/benchmarks/ssr/vitest.solid.config.ts +++ /dev/null @@ -1,8 +0,0 @@ -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 deleted file mode 100644 index cbba6db9ef..0000000000 --- a/benchmarks/ssr/vitest.unit.config.ts +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 17960d7569..0000000000 --- a/benchmarks/ssr/vitest.vue.config.ts +++ /dev/null @@ -1,8 +0,0 @@ -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 deleted file mode 100644 index 930d6c2e22..0000000000 --- a/benchmarks/ssr/vue/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "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 index 57b59e0504..f996f900e8 100644 --- a/benchmarks/ssr/vue/speed.bench.ts +++ b/benchmarks/ssr/vue/speed.bench.ts @@ -1,22 +1,50 @@ -import { test } from 'vitest' +import { afterAll, beforeAll, bench, describe } 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 appModulePath = './dist/server/server.js' const benchmarkSeed = 0xdeadbeef -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler +const uninitializedHandler: StartRequestHandler = { + fetch: () => Promise.reject(new Error('Benchmark not initialized')), } -test('ssr', async ({ bench }) => { - await bench('ssr request loop (vue)', async () => - runSsrRequestLoop(handler, { seed: benchmarkSeed }), - ).run({ - warmupIterations: 100, - time: 10_000, - throws: true, - }) +let handler = uninitializedHandler + +async function setup() { + const module = (await import(appModulePath)) as { + default: StartRequestHandler + } + + handler = module.default +} + +function teardown() { + handler = uninitializedHandler +} + +describe('ssr', () => { + /** + * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, + * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. + * + * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, + * but it does support `beforeAll` and `afterAll`. + * + * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. + */ + beforeAll(setup) + afterAll(teardown) + + bench( + 'ssr request loop (vue)', + () => runSsrRequestLoop(handler, { seed: benchmarkSeed }), + { + warmupIterations: 100, + time: 10_000, + setup, + teardown, + throws: true, + }, + ) }) diff --git a/benchmarks/ssr/vue/vite.config.ts b/benchmarks/ssr/vue/vite.config.ts index b2b9fc8a09..312f43a7ae 100644 --- a/benchmarks/ssr/vue/vite.config.ts +++ b/benchmarks/ssr/vue/vite.config.ts @@ -3,7 +3,6 @@ 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)) @@ -23,8 +22,6 @@ export default defineConfig({ minify: false, }, test: { - execArgv: cpuSimulationExecArgv(), - isolate: true, name: '@benchmarks/ssr (vue)', watch: false, environment: 'node', diff --git a/benchmarks/tsconfig.json b/benchmarks/tsconfig.json deleted file mode 100644 index 5e9ff9a8e1..0000000000 --- a/benchmarks/tsconfig.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "../tsconfig.json", - "compilerOptions": { - "types": ["node"] - }, - "include": ["cpu-simulation.ts"] -} diff --git a/docs/AGENTS.md b/docs/AGENTS.md deleted file mode 100644 index ab2d4117e2..0000000000 --- a/docs/AGENTS.md +++ /dev/null @@ -1,4 +0,0 @@ -# Documentation - -- Register new published pages in `router/config.json` or `start/config.json`; drafts need not be registered. -- Run `pnpm test:docs` from the repository root for Markdown link validation. It checks `docs/**/*.md`, not Markdown elsewhere. Relative links resolve from the containing file. diff --git a/docs/router/api/file-based-routing.md b/docs/router/api/file-based-routing.md index 7c94d484d1..ad3e07fad7 100644 --- a/docs/router/api/file-based-routing.md +++ b/docs/router/api/file-based-routing.md @@ -188,7 +188,7 @@ By default, this value is set to `false`. ### `autoCodeSplitting` -This feature is only available if you are using the TanStack Router Bundler Plugin with Vite, Rspack/Rsbuild or Webpack. With Esbuild, setting it to `true` is an error. +This feature is only available if you are using the TanStack Router Bundler Plugin. This option is used to enable automatic code-splitting for non-critical route configuration items. See the "Automatic Code-Splitting" guide for more information. diff --git a/docs/router/api/router/LinkOptionsType.md b/docs/router/api/router/LinkOptionsType.md index 9d3d3fe8d8..481a5b4a3d 100644 --- a/docs/router/api/router/LinkOptionsType.md +++ b/docs/router/api/router/LinkOptionsType.md @@ -9,7 +9,7 @@ The `LinkOptions` type extends the [`NavigateOptions`](./NavigateOptionsType.md) type LinkOptions = NavigateOptions & { target?: HTMLAnchorElement['target'] activeOptions?: ActiveOptions - preload?: false | 'intent' | 'viewport' | 'render' + preload?: false | 'intent' preloadDelay?: number disabled?: boolean } @@ -42,7 +42,7 @@ The `LinkOptions` object accepts/contains the following properties: - Type: `number` - Optional -- 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. +- Delay intent preloading by this many milliseconds. If the intent exits before this delay, the preload will be cancelled. ### `disabled` diff --git a/docs/router/api/router/NotFoundErrorType.md b/docs/router/api/router/NotFoundErrorType.md index 1f4fbe4c74..6d8b00a84b 100644 --- a/docs/router/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 `notFoundComponent` when the not-found error is handled +- Custom data that is passed into to `notFoundComponent` when the not-found error is handled ### `throw` property diff --git a/docs/router/api/router/RouteMatchType.md b/docs/router/api/router/RouteMatchType.md index b5009ebe68..251c2c031e 100644 --- a/docs/router/api/router/RouteMatchType.md +++ b/docs/router/api/router/RouteMatchType.md @@ -11,8 +11,9 @@ interface RouteMatch { routeId: string pathname: string params: Route['allParams'] - status: 'pending' | 'success' | 'error' | 'notFound' + status: 'pending' | 'success' | 'error' | 'redirected' | 'notFound' isFetching: false | 'beforeLoad' | 'loader' + showPending: boolean error: unknown paramsError: unknown searchError: unknown @@ -20,17 +21,9 @@ interface RouteMatch { loaderData?: Route['loaderData'] context: Route['allContext'] search: Route['fullSearchSchema'] + fetchedAt: number abortController: AbortController - cause: 'preload' | 'enter' | 'stay' + cause: 'enter' | 'stay' ssr?: boolean | 'data-only' } ``` - -`status` describes the match's render state. `isFetching` independently exposes -active `beforeLoad` or loader work. In particular, a successful match can report -`isFetching: 'loader'` while stale data remains visible during a background -reload. - -The router state can contain matches below the pending, error, or not-found -boundary. Those matches remain observable as part of the structurally matched -lane even though the route renderer stops at the boundary. diff --git a/docs/router/api/router/RouteOptionsType.md b/docs/router/api/router/RouteOptionsType.md index 2adfc6e5c6..3e575832de 100644 --- a/docs/router/api/router/RouteOptionsType.md +++ b/docs/router/api/router/RouteOptionsType.md @@ -56,7 +56,6 @@ The `RouteOptions` type accepts an object with the following properties: - Type: `(rawSearchParams: unknown) => TSearchSchema` - Optional - A function that will be called when this route is matched and passed the raw search params from the current location and return valid parsed search params. If this function throws, the route will be put into an error state and the error will be thrown during render. If this function does not throw, its return value will be used as the route's search params and the return type will be inferred into the rest of the router. -- This is a planning callback. It must be deterministic and side-effect-free for the same input; do not navigate or mutate application/router state from it. - Optionally, the parameter type can be tagged with the `SearchSchemaInput` type like this: `(searchParams: TSearchSchemaInput & SearchSchemaInput) => TSearchSchema`. If this tag is present, `TSearchSchemaInput` will be used to type the `search` property of `` and `navigate()` **instead of** `TSearchSchema`. The difference between `TSearchSchemaInput` and `TSearchSchema` can be useful, for example, to express optional search parameters. ### `search.middlewares` property @@ -71,7 +70,6 @@ The `RouteOptions` type accepts an object with the following properties: - Type: `(rawParams: Record) => TParams` - Optional - A function that will be called when this route is matched and passed the raw params from the current location and return valid parsed params. If this function throws, the route will be put into an error state and the error will be thrown during render. If this function does not throw, its return value will be used as the route's params and the return type will be inferred into the rest of the router. -- This is a planning callback. It must be deterministic and side-effect-free for the same input. ### `stringifyParams` method (⚠️ deprecated, use `params.stringify` instead) @@ -81,19 +79,9 @@ The `RouteOptions` type accepts an object with the following properties: ### `params.parse` method -- Type: `(rawParams: Record) => TParams | false` +- 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 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. +- 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. ### `params.stringify` method @@ -115,14 +103,14 @@ type beforeLoad = ( location: ParsedLocation navigate: NavigateFn // @deprecated buildLocation: BuildLocationFn - cause: 'preload' | 'enter' | 'stay' + cause: '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. +- This async function is called before a route is loaded. If an error is thrown here, the route's loader will not be called and the route will not render. If thrown during a navigation, the navigation will be canceled and the error will be passed to the `onError` function. If thrown during a preload event, the error will be logged to the console and the preload will fail. - 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. @@ -159,9 +147,9 @@ type loader = - 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. +- This async function is called when a route is matched and passed the route's match object. If an error is thrown here, the route will be put into an error state and the error will be thrown during render. If thrown during a navigation, the navigation will be canceled and the error will be passed to the `onError` function. If thrown during a preload event, the error will be logged to the console and the preload will fail. - 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. +- If this function returns a `TLoaderData` object, that object will be stored on the route match until the route match is no longer active. It can be accessed using the `useLoaderData` hook in any component that is a child of the route match before another `` is rendered. - 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. @@ -179,7 +167,6 @@ 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. @@ -190,26 +177,19 @@ type loaderDeps = (opts: { search: TFullSearchSchema }) => Record - Defaults to `routerOptions.defaultStaleTime`, which defaults to `0` - The amount of time in milliseconds that a route match's loader data will be considered fresh. If a route match is matched again within this time frame, its loader data will not be reloaded. -### `preload` property - -- Type: `boolean` -- Optional -- Defaults to `true` -- If `false`, speculative preloads still run this route's `beforeLoad` function but skip its `loader`. A navigation runs both `beforeLoad` and the skipped `loader` normally. - ### `preloadStaleTime` property - Type: `number` - Optional - Defaults to `routerOptions.defaultPreloadStaleTime`, which defaults to `30_000` ms (30 seconds) -- The amount of time in milliseconds that 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`. +- The amount of time in milliseconds that a route match's loader data will be considered fresh when preloading. If a route match is preloaded again within this time frame, its loader data will not be reloaded. If a route match is loaded (for navigation) within this time frame, the normal `staleTime` is used instead. ### `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. +- Defaults to `routerOptions.defaultGcTime`, which defaults to 30 minutes. +- The amount of time in milliseconds that a route match's loader data will be kept in memory after a preload or it is no longer in use. ### `shouldReload` property @@ -245,12 +225,12 @@ type loaderDeps = (opts: { search: TFullSearchSchema }) => Record - Defaults to `routerOptions.defaultPendingMinMs` which defaults to `500` - The minimum amount of time in milliseconds that the pending component will be shown for if it is shown. This is useful to prevent the pending component from flashing on the screen for a split second. -### `preloadGcTime` property +### `preloadMaxAge` 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. +- Defaults to `30_000` ms (30 seconds) +- The maximum amount of time in milliseconds that a route's preloaded route data will be cached for. If a route is not matched within this time frame, its loader data will be discarded. ### `preSearchFilters` property (⚠️ deprecated, use `search.middlewares` instead) @@ -273,33 +253,29 @@ type loaderDeps = (opts: { search: TFullSearchSchema }) => Record - Type: `(error: any) => void` - Optional - A function that will be called when an error is thrown during a navigation or preload event. -- If this function throws a [`redirect`](./redirectFunction.md), 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. +- If this function throws a [`redirect`](./redirectFunction.md), then the router will process and apply the redirect immediately. ### `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 +- Type: `(error: Error, errorInfo: ErrorInfo) => void` - Optional - Defaults to `routerOptions.defaultOnCatch` - A function that will be called when errors are caught when the route encounters an error. diff --git a/docs/router/api/router/RouterEventsType.md b/docs/router/api/router/RouterEventsType.md index c27887fba1..45d6431cdf 100644 --- a/docs/router/api/router/RouterEventsType.md +++ b/docs/router/api/router/RouterEventsType.md @@ -13,7 +13,6 @@ type RouterEvents = { toLocation: ParsedLocation pathChanged: boolean hrefChanged: boolean - hashChanged: boolean } onBeforeLoad: { type: 'onBeforeLoad' @@ -21,7 +20,6 @@ type RouterEvents = { toLocation: ParsedLocation pathChanged: boolean hrefChanged: boolean - hashChanged: boolean } onLoad: { type: 'onLoad' @@ -29,7 +27,6 @@ type RouterEvents = { toLocation: ParsedLocation pathChanged: boolean hrefChanged: boolean - hashChanged: boolean } onResolved: { type: 'onResolved' @@ -37,7 +34,6 @@ type RouterEvents = { toLocation: ParsedLocation pathChanged: boolean hrefChanged: boolean - hashChanged: boolean } onBeforeRouteMount: { type: 'onBeforeRouteMount' @@ -45,15 +41,14 @@ type RouterEvents = { toLocation: ParsedLocation pathChanged: boolean hrefChanged: boolean - hashChanged: boolean + } + onInjectedHtml: { + type: 'onInjectedHtml' } onRendered: { type: 'onRendered' fromLocation?: ParsedLocation toLocation: ParsedLocation - pathChanged: boolean - hrefChanged: boolean - hashChanged: boolean } } ``` @@ -64,7 +59,7 @@ Once an event is emitted, the following properties will be present on the event ### `type` property -- Type: `onBeforeNavigate | onBeforeLoad | onLoad | onBeforeRouteMount | onResolved | onRendered` +- Type: `onBeforeNavigate | onBeforeLoad | onLoad | onBeforeRouteMount | onResolved` - The type of the event - This is useful for discriminating between events in a listener function. @@ -88,11 +83,6 @@ Once an event is emitted, the following properties will be present on the event - Type: `boolean` - `true` if the href has changed between the `fromLocation` and `toLocation`. -### `hashChanged` property - -- Type: `boolean` -- `true` if the hash has changed between the `fromLocation` and `toLocation`. - ## Example ```tsx diff --git a/docs/router/api/router/RouterOptionsType.md b/docs/router/api/router/RouterOptionsType.md index 31f410b208..7127e1191e 100644 --- a/docs/router/api/router/RouterOptionsType.md +++ b/docs/router/api/router/RouterOptionsType.md @@ -59,7 +59,7 @@ The `RouterOptions` type accepts an object with the following properties and met - Type: `number` - Optional - Defaults to `50` -- The delay in milliseconds before intent focus/hover and viewport preloading. Touch intent preloads immediately. +- The delay in milliseconds that a route must be hovered over or touched before it is preloaded. ### `defaultComponent` property @@ -129,19 +129,19 @@ The `RouterOptions` type accepts an object with the following properties and met - Type: `number` - Optional -- Defaults to 5 minutes. +- Defaults to `routerOptions.defaultGcTime`, which defaults to 30 minutes. - The default `preloadGcTime` a route should use if no preloadGcTime is provided. ### `defaultGcTime` property - Type: `number` - Optional -- Defaults to 5 minutes. +- Defaults to 30 minutes. - The default `gcTime` a route should use if no gcTime is provided. ### `defaultOnCatch` property -- Type: `(error: unknown, errorInfo: ErrorInfo) => void` +- Type: `(error: Error, errorInfo: ErrorInfo) => void` - Optional - The default `onCatch` handler for errors caught by the Router ErrorBoundary @@ -223,13 +223,6 @@ const router = createRouter({ - Defaults to `/` - The basepath for the entire router. This is useful for mounting a router instance at a subpath. -### `origin` property - -- Type: `string` -- Optional -- The origin used to resolve URLs. Defaults to the browser origin, or `http://localhost` on the server and in browsers with an opaque origin. -- Pass a normalized origin, such as `https://example.com` or `http://localhost:3000`, without a path or trailing slash. The router uses this value as provided; if you have a full URL, normalize it with `new URL(url).origin` before passing it to the router. - ### `rewrite` property - Type: `LocationRewrite` @@ -375,10 +368,9 @@ const router = createRouter({ ### `pathParamsAllowedCharacters` property -- Type: `ReadonlyArray<';' | ':' | '@' | '&' | '=' | '+' | '$' | ','>` +- Type: `Array<';' | ':' | '@' | '&' | '=' | '+' | '$' | ','>` - Optional - Configures which URI characters are allowed in path params that would ordinarily be escaped by encodeURIComponent. -- Read only when the router is created. To change these characters, create a new router instance. Router option updates and provider props do not change this setting. ### `defaultStructuralSharing` property diff --git a/docs/router/api/router/RouterStateType.md b/docs/router/api/router/RouterStateType.md index 4da9cd9bb6..a77f4e775f 100644 --- a/docs/router/api/router/RouterStateType.md +++ b/docs/router/api/router/RouterStateType.md @@ -3,17 +3,16 @@ id: RouterStateType title: RouterState type --- -The `RouterState` type represents the observable state of the router, including -the requested and resolved locations, match presentation, and foreground loading -status. +The `RouterState` type represents shape of the internal state of the router. The Router's internal state is useful, if you need to access certain internals of the router, such as any pending matches, is the router in its loading state, etc. ```tsx type RouterState = { status: 'pending' | 'idle' isLoading: boolean + isTransitioning: boolean matches: Array location: ParsedLocation - resolvedLocation?: ParsedLocation + resolvedLocation: ParsedLocation } ``` @@ -24,24 +23,22 @@ The `RouterState` type contains all of the properties that are available on the ### `status` property - Type: `'pending' | 'idle'` -- The current foreground status of the router. `pending` means the requested route is still loading or waiting for its framework transition to settle. +- The current status of the router. If the router is pending, it means that it is currently loading a route or the router is still transitioning to the new route. ### `isLoading` property - Type: `boolean` -- `true` when `status` is `pending`. -- Background loader refreshes do not change this value. Inspect each match's `isFetching` field to observe foreground `beforeLoad`/loader work and background loader work. +- `true` if the router is currently loading a route or waiting for a route to finish loading. + +### `isTransitioning` property + +- Type: `boolean` +- `true` if the router is currently transitioning to a new route. ### `matches` property - Type: [`Array`](./RouteMatchType.md) -- The match presentation currently exposed to the application. -- A navigation can keep the previous presentation visible until pending UI is - published. Once the destination is presented, this contains its complete - structurally matched lane, including descendants that are still loading. -- Error and not-found results also preserve the complete structurally matched - lane. Rendering stops at the selected pending or terminal boundary; it does - not truncate this array. +- An array of all of the route matches that have been resolved and are currently active. ### `location` property @@ -50,5 +47,5 @@ The `RouterState` type contains all of the properties that are available on the ### `resolvedLocation` property -- Type: [`ParsedLocation`](./ParsedLocationType.md) | `undefined` -- The location whose load and framework transition have settled. It is `undefined` before the initial location resolves. +- Type: [`ParsedLocation`](./ParsedLocationType.md) +- The location that the router has resolved and loaded. diff --git a/docs/router/api/router/RouterType.md b/docs/router/api/router/RouterType.md index 3fde90e32e..0b829b85e0 100644 --- a/docs/router/api/router/RouterType.md +++ b/docs/router/api/router/RouterType.md @@ -11,9 +11,8 @@ An instance of the `Router` has the following properties and methods: ### `.update` method -- Type: `(newOptions: Omit) => void` +- Type: `(newOptions: RouterOptions) => void` - Updates the router instance with new options. -- Initialization-only options such as `pathParamsAllowedCharacters` cannot be updated. Create a new router instance to change them. ### `state` property @@ -24,11 +23,10 @@ An instance of the `Router` has the following properties and methods: ### `.subscribe` method -- Type: `(eventType: TType, fn: ListenerFn) => () => void` +- Type: `(eventType: TType, fn: ListenerFn) => (event: RouterEvent) => void` - Subscribes to a [`RouterEvent`](./RouterEventsType.md). - Returns a function that can be used to unsubscribe from the event. -- The listener will be called with the event payload whenever that event is emitted. -- See the [Router Events guide](../../guide/router-events.md) for lifecycle ordering and usage patterns. +- The callback provided to the returned function will be called with the event that was emitted. ### `.matchRoutes` method @@ -36,6 +34,16 @@ An instance of the `Router` has the following properties and methods: - Matches a pathname and search params against the router's route tree and returns an array of route matches. - If `opts.throwOnError` is `true`, any errors that occur during the matching process will be thrown (in addition to being returned in the route match's `error` property). +### `.cancelMatch` method + +- Type: `(matchId: string) => void` +- Cancels a route match that is currently pending by calling `match.abortController.abort()`. + +### `.cancelMatches` method + +- Type: `() => void` +- Cancels all route matches that are currently pending by calling `match.abortController.abort()` on each one. + ### `.buildLocation` method Builds a new parsed location object that can be used later to navigate to a new location. @@ -129,27 +137,23 @@ Navigates to a new location. ### `.invalidate` method -Invalidates selected route-match generations, reruns their loading lifecycle, -reruns `beforeLoad`, and reloads their loaders through the normal loading -protocol. +Invalidates route matches by forcing their `beforeLoad` and `load` functions to be called again. - Type: `(opts?: {filter?: (d: MakeRouteMatchUnion) => boolean, sync?: boolean, forcePending?: boolean }) => Promise` - This is useful any time your loader data might be out of date or stale. For example, if you have a route that displays a list of posts, and you have a loader function that fetches the list of posts from an API, you might want to invalidate the route matches for that route any time a new post is created so that the list of posts is always up-to-date. -- If `filter` is not supplied, all committed, cached, and in-flight match generations are invalidated. -- If `filter` is supplied, it is evaluated against committed, cached, and in-flight matches. Selecting one generation invalidates every committed, cached, or in-flight generation with the same match ID. -- Invalidation reruns `beforeLoad`; reusable loader data is marked stale and reloads through the normal loading protocol. Route-level `context` remains reusable while the match ID is unchanged. -- If `sync` is `true`, stale loader work is blocking and the returned promise resolves after it finishes instead of leaving a background refresh detached. -- If `forcePending` is `true`, selected routes that need loading enter the normal pending protocol even when successful data was already available. +- if `filter` is not supplied, all matches will be invalidated +- if `filter` is supplied, only matches for which `filter` returns `true` will be invalidated. +- if `sync` is true, the promise returned by this function will only resolve once all loaders have finished. +- if `forcePending` is true, the invalidated matches will be put into `'pending'` state regardless whether they are in `'error'` state or not. - You might also want to invalidate the Router if you imperatively `reset` the router's `CatchBoundary` to trigger loaders again. ### `.clearCache` method -Remove cached route matches and matching active preloads. +Remove cached route matches. - Type: `(opts?: {filter?: (d: MakeRouteMatchUnion) => boolean}) => void` -- If `filter` is not supplied, all cached matches and active preload lanes are removed. -- If `filter` is supplied, matching cached matches are removed. An active preload lane is canceled when any match in that lane passes the filter. -- Current committed and presented matches are not removed. +- if `filter` is not supplied, all cached matches will be removed +- if `filter` is supplied, only matches for which `filter` returns `true` will be removed. ### `.load` method @@ -165,28 +169,16 @@ Loads all of the currently matched route matches and resolves when they are all Preloads all of the matches that match the provided `NavigateOptions`. -An active preload is speculative and is not published as the current match -presentation. Successful loader data can enter the normal in-memory route -cache. Its freshness follows `preloadStaleTime`; once unused and older than -`preloadGcTime`, it is eligible for pruning during a later cache -reconciliation. +> ⚠️⚠️⚠️ **Preloaded route matches are not stored long-term in the router state. They are only stored until the next attempted navigation action.** -Every preload and navigation runs its own `beforeLoad` chain. A later lane can -reuse successful settled loader data or join loader work that is still in -flight, but it never reuses `beforeLoad` context or an already-settled -redirect, error, or not-found result. If joined loader work later produces a -terminal outcome, all current consumers of that flight observe it. - -- Type: `(opts: NavigateOptions) => Promise` +- Type: `(opts?: NavigateOptions) => Promise` - Properties - `opts` - Type: `NavigateOptions` - - Required. + - Optional, defaults to the current location. - The options that will be used to determine which route matches to preload. - Returns - - A promise that resolves with the speculative route-match lane. An ordinary error or not-found is represented by a terminal match array rather than a rejected promise. - - It resolves with `undefined` when cancellation or control flow does not produce a reusable lane. - - The method is also available on server router instances. It remains speculative and does not change the request's current location or presented matches. + - A promise that resolves with an array of all of the route matches that were preloaded. ### `.loadRouteChunk` method diff --git a/docs/router/api/router/catchBoundaryComponent.md b/docs/router/api/router/catchBoundaryComponent.md index aa2f6eb7ce..deef0ffa22 100644 --- a/docs/router/api/router/catchBoundaryComponent.md +++ b/docs/router/api/router/catchBoundaryComponent.md @@ -29,7 +29,7 @@ The `CatchBoundary` component accepts the following props: ### `props.onCatch` prop -- Type: `(error: unknown, errorInfo: ErrorInfo) => void` in React; `(error: unknown) => void` in Vue; `(error: Error) => void` in Solid +- Type: `(error: any) => void` - Optional - A callback that will be called with the error that was thrown by the component's children. diff --git a/docs/router/api/router/errorComponentComponent.md b/docs/router/api/router/errorComponentComponent.md index 07d7187580..04399f124d 100644 --- a/docs/router/api/router/errorComponentComponent.md +++ b/docs/router/api/router/errorComponentComponent.md @@ -3,7 +3,7 @@ id: errorComponentComponent title: ErrorComponent component --- -The `ErrorComponent` component renders an error notice and optional details about the thrown value. +The `ErrorComponent` component is a component that renders an error message and optionally the error's message. ## ErrorComponent props @@ -11,8 +11,8 @@ The `ErrorComponent` component accepts the following props: ### `props.error` prop -- Type: `unknown` in React and Vue; `Error` in Solid -- The caught error. Solid normalizes non-`Error` values, including SSR loader errors, into an `Error` with the original value in `cause`. +- Type: `TError` (defaults to `Error`) +- The error that was thrown by the component's children ### `props.info` prop @@ -27,6 +27,6 @@ The `ErrorComponent` component accepts the following props: ## ErrorComponent returns -- Displays an error notice, with details when the thrown value has a nonempty `message`. Values without a message still display the error notice. +- Returns a formatted error message with the error's message if it exists. - The error message can be toggled by clicking the "Show Error" button. - By default, the error message will be shown in development. diff --git a/docs/router/api/router/linkComponent.md b/docs/router/api/router/linkComponent.md index 478271a208..a8227913b5 100644 --- a/docs/router/api/router/linkComponent.md +++ b/docs/router/api/router/linkComponent.md @@ -43,7 +43,7 @@ By default, param values with characters such as `@` will be encoded in the URL: ``` -To opt out, set [pathParamsAllowedCharacters](../router/RouterOptionsType#pathparamsallowedcharacters-property) when creating the router. This setting cannot be changed on an existing router instance. +To opt-out, update the [pathParamsAllowedCharacters](../router/RouterOptionsType#pathparamsallowedcharacters-property) config on the router ```tsx import { createRouter } from '@tanstack/react-router' diff --git a/docs/router/api/router/useBlockerHook.md b/docs/router/api/router/useBlockerHook.md index 3d9c00d602..98d4a06c3b 100644 --- a/docs/router/api/router/useBlockerHook.md +++ b/docs/router/api/router/useBlockerHook.md @@ -20,7 +20,7 @@ The `useBlocker` hook accepts a single _required_ argument, an option object: - Think of this function as telling the router if it should block the navigation, so returning `true` mean that it should block the navigation and `false` meaning that it should be allowed ```ts -type ShouldBlockFnLocation<...> = { +interface ShouldBlockFnLocation<...> { routeId: TRouteId fullPath: TFullPath pathname: string diff --git a/docs/router/api/router/useChildMatchesHook.md b/docs/router/api/router/useChildMatchesHook.md index 13212e61e0..d6de892192 100644 --- a/docs/router/api/router/useChildMatchesHook.md +++ b/docs/router/api/router/useChildMatchesHook.md @@ -5,9 +5,8 @@ title: useChildMatches hook The `useChildMatches` hook returns all of the child [`RouteMatch`](./RouteMatchType.md) objects from the closest match down to the leaf-most match. **It does not include the current match, which can be obtained using the `useMatch` hook.** -The result is derived from the router's current match presentation. It can -include still-loading descendants and descendants below the current render -boundary. +> [!IMPORTANT] +> If the router has pending matches and they are showing their pending component fallbacks, pending matches are used instead of active matches. ## useChildMatches options diff --git a/docs/router/api/router/useMatchRouteHook.md b/docs/router/api/router/useMatchRouteHook.md index e67ccb6cbd..01c26d07c6 100644 --- a/docs/router/api/router/useMatchRouteHook.md +++ b/docs/router/api/router/useMatchRouteHook.md @@ -3,9 +3,7 @@ id: useMatchRouteHook title: useMatchRoute hook --- -The `useMatchRoute` hook returns a `matchRoute` function that can be used to match a route against either the current or pending location. The hook subscribes the component to changes in the router state used for matching, making it useful when the match result affects what the component renders. - -The `matchRoute` function's identity changes when that router state changes. For an imperative check, such as one performed in an event handler, use [`useRouter`](./useRouterHook.md) and call `router.matchRoute` instead. The router instance is stable, and this avoids subscribing the component to router state that it does not use while rendering. +The `useMatchRoute` hook is a hook that returns a `matchRoute` function that can be used to match a route against either the current or pending location. ## useMatchRoute returns @@ -27,8 +25,6 @@ The `matchRoute` function accepts a single argument, an `options` object. ## Examples -Use `useMatchRoute` when the result determines the rendered output: - ```tsx import { useMatchRoute } from '@tanstack/react-router' @@ -37,36 +33,7 @@ function Component() { const matchRoute = useMatchRoute() const params = matchRoute({ to: '/posts/$postId' }) // ^ { postId: '123' } - - return params ? : } -``` - -For a check made at the time of an event, call `router.matchRoute` directly: - -```tsx -import { useRouter } from '@tanstack/react-router' - -function Component() { - const router = useRouter() - - return ( - - ) -} -``` - -Additional matching examples: - -```tsx -import { useMatchRoute } from '@tanstack/react-router' // Current location: /posts/123 function Component() { diff --git a/docs/router/api/router/useMatchesHook.md b/docs/router/api/router/useMatchesHook.md index e57c6c2c7e..d7a1be8dc3 100644 --- a/docs/router/api/router/useMatchesHook.md +++ b/docs/router/api/router/useMatchesHook.md @@ -3,7 +3,7 @@ id: useMatchesHook title: useMatches hook --- -The `useMatches` hook returns the router's complete presented array of [`RouteMatch`](./RouteMatchType.md) objects **regardless of its caller's position in the component tree**. The array can include still-loading descendants or matches below a pending/error/not-found render boundary. +The `useMatches` hook returns all of the [`RouteMatch`](./RouteMatchType.md) objects from the router **regardless of its callers position in the React component tree**. > [!TIP] > If you only want the parent or child matches, then you can use the [`useParentMatches`](./useParentMatchesHook.md) or the [`useChildMatches`](./useChildMatchesHook.md) based on the selection you need. diff --git a/docs/router/api/router/useParentMatchesHook.md b/docs/router/api/router/useParentMatchesHook.md index a0ce985411..7afc5585a6 100644 --- a/docs/router/api/router/useParentMatchesHook.md +++ b/docs/router/api/router/useParentMatchesHook.md @@ -5,9 +5,8 @@ title: useParentMatches hook The `useParentMatches` hook returns all of the parent [`RouteMatch`](./RouteMatchType.md) objects from the root down to the immediate parent of the current match in context. **It does not include the current match, which can be obtained using the `useMatch` hook.** -The result is derived from the router's current match presentation. During a -navigation that may still be the previous presentation; after pending UI is -published it is the destination's complete structurally matched lane. +> [!IMPORTANT] +> If the router has pending matches and they are showing their pending component fallbacks, pending matches are used instead of active matches. ## useParentMatches options diff --git a/docs/router/comparison.md b/docs/router/comparison.md index 8eaef776f3..84a2119162 100644 --- a/docs/router/comparison.md +++ b/docs/router/comparison.md @@ -80,7 +80,7 @@ Feature/Capability Key: | React Server Function Middleware | ✅ | 🛑 | 🛑 | | API Routes | ✅ | ✅ | ✅ | | API Middleware | ✅ | ✅ | ✅ | -| React Server Components | 🟡 (Experimental) | 🟡 (Experimental) | ✅ | +| React Server Components | 🛑 | 🟡 (Experimental) | ✅ | | `
` API | 🛑 | ✅ | ✅ | [bp-tanstack-router]: https://badgen.net/bundlephobia/minzip/@tanstack/react-router diff --git a/docs/router/config.json b/docs/router/config.json index 1258ddd817..e13b8e403f 100644 --- a/docs/router/config.json +++ b/docs/router/config.json @@ -25,6 +25,10 @@ "label": "Decisions on DX", "to": "decisions-on-dx" }, + { + "label": "LLM Assistance Support", + "to": "llm-support" + }, { "label": "Comparison", "to": "comparison" @@ -94,7 +98,7 @@ ] }, { - "label": "Core Routing", + "label": "Routing", "children": [ { "label": "Routing Concepts", @@ -123,10 +127,6 @@ { "label": "File Naming Conventions", "to": "routing/file-naming-conventions" - }, - { - "label": "URL Rewrites", - "to": "guide/url-rewrites" } ], "frameworks": [ @@ -141,21 +141,28 @@ ] }, { - "label": "Navigation & URL State", - "collapsible": true, + "label": "Guides", "children": [ + { + "label": "Code Splitting", + "to": "guide/code-splitting" + }, + { + "label": "Automatic Code Splitting", + "to": "guide/automatic-code-splitting" + }, + { + "label": "Creating a Router", + "to": "guide/creating-a-router" + }, + { + "label": "Outlets", + "to": "guide/outlets" + }, { "label": "Navigation", "to": "guide/navigation" }, - { - "label": "Link Options", - "to": "guide/link-options" - }, - { - "label": "Custom Links", - "to": "guide/custom-link" - }, { "label": "Path Params", "to": "guide/path-params" @@ -165,52 +172,12 @@ "to": "guide/search-params" }, { - "label": "Custom Search Param Serialization", - "to": "guide/custom-search-param-serialization" + "label": "Link Options", + "to": "guide/link-options" }, { - "label": "Route Masking", - "to": "guide/route-masking" - }, - { - "label": "Navigation Blocking", - "to": "guide/navigation-blocking" - }, - { - "label": "History Types", - "to": "guide/history-types" - }, - { - "label": "Scroll Restoration", - "to": "guide/scroll-restoration" - }, - { - "label": "Internationalization", - "to": "guide/internationalization-i18n" - } - ], - "frameworks": [ - { - "label": "react", - "children": [] - }, - { - "label": "solid", - "children": [] - } - ] - }, - { - "label": "Data & Rendering", - "collapsible": true, - "children": [ - { - "label": "Code Splitting", - "to": "guide/code-splitting" - }, - { - "label": "Automatic Code Splitting", - "to": "guide/automatic-code-splitting" + "label": "Custom Links", + "to": "guide/custom-link" }, { "label": "Data Loading", @@ -228,6 +195,14 @@ "label": "Data Mutations", "to": "guide/data-mutations" }, + { + "label": "Type Safety", + "to": "guide/type-safety" + }, + { + "label": "Type Utilities", + "to": "guide/type-utilities" + }, { "label": "Preloading", "to": "guide/preloading" @@ -237,48 +212,20 @@ "to": "guide/document-head-management" }, { - "label": "SSR", - "to": "guide/ssr" + "label": "Route Masking", + "to": "guide/route-masking" }, { - "label": "Render Optimizations", - "to": "guide/render-optimizations" - } - ], - "frameworks": [ - { - "label": "react", - "children": [] + "label": "Navigation Blocking", + "to": "guide/navigation-blocking" }, { - "label": "solid", - "children": [] - } - ] - }, - { - "label": "Router Configuration", - "collapsible": true, - "children": [ - { - "label": "Creating a Router", - "to": "guide/creating-a-router" + "label": "Custom Search Param Serialization", + "to": "guide/custom-search-param-serialization" }, { - "label": "Outlets", - "to": "guide/outlets" - }, - { - "label": "Router Events", - "to": "guide/router-events" - }, - { - "label": "Type Safety", - "to": "guide/type-safety" - }, - { - "label": "Type Utilities", - "to": "guide/type-utilities" + "label": "History Types", + "to": "guide/history-types" }, { "label": "Router Context", @@ -292,9 +239,21 @@ "label": "Authenticated Routes", "to": "guide/authenticated-routes" }, + { + "label": "Scroll Restoration", + "to": "guide/scroll-restoration" + }, { "label": "Static Route Data", "to": "guide/static-route-data" + }, + { + "label": "SSR", + "to": "guide/ssr" + }, + { + "label": "Render Optimizations", + "to": "guide/render-optimizations" } ], "frameworks": [ diff --git a/docs/router/decisions-on-dx.md b/docs/router/decisions-on-dx.md index a06ec4b331..26c366a9da 100644 --- a/docs/router/decisions-on-dx.md +++ b/docs/router/decisions-on-dx.md @@ -39,7 +39,7 @@ But to achieve this, we had to make some decisions that deviate from the norms i ## Why is the Router's configuration done this way? -When you want to leverage TypeScript's inference features to its fullest, you'll quickly realize that _Generics_ are your best friend. And so, TanStack Router uses Generics everywhere to ensure that the types of your routes are inferred as much as possible. +When you want to leverage the TypeScript's inference features to its fullest, you'll quickly realize that _Generics_ are your best friend. And so, TanStack Router uses Generics everywhere to ensure that the types of your routes are inferred as much as possible. This means that you have to define your routes in a way that allows TypeScript to infer the types of your routes as much as possible. @@ -219,7 +219,7 @@ TanStack Router's file-based routing is designed to solve all of these issues. I The file-based routing approach is powered by the TanStack Router Bundler Plugin. It performs 3 essential tasks that solve the pain points in route configuration when using code-based routing: 1. **Route configuration boilerplate**: It generates the boilerplate for your route configurations. -2. **Route tree stitching**: It stitches together your route configurations into a single cohesive route-tree. Also in the background, it correctly updates the route configurations to define the `getParentRoute` function and so matches the routes with their parent routes. +2. **Route tree stitching**: It stitches together your route configurations into a single cohesive route-tree. Also in the background, it correctly updates the route configurations to define the `getParentRoute` function match the routes with their parent routes. 3. **Code-splitting**: It automatically code-splits your route content components and updates the route configurations with the correct component. Additionally, at runtime, it ensures that the correct component is loaded when the route is visited. Let's take a look at how the route configuration for the previous example would look like with file-based routing. diff --git a/docs/router/eslint/create-route-property-order.md b/docs/router/eslint/create-route-property-order.md index 453fd64acc..c22aa7c52d 100644 --- a/docs/router/eslint/create-route-property-order.md +++ b/docs/router/eslint/create-route-property-order.md @@ -37,10 +37,7 @@ import { createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/path')({ loader: async ({ context }) => { - await context.queryClient.query({ - ...getQueryOptions(context.hello), - staleTime: 'static', - }) + await context.queryClient.ensureQueryData(getQueryOptions(context.hello)) }, beforeLoad: () => ({ hello: 'world' }), }) @@ -58,10 +55,7 @@ import { createFileRoute } from '@tanstack/solid-router' export const Route = createFileRoute('/path')({ loader: async ({ context }) => { - await context.queryClient.query({ - ...getQueryOptions(context.hello), - staleTime: 'static', - }) + await context.queryClient.ensureQueryData(getQueryOptions(context.hello)) }, beforeLoad: () => ({ hello: 'world' }), }) @@ -86,10 +80,7 @@ import { createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/path')({ beforeLoad: () => ({ hello: 'world' }), loader: async ({ context }) => { - await context.queryClient.query({ - ...getQueryOptions(context.hello), - staleTime: 'static', - }) + await context.queryClient.ensureQueryData(getQueryOptions(context.hello)) }, }) ``` @@ -107,10 +98,7 @@ import { createFileRoute } from '@tanstack/solid-router' export const Route = createFileRoute('/path')({ beforeLoad: () => ({ hello: 'world' }), loader: async ({ context }) => { - await context.queryClient.query({ - ...getQueryOptions(context.hello), - staleTime: 'static', - }) + await context.queryClient.ensureQueryData(getQueryOptions(context.hello)) }, }) ``` diff --git a/docs/router/guide/authenticated-routes.md b/docs/router/guide/authenticated-routes.md index 5e96fff2ca..706e89955c 100644 --- a/docs/router/guide/authenticated-routes.md +++ b/docs/router/guide/authenticated-routes.md @@ -5,8 +5,6 @@ title: Authenticated Routes Authentication is an extremely common requirement for web applications. In this guide, we'll walk through how to use TanStack Router to build protected routes, and how to redirect users to login if they try to access them. -> **A route guard is not a data authorization boundary.** This guide shows how to gate a route's UI behind `beforeLoad`. Any server function, server route, or API endpoint that returns private data must authorize the request itself, because it can be requested independently of the route that calls it. See [Authentication Server Primitives](../../start/framework/react/guide/authentication-server-primitives.md) in the Start docs. - ## The `route.beforeLoad` Option The `route.beforeLoad` option allows you to specify a function that will be called before a route is loaded. It receives all of the same arguments that the `route.loader` function does. This is a great place to check if a user is authenticated, and redirect them to a login page if they are not. diff --git a/docs/router/guide/automatic-code-splitting.md b/docs/router/guide/automatic-code-splitting.md index 859a19ff09..4612c298c6 100644 --- a/docs/router/guide/automatic-code-splitting.md +++ b/docs/router/guide/automatic-code-splitting.md @@ -4,7 +4,7 @@ title: Automatic Code Splitting The automatic code splitting feature in TanStack Router allows you to optimize your application's bundle size by lazily loading route components and their associated data. This is particularly useful for large applications where you want to minimize the initial load time by only loading the necessary code for the current route. -To turn this feature on, simply set the `autoCodeSplitting` option to `true` in your bundler plugin configuration. This enables the router to automatically handle code splitting for your routes without requiring any additional setup. It is available with Vite, Rspack/Rsbuild and Webpack, not with Esbuild. +To turn this feature on, simply set the `autoCodeSplitting` option to `true` in your bundler plugin configuration. This enables the router to automatically handle code splitting for your routes without requiring any additional setup. ```ts // vite.config.ts @@ -35,7 +35,7 @@ This happens seamlessly, without requiring you to manually split your code or ma ### The transformation process -When you enable automatic code splitting, the bundler plugin does this by using static code analysis to look at the code in your route files and to transform them into optimized outputs. +When you enable automatic code splitting, the bundler plugin does this by using static code analysis look at your the code in your route files to transform them into optimized outputs. This transformation process produces two key outputs when each of your route files are processed: @@ -48,7 +48,7 @@ This process ensures that your original code remains clean and readable, while t The decision of what to split into separate chunks is crucial for optimizing your application's performance. TanStack Router uses a concept called "**Split Groupings**" to determine how different parts of your route should be bundled together. -Split groupings are arrays of properties that tell TanStack Router how to bundle different parts of your route together. Each grouping is a list of property names that you want to bundle together into a single lazy-loaded chunk. +Split groupings are arrays of properties that tell TanStack Router how to bundle different parts of your route together. Each grouping is an list of property names that you want to bundle together into a single lazy-loaded chunk. The available properties to split are: @@ -76,7 +76,7 @@ This means that it creates three separate lazy-loaded chunks for each route. Res ### Rules of Splitting -For automatic code splitting to work, there are some rules in place to make sure that this process can happen reliably and predictably. +For automatic code splitting to work, there are some rules in-place to make sure that this process can reliably and predictably happen. #### Do not export route properties diff --git a/docs/router/guide/code-splitting.md b/docs/router/guide/code-splitting.md index b1423253be..698bf262b5 100644 --- a/docs/router/guide/code-splitting.md +++ b/docs/router/guide/code-splitting.md @@ -115,7 +115,7 @@ These are the only options that `createLazyFileRoute` supports: ### Example code splitting with `.lazy.tsx` -When you are using `.lazy.tsx`, you can split your route into two files to enable code splitting: +When you are using `.lazy.tsx` you can split your route into two files to enable code splitting: **Before (Single File)** diff --git a/docs/router/guide/data-loading.md b/docs/router/guide/data-loading.md index 6b9fd42777..2ecdf443ad 100644 --- a/docs/router/guide/data-loading.md +++ b/docs/router/guide/data-loading.md @@ -81,7 +81,7 @@ Use the object form when you want to configure loader-specific behavior such as The `loader` function receives a single object with the following properties: -- `abortController` - The controller for this shareable loader invocation. A preload and navigation can share the same in-flight loader work. Its signal is cancelled after the invocation becomes outdated and no consumer still needs it. +- `abortController` - The route's abortController. Its signal is cancelled when the route is unloaded or when the Route is no longer relevant and the current invocation of the `loader` function becomes outdated. - `cause` - The cause of the current route match. Can be either one of the following: - `enter` - When the route is matched and loaded after not being matched in the previous location. - `preload` - When the route is being preloaded. @@ -150,7 +150,7 @@ Using these dependencies as keys, TanStack Router will cache the data returned f To control router dependencies and "freshness", TanStack Router provides a plethora of options to control the keying and caching behavior of your route loaders. Let's take a look at them in the order that you are most likely to use them: - `routeOptions.loaderDeps` - - A deterministic, side-effect-free function that supplies you the validated search params for a router and returns a serializable object of dependencies for use in your `loader` function. When these deps change from navigation to navigation, it will cause the route to reload regardless of `staleTime`s. The deps are compared using a deep equality check. + - A function that supplies you the search params for a router and returns an object of dependencies for use in your `loader` function. When these deps changed from navigation to navigation, it will cause the route to reload regardless of `staleTime`s. The deps are compared using a deep equality check. - `routeOptions.staleTime` - `routerOptions.defaultStaleTime` - The number of milliseconds that a route's data should be considered fresh when attempting to load. @@ -168,11 +168,11 @@ To control router dependencies and "freshness", TanStack Router provides a pleth ### ⚠️ Some Important Defaults -- By default, `staleTime` is set to `0`, so reusable successful data is immediately considered stale. When the same loader key is entered again or `router.load()` is called explicitly, stale data revalidates in the background by default. A different loader key identifies a separate cache entry and must load if it has no reusable data. -- By default, loader data produced by a preload is considered fresh for **30 seconds**. Every preload and navigation still runs its own `beforeLoad` chain, but a later preload and the first navigation can reuse the preload's loader data or in-flight loader work during that interval. After navigation accepts that loader generation, subsequent freshness checks use the standard `staleTime`. -- By default, `gcTime` and `preloadGcTime` define **5-minute** retention windows. Once unused data is older than its applicable window, it is eligible for pruning during a later cache reconciliation. The two windows can be configured independently. +- By default, the `staleTime` is set to `0`, meaning that the route's data is immediately considered stale. Stale matches are reloaded in the background when the route is entered again, when its loader key changes (path params used by the route or `loaderDeps`), or when `router.load()` is called explicitly. +- By default, a previously preloaded route is considered fresh for **30 seconds**. This means if a route is preloaded, then preloaded again within 30 seconds, the second preload will be ignored. This prevents unnecessary preloads from happening too frequently. **When a route is loaded normally, the standard `staleTime` is used.** +- By default, the `gcTime` is set to **30 minutes**, meaning that any route data that has not been accessed in 30 minutes will be garbage collected and removed from the cache. - By default, `staleReloadMode` is `'background'`, so stale successful matches keep rendering with their existing `loaderData` while the loader revalidates in the background. -- `router.invalidate()` selects matching committed, cached, and in-flight loader generations for invalidation and retires matching active preload lanes. Current active routes reload through the normal loading protocol; cached inactive data remains marked stale and reloads when it is reused. By default, stale successful loader data revalidates in the background unless `sync: true` is requested. +- `router.invalidate()` will force all active routes to reload their loaders immediately and mark every cached route's data as stale. ### Using `loaderDeps` to access search params @@ -180,11 +180,6 @@ Imagine a `/posts` route supports some pagination via search params `offset` and Once we have these deps in place, the route will always reload when the deps change. -`loaderDeps` defines a cache key during route planning. For the same validated -search input it must return the same value without navigating or mutating state. -The returned value and custom serialization methods such as `toJSON` must also -be side-effect-free. - ```tsx // /routes/posts.tsx export const Route = createFileRoute('/posts')({ @@ -221,13 +216,7 @@ export const Route = createFileRoute('/posts')({ ### Using `staleTime` to control how long data is considered fresh -By default, `staleTime` for accepted navigation data is `0`ms, while -`preloadStaleTime` is 30 seconds. A successful preload can therefore provide -loader data to the first navigation during that interval. Once navigation -accepts that loader generation, normal navigation freshness applies. With the -default `staleTime`, the data is immediately stale for a later use of the same -loader key and revalidates in the background while cached data remains visible. -A different loader key identifies a separate cache entry. +By default, `staleTime` for navigations is set to `0`ms (and 30 seconds for preloads) which means that the route's data will always be considered stale. When a stale route is entered again, its loader key changes, or `router.load()` is called explicitly, the route will reload in the background. **This is a good default for most use cases, but you may find that some route data is more static or potentially expensive to load.** In these cases, you can use the `staleTime` option to control how long the route's data is considered fresh for navigations. Let's take a look at an example: @@ -313,16 +302,9 @@ export const Route = createFileRoute('/posts')({ ### Opting out of caching while still preloading -Even though you may opt out of retaining ordinary route data, you can still get -the benefits of preloading. Preloaded results use `preloadGcTime` for retention -and `preloadStaleTime` for freshness, so the default settings keep a recent -preload in memory and let the first navigation reuse it without another loader -call. +Even though you may opt-out of short-term caching for your route data, you can still get the benefits of preloading! With the above configuration, preloading will still "just work" with the default `preloadGcTime`. This means that if a route is preloaded, then navigated to, the route's data will be considered fresh and will not be reloaded. -Use `routerOptions.defaultPreload` to control automatic link preloading. Setting -`routeOptions.preload` to `false` has a narrower effect: a speculative lane -still runs that route's `beforeLoad`, but skips its `loader`. Navigation runs -both normally. +To opt out of preloading, don't turn it on via the `routerOptions.defaultPreload` or `routeOptions.preload` options. ## Passing all loader events to an external cache @@ -335,11 +317,7 @@ const router = createRouter({ }) ``` -This makes settled preload data immediately stale in the Router, allowing your -external cache to decide whether to fetch. Retention still follows -`preloadGcTime`, and overlapping preload or navigation consumers can still -share in-flight loader work. A route's `shouldReload` option can also suppress -a loader call. +This will ensure that every preload, load, and reload event will trigger your `loader` functions, which can then be handled and deduped by your external cache. ## Using Router Context @@ -494,7 +472,7 @@ export const Route = createFileRoute('/posts')({ ## Using the Abort Signal -The `abortController` property of the `loader` function is an [AbortController](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) for that loader invocation. A preload and navigation can share an in-flight invocation, so its signal remains active while any consumer still needs the work. The signal is cancelled after the invocation becomes outdated and has no remaining consumers. Here is an example using it with a fetch call: +The `abortController` property of the `loader` function is an [AbortController](https://developer.mozilla.org/en-US/docs/Web/API/AbortController). Its signal is cancelled when the route is unloaded or when the `loader` call becomes outdated. This is useful for cancelling network requests when the route is unloaded or when the route's params change. Here is an example using it with a fetch call: ```tsx // src/routes/posts.tsx @@ -570,7 +548,7 @@ The `routeOptions.onCatch` option is a function that is called whenever an error ```tsx // src/routes/posts.tsx export const Route = createFileRoute('/posts')({ - onCatch: (error) => { + onCatch: ({ error, errorInfo }) => { // Log the error console.error(error) }, @@ -581,20 +559,16 @@ export const Route = createFileRoute('/posts')({ The `routeOptions.errorComponent` option is a component that is rendered when an error occurs during the route loading or rendering lifecycle. It is rendered with the following props: -- `error` - The caught value (`unknown` in React and Vue; `Error` in Solid) +- `error` - The error that occurred - `reset` - A function to reset the internal `CatchBoundary` -`ErrorComponentProps` defaults its `error` property to `unknown` in React and Vue, where you must narrow the value before accessing properties such as `message`. In Solid, it defaults to `Error`. `ErrorComponentProps` can describe an error after you have narrowed it; it does not restrict what a route can throw. This applies to boundary components and `onCatch` callbacks, including `defaultOnCatch`; it does not change the `onError` callback. - -React and Vue boundaries pass through the caught value, including falsy values. Solid wraps non-`Error` throws in an `Error` whose `cause` contains the original value. This also applies to Solid error components rendered during SSR: existing `Error` instances are preserved, strings become the error message, and other values use the message `Unknown error`. Router state and loader `onError` callbacks retain the original value. - ```tsx // src/routes/posts.tsx export const Route = createFileRoute('/posts')({ loader: () => fetchPosts(), errorComponent: ({ error }) => { // Render an error message - return
{error instanceof Error ? error.message : String(error)}
+ return
{error.message}
}, }) ``` @@ -608,7 +582,7 @@ export const Route = createFileRoute('/posts')({ errorComponent: ({ error, reset }) => { return (
- {error instanceof Error ? error.message : String(error)} + {error.message} - ) -} -``` - --- Phew! That's a lot of navigating! That said, hopefully you're feeling pretty good about getting around your application now. Let's move on! diff --git a/docs/router/guide/not-found-errors.md b/docs/router/guide/not-found-errors.md index 88b8767a00..adba054b74 100644 --- a/docs/router/guide/not-found-errors.md +++ b/docs/router/guide/not-found-errors.md @@ -10,13 +10,13 @@ There are 2 uses for not-found errors in TanStack Router: - **Non-matching route paths**: When a path does not match any known route matching pattern **OR** when it partially matches a route, but with extra path segments - The **router** will automatically throw a not-found error when a path does not match any known route matching pattern - - If the router's `notFoundMode` is set to `fuzzy`, the nearest matching route with a `notFoundComponent` will handle the error. If the router's `notFoundMode` is set to `root`, the root route will handle the error. + - If the router's `notFoundMode` is set to `fuzzy`, the nearest parent route with a `notFoundComponent` will handle the error. If the router's `notFoundMode` is set to `root`, the root route will handle the error. - Examples: - Attempting to access `/users` when there is no `/users` route - Attempting to access `/posts/1/edit` when the route tree only handles `/posts/$postId` - **Missing resources**: When a resource cannot be found, such as a post with a given ID or any asynchronous data that is not available or does not exist - **You, the developer** must throw a not-found error when a resource cannot be found. This can be done in the `beforeLoad` or `loader` functions using the `notFound` utility. - - Will be handled by the nearest matching route with a `notFoundComponent` (when `notFound` is called within `loader`) or the root route. + - Will be handled by the nearest parent route with a `notFoundComponent` (when `notFound` is called within `loader`) or the root route. - Examples: - Attempting to access `/posts/1` when the post with ID 1 does not exist - Attempting to access `/docs/path/to/document` when the document does not exist @@ -27,19 +27,20 @@ Under the hood, both of these cases are implemented using the same `notFound` fu When TanStack Router encounters a **pathname** that doesn't match any known route pattern **OR** partially matches a route pattern but with extra trailing pathname segments, it will automatically throw a not-found error. -Depending on the `notFoundMode` option, the router will handle these automatic errors differently: +Depending on the `notFoundMode` option, the router will handle these automatic errors differently:: - ["fuzzy" mode](#notfoundmode-fuzzy) (default): The router will intelligently find the closest matching suitable route and display the `notFoundComponent`. - ["root" mode](#notfoundmode-root): All not-found errors will be handled by the root route's `notFoundComponent`, regardless of the nearest matching route. ### `notFoundMode: 'fuzzy'` -By default, the router's `notFoundMode` is set to `fuzzy`, which indicates that if a pathname doesn't match any known route, the router will attempt to use the closest matching route with a configured `notFoundComponent`. +By default, the router's `notFoundMode` is set to `fuzzy`, which indicates that if a pathname doesn't match any known route, the router will attempt to use the closest matching route with children/(an outlet) and a configured not found component. > **❓ Why is this the default?** Fuzzy matching to preserve as much parent layout as possible for the user gives them more context to navigate to a useful location based on where they thought they would arrive. The nearest suitable route is found using the following criteria: +- The route must have children and therefore an `Outlet` to render the `notFoundComponent` - The route must have a `notFoundComponent` configured or the router must have a `defaultNotFoundComponent` configured For example, consider the following route tree: @@ -52,10 +53,9 @@ If provided the path of `/posts/1/edit`, the following component structure will - `` - `` - - `` - - `` + - `` -The `notFoundComponent` of the `$postId` route will be rendered because it is the **nearest matching route with a `notFoundComponent` configured**. +The `notFoundComponent` of the `posts` route will be rendered because it is the **nearest suitable parent route with children (and therefore an outlet) and a `notFoundComponent` configured**. ### `notFoundMode: 'root'` diff --git a/docs/router/guide/path-params.md b/docs/router/guide/path-params.md index d326eabb4b..a4b22ddeca 100644 --- a/docs/router/guide/path-params.md +++ b/docs/router/guide/path-params.md @@ -131,32 +131,6 @@ function PostComponent() { -## Prioritizing Parsed Path Param Routes - -When multiple dynamic, optional, or wildcard routes can match the same URL, routes with `params.parse` are tried before equivalent routes without it. If multiple matching candidates use `params.parse`, you can use `params.priority` to control which candidate is tried first. - -Higher `params.priority` values are tried first. The default priority is `0`, and if a higher-priority route's `params.parse` returns `false`, matching continues to the next candidate route. - -`params.parse` runs during route planning and may be evaluated more than once. -It must be deterministic and side-effect-free for the same raw params. - -```tsx title="src/routes/posts.$postId.tsx" -export const Route = createFileRoute('/posts/$postId')({ - params: { - priority: 10, - parse: ({ postId }) => { - if (!/^\d+$/.test(postId)) return false - return { postId: Number(postId) } - }, - stringify: ({ postId }) => ({ postId: String(postId) }), - }, -}) -``` - -With a fallback `/posts/$slug` route, `/posts/123` can match the parsed numeric route first, while `/posts/hello-world` can fall through to the slug route when `params.parse` returns `false`. - -`params.priority` only affects competing candidates that use `params.parse`. It does not override normal route specificity, so static routes still match before dynamic, optional, or wildcard routes. - ## Navigating with Path Params When navigating to a route with path params, TypeScript will require you to pass the params either as an object or as a function that returns an object of params. @@ -229,7 +203,7 @@ function PostComponent() { -You can even combine prefixes with wildcard routes to create more complex patterns: +You can even combines prefixes with wildcard routes to create more complex patterns: @@ -343,7 +317,7 @@ You can combine both prefixes and suffixes to create very specific routing patte # React -```tsx title="src/routes/users/user-{$userId}[.]json.tsx" +```tsx title="src/routes/users/user-{$userId}.json" export const Route = createFileRoute('/users/user-{$userId}.json')({ component: UserComponent, }) @@ -357,7 +331,7 @@ function UserComponent() { # Solid -```tsx title="src/routes/users/user-{$userId}[.]json.tsx" +```tsx title="src/routes/users/user-{$userId}.json" export const Route = createFileRoute('/users/user-{$userId}.json')({ component: UserComponent, }) @@ -481,7 +455,7 @@ Optional parameters support prefix and suffix patterns: # React -```tsx title="src/routes/files/prefix{-$name}[.]txt.tsx" +```tsx title="src/routes/files/prefix{-$name}.txt" // Route: /files/prefix{-$name}.txt // Matches: /files/prefix.txt and /files/prefixdocument.txt export const Route = createFileRoute('/files/prefix{-$name}.txt')({ @@ -496,7 +470,7 @@ function FileComponent() { # Solid -```tsx title="src/routes/files/prefix{-$name}[.]txt.tsx" +```tsx title="src/routes/files/prefix{-$name}.txt" // Route: /files/prefix{-$name}.txt // Matches: /files/prefix.txt and /files/prefixdocument.txt export const Route = createFileRoute('/files/prefix{-$name}.txt')({ @@ -585,10 +559,10 @@ Optional parameters can be combined with wildcards for complex routing patterns: # React -```tsx title="src/routes/docs/v{-$version}/$.tsx" -// Route: /docs/v{-$version}/$ +```tsx title="src/routes/docs/{-$version}/$.tsx" +// Route: /docs/{-$version}/$ // Matches: /docs/extra/path, /docs/v2/extra/path -export const Route = createFileRoute('/docs/v{-$version}/$')({ +export const Route = createFileRoute('/docs/{-$version}/$')({ component: DocsComponent, }) @@ -598,7 +572,7 @@ function DocsComponent() { return (
- Version: {version ? `v${version}` : 'latest'} + Version: {version || 'latest'} Path: {_splat}
) @@ -607,10 +581,10 @@ function DocsComponent() { # Solid -```tsx title="src/routes/docs/v{-$version}/$.tsx" -// Route: /docs/v{-$version}/$ +```tsx title="src/routes/docs/{-$version}/$.tsx" +// Route: /docs/{-$version}/$ // Matches: /docs/extra/path, /docs/v2/extra/path -export const Route = createFileRoute('/docs/v{-$version}/$')({ +export const Route = createFileRoute('/docs/{-$version}/$')({ component: DocsComponent, }) @@ -619,7 +593,7 @@ function DocsComponent() { return (
- Version: {params().version ? `v${params().version}` : 'latest'} + Version: {params().version || 'latest'} Path: {params()._splat}
) @@ -1395,8 +1369,6 @@ const router = createRouter({ }) ``` -This setting is fixed when the router is created. To use different allowed characters, create a new router instance. - The following is the list of accepted allowed characters: - `;` diff --git a/docs/router/guide/preloading.md b/docs/router/guide/preloading.md index 7f48412ce6..453294ab6e 100644 --- a/docs/router/guide/preloading.md +++ b/docs/router/guide/preloading.md @@ -18,17 +18,10 @@ Preloading in TanStack Router is a way to load a route before the user actually ## How long does preloaded data stay in memory? -Successful preloaded loader results can enter the router's in-memory cache with -two independent policies: +Preloaded route matches are temporarily cached in memory with a few important caveats: -- **Freshness defaults to 30 seconds.** Configure it with - `defaultPreloadStaleTime` or a route's `preloadStaleTime`. -- **The unused retention window defaults to 5 minutes.** Configure it with - `defaultPreloadGcTime` or a route's `preloadGcTime`. Older unused entries - are eligible for pruning during a later cache reconciliation. -- **The speculative lane is never promoted into router state.** Navigation - creates its own presentation and runs its own `beforeLoad` chain. It can reuse - cached loader data or join a loader that is still in flight. +- **Unused preloaded data is removed after 30 seconds by default.** This can be configured by setting the `defaultPreloadMaxAge` option on your router. +- **Obviously, when a route is loaded, its preloaded version is promoted to the router's normal pending matches state.** If you need more control over preloading, caching and/or garbage collection of preloaded data, you should use an external caching library like [TanStack Query](https://tanstack.com/query). @@ -64,7 +57,7 @@ This will turn on `intent` preloading by default for all `` components in ## Preload Delay -By default, intent focus/hover and viewport preloading start after **50ms**. Pending preloads are cancelled if focus or hover ends, or the link leaves the viewport. Touch intent preloads immediately. You can change this delay by setting the `defaultPreloadDelay` option on your router: +By default, preloading will start after **50ms** of the user hovering or touching a `` component. You can change this delay by setting the `defaultPreloadDelay` option on your router: @@ -94,16 +87,9 @@ const router = createRouter({ You can also set the `preloadDelay` prop on individual `` components to override the default behavior on a per-link basis. -## Built-in Preloading, Freshness, and Retention +## Built-in Preloading & `preloadStaleTime` -If you're using the built-in loaders, you can control how long preloaded data is considered fresh by setting either `routerOptions.defaultPreloadStaleTime` or `routeOptions.preloadStaleTime` to a number of milliseconds. **By default, preloaded data is considered fresh for 30 seconds.** - -Freshness and retention are separate. `preloadStaleTime` controls whether the -retained loader result can be reused without another loader call. -`preloadGcTime` (or `defaultPreloadGcTime`) controls when an unused preload -result becomes eligible for pruning during a later cache reconciliation; it -does not schedule a timer to evict the result at that exact moment. Both preload -GC options default to 5 minutes. +If you're using the built-in loaders, you can control how long preloaded data is considered fresh until another preload is triggered by setting either `routerOptions.defaultPreloadStaleTime` or `routeOptions.preloadStaleTime` to a number of milliseconds. **By default, preloaded data is considered fresh for 30 seconds.**. To change this, you can set the `defaultPreloadStaleTime` option on your router: @@ -139,34 +125,16 @@ Or, you can use the `routeOptions.preloadStaleTime` option on individual routes: // src/routes/posts.$postId.tsx export const Route = createFileRoute('/posts/$postId')({ loader: async ({ params }) => fetchPost(params.postId), - // Reload preloaded data when it is more than 10 seconds old + // Preload the route again if the preload cache is older than 10 seconds preloadStaleTime: 10_000, }) ``` -Client-side preloading runs each route's `beforeLoad` with `preload: true`. -Every later preload or navigation runs its own `beforeLoad` chain, so a -navigation observes `preload: false` even when an identical preload is still -active. A later lane can reuse successful settled loader data or join loader -work that is still in flight, but it never reuses `beforeLoad` context or an -already-settled redirect, error, or not-found result. If joined loader work -later produces a terminal outcome, all current consumers of that flight observe -it. The `shouldReload` option remains loader-only. - -If a route has `preload: false`, its speculative lane still runs `beforeLoad`, -but skips that route's loader. Navigation runs `beforeLoad` again and performs -the skipped loader work. - ## Preloading with External Libraries When integrating external caching libraries like React Query, which have their own mechanisms for determining stale data, you may want to override the default preloading and stale-while-revalidate logic of TanStack Router. These libraries often use options like staleTime to control the freshness of data. -To let an external cache make the freshness decision, set -`routerOptions.defaultPreloadStaleTime` or `routeOptions.preloadStaleTime` to -`0`. Settled preload data then becomes immediately stale in the Router, while -retention still follows `preloadGcTime`. Overlapping preload or navigation -consumers can still share in-flight loader work, and `shouldReload` can still -suppress a loader call. +To customize the preloading behavior in TanStack Router and fully leverage your external library's caching strategy, you can bypass the built-in caching by setting routerOptions.defaultPreloadStaleTime or routeOptions.preloadStaleTime to 0. This ensures that all preloads are marked as stale internally, and loaders are always invoked, allowing your external library, such as React Query, to manage data loading and caching. For example: @@ -200,38 +168,25 @@ This would then allow you, for instance, to use an option like React Query's `st ## Preloading Manually -If you need to manually preload a route, use the router's `preloadRoute` method. -It accepts a standard TanStack `NavigateOptions` object and returns the -speculative match lane. An ordinary error or not-found thrown while loading is -represented in that returned lane; cancellation or control flow that produces -no reusable lane can return `undefined`. +If you need to manually preload a route, you can use the router's `preloadRoute` method. It accepts a standard TanStack `NavigateOptions` object and returns a promise that resolves when the route is preloaded. # React ```tsx -import { isNotFound } from '@tanstack/react-router' - function Component() { const router = useRouter() useEffect(() => { async function preload() { - const matches = await router.preloadRoute({ - to: postRoute, - params: { id: 1 }, - }) - - const routeFailure = matches?.find( - (match) => - match.status === 'error' || - match.status === 'notFound' || - isNotFound(match.error), - ) - - if (routeFailure) { - // Inspect routeFailure.error + try { + const matches = await router.preloadRoute({ + to: postRoute, + params: { id: 1 }, + }) + } catch (err) { + // Failed to preload route } } @@ -245,27 +200,18 @@ function Component() { # Solid ```tsx -import { isNotFound } from '@tanstack/solid-router' - function Component() { const router = useRouter() createEffect(() => { async function preload() { - const matches = await router.preloadRoute({ - to: postRoute, - params: { id: 1 }, - }) - - const routeFailure = matches?.find( - (match) => - match.status === 'error' || - match.status === 'notFound' || - isNotFound(match.error), - ) - - if (routeFailure) { - // Inspect routeFailure.error + try { + const matches = await router.preloadRoute({ + to: postRoute, + params: { id: 1 }, + }) + } catch (err) { + // Failed to preload route } } diff --git a/docs/router/guide/router-context.md b/docs/router/guide/router-context.md index 347082106f..5fc4001010 100644 --- a/docs/router/guide/router-context.md +++ b/docs/router/guide/router-context.md @@ -278,10 +278,9 @@ Then, in your route: export const Route = createFileRoute('/todos')({ component: Todos, loader: async ({ context }) => { - await context.queryClient.query({ + await context.queryClient.ensureQueryData({ queryKey: ['todos', { userId: user.id }], queryFn: fetchTodos, - staleTime: 'static', }) }, }) diff --git a/docs/router/guide/router-events.md b/docs/router/guide/router-events.md deleted file mode 100644 index ca798a9676..0000000000 --- a/docs/router/guide/router-events.md +++ /dev/null @@ -1,129 +0,0 @@ ---- -title: Router Events ---- - -TanStack Router exposes router lifecycle events through `router.subscribe`. This is useful for imperative side effects like analytics, resetting external state, or running DOM-dependent logic after navigation. - -## Basic usage - -`router.subscribe` takes an event name and a listener, then returns an unsubscribe function: - -```tsx -const unsubscribe = router.subscribe('onResolved', (event) => { - console.info('Navigation finished:', event.toLocation.href) -}) - -// Later, clean up the listener -unsubscribe() -``` - -## When to use it - -`router.subscribe` is best for imperative integrations that need to observe navigation without driving rendering: - -- Analytics and pageview tracking -- Resetting external caches or mutation state -- Logging navigation timing and transitions -- Running DOM-dependent logic after routes render - -If you need reactive UI updates, prefer framework hooks like `useRouterState`, `useSearch`, and `useParams` instead of subscribing manually. - -## Available events - -TanStack Router emits these lifecycle events: - -- `onBeforeNavigate` - right before a navigation begins -- `onBeforeLoad` - before route loading starts -- `onLoad` - after the next location has committed and route matches have loaded -- `onBeforeRouteMount` - after loading finishes, just before route components mount -- `onResolved` - after the navigation has fully resolved -- `onRendered` - after the route has rendered - -For the full event payload types, see the [`RouterEvents` type](../api/router/RouterEventsType.md). - -## Typical event flow - -For a normal navigation, the events usually flow like this: - -1. `onBeforeNavigate` -2. `onBeforeLoad` -3. `onLoad` -4. `onBeforeRouteMount` -5. `onResolved` -6. `onRendered` - -You usually do not need every event. A good rule of thumb is: - -- Use `onBeforeNavigate` or `onBeforeLoad` to observe navigation start -- Use `onResolved` for analytics and cleanup after navigation finishes -- Use `onRendered` for DOM-dependent work - -## Event payload - -Navigation events receive location change metadata describing what changed: - -```tsx -const unsubscribe = router.subscribe('onBeforeNavigate', (event) => { - console.info({ - from: event.fromLocation?.href, - to: event.toLocation.href, - pathChanged: event.pathChanged, - hrefChanged: event.hrefChanged, - hashChanged: event.hashChanged, - }) -}) -``` - -A few useful details: - -- `fromLocation` can be `undefined` on the initial load -- `pathChanged` tells you whether the pathname changed -- `hrefChanged` includes pathname, search, and hash changes -- `hashChanged` is useful for distinguishing hash-only navigations - -## Common patterns - -### Track pageviews - -`onResolved` is a good default for analytics because it fires after navigation finishes: - -```tsx -const unsubscribe = router.subscribe('onResolved', ({ toLocation }) => { - analytics.track('page_view', { - path: toLocation.pathname, - href: toLocation.href, - }) -}) -``` - -### Clear external mutation state - -If you use a mutation library without keyed mutation state, clear it after navigation: - -```tsx -const unsubscribe = router.subscribe('onResolved', ({ pathChanged }) => { - if (pathChanged) { - mutationCache.clear() - } -}) -``` - -### Run DOM-dependent logic - -Use `onRendered` when your side effect depends on the new route content already being in the DOM: - -```tsx -const unsubscribe = router.subscribe('onRendered', ({ toLocation }) => { - focusPageHeading(toLocation.pathname) -}) -``` - -## Unsubscribing in components - -If you subscribe from a component or framework effect, always return the unsubscribe function from your cleanup so the listener is removed when the component unmounts. - -## Related APIs - -- [`Router` type](../api/router/RouterType.md) -- [`RouterEvents` type](../api/router/RouterEventsType.md) -- [Data Mutations](./data-mutations.md) diff --git a/docs/router/guide/ssr.md b/docs/router/guide/ssr.md index 46a0941e7c..6cb98766d1 100644 --- a/docs/router/guide/ssr.md +++ b/docs/router/guide/ssr.md @@ -8,8 +8,6 @@ title: SSR Server Side Rendering (SSR) is the process of rendering a component on the server and sending the HTML markup to the client. The client then hydrates the markup into a fully interactive component. -> **TanStack Router is not Next.js, Remix, or React Router DOM.** When generating routes or components, do **not** use `src/pages/`, `app/layout.tsx`, `_app/index.tsx`, `getServerSideProps`, `getStaticProps`, Remix-style `loader`/`action` exports, or imports from `react-router-dom` or `next/`. TanStack uses `src/routes/` with `createFileRoute`, `Link`/`useNavigate`/`redirect` from `@tanstack/react-router`, and (for Start) `createServerFn` from `@tanstack/-start`. Wrong-framework code typically fails to build or produces conflicting `/` routes at runtime. - There are usually two different flavors of SSR to be considered: - Non-streaming SSR @@ -60,9 +58,7 @@ To implement non-streaming SSR with TanStack Router, you will need the following ### Automatic Server History -On the client, Router defaults to using an instance of `createBrowserHistory`. On the server, the Router SSR request handler and TanStack Start automatically create a lightweight history containing only the request URL. This history does not keep a navigation stack or respond to `push`, `replace`, `go`, `back`, or `forward` calls. - -Server-side calls to `router.navigate()` and `router.commitLocation()` are also no-ops: their promises resolve without changing the request location or running another load. To redirect a request, use the dedicated [redirect API](../api/router/redirectFunction.md), such as `throw redirect({ to: '/login' })` in `beforeLoad` or a loader. +On the client, Router defaults to using an instance of `createBrowserHistory`, which is the preferred type of history to use on the client. On the server, however, you will want to use an instance of `createMemoryHistory` instead. This is because `createBrowserHistory` uses the `window` object, which does not exist on the server. This is handled automatically for you in the RouterServer component. ### Automatic Loader Dehydration/Hydration @@ -158,8 +154,6 @@ export async function render({ request }: { request: Request }) { using `renderRouterToString` -React and Solid use their native synchronous string renderers. Suspended components render their Suspense fallback without waiting for the component to resolve. The router still finishes serializing hydration data before returning the response. Use `renderRouterToStream` when you need the server to render suspended content after it resolves. - # React @@ -240,7 +234,7 @@ hydrateRoot(document, ) # Solid ```tsx title="src/entry-client.tsx" -import { hydrate } from 'solid-js/web' +import { hydrate } from '@solidjs/web' import { RouterClient } from '@tanstack/solid-router/ssr/client' import { createRouter } from './router' @@ -262,9 +256,6 @@ This pattern can be useful for pages that have slow or high-latency data fetchin > [!NOTE] > This streaming pattern is all automatic as long as you are using either `defaultStreamHandler` or `renderRouterToStream`. -> [!IMPORTANT] -> Render [``](./document-head-management.md#scripts) inside `` of your root route. It emits the route scripts and marks where the router inserts streamed hydration data. Without it the response still completes, but the page cannot hydrate. - using `defaultStreamHandler` diff --git a/docs/router/guide/type-safety.md b/docs/router/guide/type-safety.md index 3faaed79e7..2adffc58c5 100644 --- a/docs/router/guide/type-safety.md +++ b/docs/router/guide/type-safety.md @@ -137,13 +137,12 @@ As your application scales, TypeScript check times will naturally increase. Ther ### Only infer types you need -A great pattern with client side data caches (TanStack Query, etc.) is to prefetch data. For example with TanStack Query you might have a route which calls `queryClient.query` in a `loader`. +A great pattern with client side data caches (TanStack Query, etc.) is to prefetch data. For example with TanStack Query you might have a route which calls `queryClient.ensureQueryData` in a `loader`. ```tsx export const Route = createFileRoute('/posts/$postId/deep')({ - // (ctx: LoaderFnContext) => Promise loader: ({ context: { queryClient }, params: { postId } }) => - queryClient.query({ ...postQueryOptions(postId), staleTime: 'static' }), + queryClient.ensureQueryData(postQueryOptions(postId)), component: PostDeepComponent, }) @@ -155,16 +154,12 @@ function PostDeepComponent() { } ``` -This may look fine and for small route trees and you may not notice any TS performance issues. However in this case TS has to infer the loader's return type, despite it never being used in your route. If the loader data is a complex type with many routes that prefetch in this manner, it can slow down editor performance. In this case, the change is quite simple and let typescript infer `Promise`. +This may look fine and for small route trees and you may not notice any TS performance issues. However in this case TS has to infer the loader's return type, despite it never being used in your route. If the loader data is a complex type with many routes that prefetch in this manner, it can slow down editor performance. In this case, the change is quite simple and let typescript infer Promise. ```tsx export const Route = createFileRoute('/posts/$postId/deep')({ - // (ctx: LoaderFnContext) => Promise loader: async ({ context: { queryClient }, params: { postId } }) => { - await queryClient.query({ - ...postQueryOptions(postId), - staleTime: 'static', - }) + await queryClient.ensureQueryData(postQueryOptions(postId)) }, component: PostDeepComponent, }) diff --git a/docs/router/guide/url-rewrites.md b/docs/router/guide/url-rewrites.md index e780e01781..7bc3df8545 100644 --- a/docs/router/guide/url-rewrites.md +++ b/docs/router/guide/url-rewrites.md @@ -343,8 +343,6 @@ const navigate = useNavigate() navigate({ to: '/about' }) ``` -When the final output URL has a different origin, programmatic navigation performs a full page load automatically. You do not need to set `reloadDocument: true` for cross-origin rewrites. If a route mask is applied, its output URL determines whether navigation stays on the current origin. - ### Hard Links for Cross-Origin Rewrites When an output rewrite changes the origin (hostname), the `` component automatically renders a standard anchor tag instead of using client-side navigation: diff --git a/docs/router/how-to/arrays-objects-dates-search-params.md b/docs/router/how-to/arrays-objects-dates-search-params.md index 4efbdab30f..3c0613434e 100644 --- a/docs/router/how-to/arrays-objects-dates-search-params.md +++ b/docs/router/how-to/arrays-objects-dates-search-params.md @@ -165,7 +165,7 @@ const dashboardSchema = z.object({ columns: z.number().min(1).max(6).default(3), showDetails: z.boolean().default(false), }) - .prefault({}), + .default({}), filters: z .object({ @@ -176,9 +176,9 @@ const dashboardSchema = z.object({ before: z.string().optional(), }) .optional(), - metadata: z.record(z.string(), z.string()).optional(), // Dynamic object keys + metadata: z.record(z.string()).optional(), // Dynamic object keys }) - .prefault({}), + .default({}), }) export const Route = createFileRoute('/dashboard')({ @@ -459,7 +459,7 @@ const analyticsSchema = z.object({ gap: z.number().default(16), responsive: z.boolean().default(true), }) - .prefault({}), + .default({}), timeRange: z .object({ @@ -471,9 +471,9 @@ const analyticsSchema = z.object({ }) .optional(), }) - .prefault({}), + .default({}), }) - .prefault({}), + .default({}), }) export const Route = createFileRoute('/analytics')({ diff --git a/docs/router/how-to/debug-router-issues.md b/docs/router/how-to/debug-router-issues.md index 27dadd361f..b4d20ec72f 100644 --- a/docs/router/how-to/debug-router-issues.md +++ b/docs/router/how-to/debug-router-issues.md @@ -322,16 +322,11 @@ const route = createRoute({ ```tsx function DataLoadingDebug() { - const state = useRouterState() + const location = useLocation() console.log('Route status:', { - status: state.status, - isLoading: state.isLoading, - matches: state.matches.map((match) => ({ - routeId: match.routeId, - status: match.status, - isFetching: match.isFetching, - })), + isLoading: location.isLoading, + isTransitioning: location.isTransitioning, }) return null diff --git a/docs/router/how-to/setup-basic-search-params.md b/docs/router/how-to/setup-basic-search-params.md index e85579f5f4..27e49f7584 100644 --- a/docs/router/how-to/setup-basic-search-params.md +++ b/docs/router/how-to/setup-basic-search-params.md @@ -13,9 +13,9 @@ import { createFileRoute } from '@tanstack/react-router' import { z } from 'zod' const productSearchSchema = z.object({ - page: z.number().default(1).catch(1), - category: z.string().default('all').catch('all'), - showSale: z.boolean().default(false).catch(false), + page: fallback(z.number(), 1).default(1), + category: fallback(z.string(), 'all').default('all'), + showSale: fallback(z.boolean(), false).default(false), }) export const Route = createFileRoute('/products')({ @@ -100,6 +100,7 @@ Start by identifying what search parameters your route needs: ```tsx import { z } from 'zod' +import { fallback } from '@tanstack/zod-adapter' const shopSearchSchema = z.object({ // Pagination @@ -237,7 +238,7 @@ const dashboardSchema = z.object({ status: z.enum(['active', 'inactive']).optional(), type: z.string().optional(), }) - .prefault({}), + .default({}), }) ``` @@ -332,7 +333,7 @@ export const Route = createFileRoute('/example')({ ### Problem: Search Parameters Cause TypeScript Errors -**Cause:** Missing or incorrect schema definition. +**Cause:** Missing or incorrect schema definition with Zod v3. **Solution:** Ensure your schema covers all search parameters and use proper types: @@ -344,12 +345,12 @@ export const Route = createFileRoute('/page')({ // ✅ Complete schema with proper validation const searchSchema = z.object({ - page: z.number().default(1).catch(1), - category: z.string().default('all').catch('all'), + page: fallback(z.number(), 1).default(1), + category: fallback(z.string(), 'all').default('all'), }) export const Route = createFileRoute('/page')({ - validateSearch: searchSchema, + validateSearch: zodValidator(searchSchema), component: MyPage, }) ``` @@ -381,7 +382,7 @@ const schema = z.object({ ```tsx const schema = z.object({ // Required with default (navigation can omit, but always present in component) - page: z.number().default(1).catch(1), + page: fallback(z.number(), 1).default(1), // Truly optional (can be undefined in component) searchTerm: z.string().optional(), @@ -396,8 +397,8 @@ const schema = z.object({ ```tsx const schema = z.object({ - filters: z - .object({ + filters: fallback( + z.object({ status: z.enum(['active', 'inactive']).optional(), tags: z.string().array().optional(), dateRange: z @@ -406,9 +407,9 @@ const schema = z.object({ end: z.string().pipe(z.coerce.date()), }) .optional(), - }) - .prefault({}) - .catch({}), + }), + {}, + ).default({}), }) ``` diff --git a/docs/router/how-to/setup-testing.md b/docs/router/how-to/setup-testing.md index 104cbedc0d..72f40032cf 100644 --- a/docs/router/how-to/setup-testing.md +++ b/docs/router/how-to/setup-testing.md @@ -224,12 +224,8 @@ export function LoadingComponent() { return
Loading...
} -export function ErrorComponent({ error }: { error: unknown }) { - return ( -
- Error: {error instanceof Error ? error.message : String(error)} -
- ) +export function ErrorComponent({ error }: { error: Error }) { + return
Error: {error.message}
} ``` @@ -590,12 +586,8 @@ describe('Code-Based Route Data Loading', () => { return
{user.name}
} - function ErrorComponent({ error }: { error: unknown }) { - return ( -
- Error: {error instanceof Error ? error.message : String(error)} -
- ) + function ErrorComponent({ error }: { error: Error }) { + return
Error: {error.message}
} const userRoute = createRoute({ @@ -659,10 +651,9 @@ describe('React Query Integration', () => { path: '/posts', component: PostsList, loader: ({ context: { queryClient } }) => - queryClient.query({ + queryClient.ensureQueryData({ queryKey: ['posts'], queryFn: mockFetchPosts, - staleTime: 'static', }), }) diff --git a/docs/router/how-to/share-search-params-across-routes.md b/docs/router/how-to/share-search-params-across-routes.md index 23a202b176..e1e24c1e0d 100644 --- a/docs/router/how-to/share-search-params-across-routes.md +++ b/docs/router/how-to/share-search-params-across-routes.md @@ -2,6 +2,8 @@ title: Share Search Parameters Across Routes --- +# How to Share Search Parameters Across Routes + Search parameters automatically inherit from parent routes in TanStack Router. When a parent route validates search parameters, child routes can access them via `Route.useSearch()` alongside their own parameters. ## How Parameter Inheritance Works diff --git a/docs/router/how-to/use-environment-variables.md b/docs/router/how-to/use-environment-variables.md index 4f6a764f28..2d35308158 100644 --- a/docs/router/how-to/use-environment-variables.md +++ b/docs/router/how-to/use-environment-variables.md @@ -164,7 +164,7 @@ const fetchPosts = async () => { export const Route = createFileRoute('/posts/')({ loader: fetchPosts, errorComponent: ({ error }) => ( -
Error loading posts: {error instanceof Error ? error.message : String(error)}
+
Error loading posts: {error.message}
), }) ``` diff --git a/docs/router/how-to/validate-search-params.md b/docs/router/how-to/validate-search-params.md index 15d3f9d6c8..5abd435cef 100644 --- a/docs/router/how-to/validate-search-params.md +++ b/docs/router/how-to/validate-search-params.md @@ -36,7 +36,7 @@ export const Route = createFileRoute('/products')({ return (

Invalid Search Parameters

-

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

+

{error.message}

diff --git a/docs/router/installation/manual.md b/docs/router/installation/manual.md index ab89060ef1..e2cfcabcf3 100644 --- a/docs/router/installation/manual.md +++ b/docs/router/installation/manual.md @@ -204,7 +204,7 @@ function About() { ```tsx title="src/main.tsx" /* @refresh reload */ -import { render } from 'solid-js/web' +import { render } from '@solidjs/web' import { RouterProvider, createRouter } from '@tanstack/solid-router' // Import the generated route tree @@ -232,7 +232,7 @@ render(() => , rootElement) Regardless of whether you are using the `@tanstack/router-plugin` package and running the `npm run dev`/`npm run build` scripts, or manually running the `tsr watch`/`tsr generate` commands from your package scripts, the route tree file will be generated at `src/routeTree.gen.ts`. -If you are working with this pattern, you should change the `id` of the root `
` on your `index.html` file to `
` +If you are working with this pattern you should change the `id` of the root `
` on your `index.html` file to `
` ## Using Code-Based Route Configuration @@ -319,7 +319,7 @@ if (!rootElement.innerHTML) { ```tsx /* @refresh reload */ -import { render } from 'solid-js/web' +import { render } from '@solidjs/web' import { Outlet, RouterProvider, diff --git a/docs/router/installation/with-esbuild.md b/docs/router/installation/with-esbuild.md index 8ecd9b8d0a..b5cad0622c 100644 --- a/docs/router/installation/with-esbuild.md +++ b/docs/router/installation/with-esbuild.md @@ -25,6 +25,7 @@ export default { plugins: [ tanstackRouter({ target: 'react', + autoCodeSplitting: true, }), ], } @@ -49,7 +50,10 @@ const ctx = await esbuild.context({ format: 'esm', target: ['esnext'], sourcemap: true, - plugins: [solidPlugin(), tanstackRouter({ target: 'solid' })], + plugins: [ + solidPlugin(), + tanstackRouter({ target: 'solid', autoCodeSplitting: true }), + ], }) if (isDev) { @@ -68,9 +72,6 @@ Or, you can clone our [Quickstart Esbuild example](https://github.com/TanStack/r Now that you've added the plugin to your Esbuild configuration, you're all set to start using file-based routing with TanStack Router. -> [!NOTE] -> Automatic code splitting is not available with Esbuild: the plugin throws an error when `autoCodeSplitting` is `true`. Route generation works as usual. To split routes, use [manual code splitting](../guide/code-splitting.md) or another bundler. - ## Ignoring the generated route tree file If your project is configured to use a linter and/or formatter, you may want to ignore the generated route tree file. This file is managed by TanStack Router and therefore shouldn't be changed by your linter or formatter. diff --git a/docs/router/integrations/query.md b/docs/router/integrations/query.md index 707f90900c..22fbb927c8 100644 --- a/docs/router/integrations/query.md +++ b/docs/router/integrations/query.md @@ -17,7 +17,7 @@ title: TanStack Query Integration The TanStack query integration is a separate package that you need to install: - + react: @tanstack/react-router-ssr-query solid: @tanstack/solid-router-ssr-query @@ -64,61 +64,6 @@ export function getRouter() { By default, the integration wraps your router with a `QueryClientProvider`. If you already provide your own provider, pass `wrapQueryClient: false` and keep your custom wrapper. -You can also pass `dehydrateOptions` and `hydrateOptions` to customize how TanStack Query serializes SSR payloads and restores them on the client. - -```tsx -setupRouterSsrQueryIntegration({ - router, - queryClient, - dehydrateOptions: { - shouldDehydrateQuery: (query) => query.meta?.ssr !== false, - }, - hydrateOptions: { - defaultOptions: { - queries: { - gcTime: 60_000, - }, - }, - }, -}) -``` - -Common uses for these options: - -- Set `hydrateOptions.defaultOptions.queries.gcTime` to control how long hydrated SSR queries stay in the client cache before garbage collection. -- Set `dehydrateOptions.shouldDehydrateQuery` to exclude queries you do not want serialized into the HTML payload. -- Set `dehydrateOptions.serializeData` and `hydrateOptions.defaultOptions.deserializeData` when your SSR payload needs custom serialization. - -```tsx title="src/router.tsx" -import { QueryClient } from '@tanstack/react-query' -import { createRouter } from '@tanstack/react-router' -import { setupRouterSsrQueryIntegration } from '@tanstack/react-router-ssr-query' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - const queryClient = new QueryClient() - - const router = createRouter({ - routeTree, - context: { queryClient }, - }) - - setupRouterSsrQueryIntegration({ - router, - queryClient, - hydrateOptions: { - defaultOptions: { - queries: { - gcTime: 5 * 60 * 1000, - }, - }, - }, - }) - - return router -} -``` - ## SSR behavior and streaming - During server render, the integration dehydrates initial queries and streams any subsequent queries that resolve while rendering. @@ -132,6 +77,14 @@ export function getRouter() { - `useSuspenseQuery`: runs on the server during SSR when its data is required and will be streamed to the client as it resolves. - `useQuery`: does not execute on the server; it will fetch on the client after hydration. Use this for data that is not required for SSR. +```tsx +// Suspense: executes on server and streams +const { data } = useSuspenseQuery(postsQuery) + +// Non-suspense: executes only on client +const { data, isLoading } = useQuery(postsQuery) +``` + # React @@ -152,7 +105,7 @@ Preload critical data in the route `loader` to avoid waterfalls and loading flas -# Blocking `query` in loader +# React ```tsx title="src/routes/posts.tsx" import { queryOptions, useSuspenseQuery, useQuery } from '@tanstack/react-query' @@ -165,12 +118,7 @@ const postsQuery = queryOptions({ export const Route = createFileRoute('/posts')({ // Ensure the data is in the cache before render - loader: ({ context }) => - context.queryClient.query({ - ...postsQuery, - // returns data from cache immediately, otherwise executes a fetch - staleTime: 'static', - }), + loader: ({ context }) => context.queryClient.ensureQueryData(postsQuery), component: PostsPage, }) @@ -185,15 +133,15 @@ function PostsPage() { ### Prefetching and streaming -You can also prefetch with `query` in a loader without consuming the data in a component. If you return the promise directly from the loader, it will be awaited and thus block the SSR request until the query finishes. If you don't await the promise nor return it, the query will be started on the server and will be streamed to the client without blocking the SSR request. +You can also prefetch with `fetchQuery` or `ensureQueryData` in a loader without consuming the data in a component. If you return the promise directly from the loader, it will be awaited and thus block the SSR request until the query finishes. If you don't await the promise nor return it, the query will be started on the server and will be streamed to the client without blocking the SSR request. -# Non-blocking `query` in loader +# React ```tsx title="src/routes/users.$id.tsx" import { createFileRoute } from '@tanstack/react-router' -import { noop, queryOptions, useQuery } from '@tanstack/react-query' +import { queryOptions, useQuery } from '@tanstack/react-query' const userQuery = (id: string) => queryOptions({ @@ -202,18 +150,15 @@ const userQuery = (id: string) => }) export const Route = createFileRoute('/user/$id')({ - loader: ({ context, params }) => { - // Do not await this nor return the promise, just kick off the query to stream it to the client - void context.queryClient.query(userQuery(params.id)).catch(noop) + loader: ({ params }) => { + // do not await this nor return the promise, just kick off the query to stream it to the client + context.queryClient.fetchQuery(userQuery(params.id)) }, }) ``` -> [!NOTE] -> Previous versions of this guide used `queryClient.ensureQueryData` and `queryClient.prefetchQuery`. These methods are now deprecated in TanStack Query in favor of `queryClient.query`. See the TanStack Query [v5 migration guide](https://tanstack.com/query/latest/docs/framework/react/guides/migrating-to-v5#imperative-queryclient-methods) for more details. - ## Redirect handling If a query or mutation throws a `redirect(...)`, the integration intercepts it on the client and performs a router navigation. diff --git a/docs/router/llm-support.md b/docs/router/llm-support.md new file mode 100644 index 0000000000..0af9c58770 --- /dev/null +++ b/docs/router/llm-support.md @@ -0,0 +1,32 @@ +--- +id: llm-assistance +title: LLM Assistance Support +--- + +TanStack Router's documentation is integrated into its NPM module, making it available to install as LLM assistance rules. These rules can be integrated into various editors to provide context-aware help using [`vibe-rules`](https://www.npmjs.com/package/vibe-rules). + +## Installation + +To use `vibe-rules`, install it globally using your package manager of choice. For example, with `pnpm`: + +```bash +pnpm add -g vibe-rules +``` + +Once installed, you can then run it in the editor of your choice. For example, to integrate with Cursor: + +```bash +vibe-rules install cursor +``` + +## Supported Editors + +`vibe-rules` supports a variety of editors, including `windsurf`, `claude-code`, and more. For more information on supported editors and how to set them up, refer to the [`vibe-rules` documentation](https://github.com/FutureExcited/vibe-rules). + +> [!IMPORTANT] +> If you're using [Yarn Workspaces](https://yarnpkg.com/features/workspaces), you will need to add the following configuration to your `.yarnrc.yaml` file of your application that uses TanStack Router: + +> ```yaml +> pnpFallbackMode: all +> pnpMode: loose +> ``` diff --git a/docs/router/quick-start.md b/docs/router/quick-start.md index a3571756df..69ec50c538 100644 --- a/docs/router/quick-start.md +++ b/docs/router/quick-start.md @@ -9,8 +9,8 @@ The fastest way to get started with TanStack Router is to scaffold a new project -react: @tanstack/cli create --router-only -solid: @tanstack/cli create --router-only --framework solid +react: create-tsrouter-app@latest +solid: create-tsrouter-app@latest --framework solid @@ -25,7 +25,7 @@ The CLI will guide you through a short series of prompts to customize your setup Once complete, a new project will be generated with TanStack Router installed and ready to use. > [!TIP] -> For full details on available options and templates, visit the [`@tanstack/cli` documentation](https://github.com/TanStack/cli). +> For full details on available options and templates, visit the [`create-tsrouter-app` documentation](https://github.com/TanStack/create-tsrouter-app/tree/main/cli/create-tsrouter-app). ## Routing Options @@ -35,37 +35,23 @@ TanStack Router supports both file-based and code-based route configurations. Yo The file-based approach is the recommended option for most projects. It automatically creates routes based on your file structure, giving you the best mix of performance, simplicity, and developer experience. -For more details, see the [file-based routing documentation](./routing/file-based-routing.md) or + - +react: create-tsrouter-app@latest my-app --template file-router +solid: create-tsrouter-app@latest my-app --framework solid --template file-router -# React - -[explore the live example](https://tanstack.com/router/latest/docs/framework/react/examples/basic-file-based) - -# Solid - -[explore the live example](https://tanstack.com/router/latest/docs/framework/solid/examples/basic-file-based) - - + ### Code-Based Route Configuration If you prefer to define routes programmatically, you can use the code-based route configuration. This approach gives you full control over routing logic. -For more details, see the [code-based routing documentation](./routing/code-based-routing.md) or + - +react: create-tsrouter-app@latest my-app +solid: create-tsrouter-app@latest my-app --framework solid -# React - -[explore the live example](https://tanstack.com/router/latest/docs/framework/react/examples/basic) - -# Solid - -[explore the live example](https://tanstack.com/router/latest/docs/framework/solid/examples/basic) - - + With either approach, navigate to your project directory and start the development server. diff --git a/docs/router/routing/code-based-routing.md b/docs/router/routing/code-based-routing.md index b1457c6fbe..d3102cafd6 100644 --- a/docs/router/routing/code-based-routing.md +++ b/docs/router/routing/code-based-routing.md @@ -14,7 +14,7 @@ title: Code-Based Routing Code-based routing is no different from file-based routing in that it uses the same route tree concept to organize, match and compose matching routes into a component tree. The only difference is that instead of using the filesystem to organize your routes, you use code. -Let's consider the same route tree from the [Route Trees](./route-trees.md#route-trees) guide, and convert it to code-based routing: +Let's consider the same route tree from the [Route Trees & Nesting](./route-trees.md#route-trees) guide, and convert it to code-based routing: Here is the file-based version: diff --git a/docs/router/routing/file-based-routing.md b/docs/router/routing/file-based-routing.md index 2eea38bba2..6be11e55d6 100644 --- a/docs/router/routing/file-based-routing.md +++ b/docs/router/routing/file-based-routing.md @@ -12,7 +12,7 @@ File-based routing is a way to configure your routes using the filesystem. Inste - **Organization**: Routes are organized in a way that mirrors the URL structure of your application. - **Scalability**: As your application grows, file-based routing makes it easy to add new routes and maintain existing ones. - **Code-Splitting**: File-based routing allows TanStack Router to automatically code-split your routes for better performance. -- **Type-Safety**: File-based routing raises the ceiling on type-safety by generating and managing type linkages for your routes, which can otherwise be a tedious process via code-based routing. +- **Type-Safety**: File-based routing raises the ceiling on type-safety by generating managing type linkages for your routes, which can otherwise be a tedious process via code-based routing. - **Consistency**: File-based routing enforces a consistent structure for your routes, making it easier to maintain and update your application and move from one project to another. ## `/`s or `.`s? @@ -80,7 +80,7 @@ See the example below: ## Mixed Flat and Directory Routes -It's extremely likely that a 100% directory or flat route structure won't be the best fit for your project, which is why TanStack Router allows you to mix both flat and directory routes together to create a route tree that uses the best of both worlds where it makes sense. +It's extremely likely that a 100% directory or flat route structure won't be the best fit for your project, which is why TanStack Router allows you to mix both flat and directory routes together to create a route tree that uses the best of both worlds where it makes sense: See the example below: diff --git a/docs/router/routing/file-naming-conventions.md b/docs/router/routing/file-naming-conventions.md index 896e7d3d9b..115310f5b3 100644 --- a/docs/router/routing/file-naming-conventions.md +++ b/docs/router/routing/file-naming-conventions.md @@ -2,7 +2,7 @@ title: File Naming Conventions --- -File-based routing requires that you follow a few simple file naming conventions to ensure that your routes are generated correctly. The concepts these conventions enable are covered in detail in the [Route Trees](./route-trees.md) guide. +File-based routing requires that you follow a few simple file naming conventions to ensure that your routes are generated correctly. The concepts these conventions enable are covered in detail in the [Route Trees & Nesting](./route-trees.md) guide. | Feature | Description | | ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | @@ -40,4 +40,4 @@ Pathless routes wrap child routes with either logic or a component without requi | ʦ `_app.a.tsx` | /a | `
` | | ʦ `_app.b.tsx` | /b | `` | -To learn more about pathless routes, see the [Routing Concepts - Pathless Layout Routes](./routing-concepts.md#pathless-layout-routes) guide. +To learn more about pathless routes, see the [Routing Concepts - Pathless Routes](./routing-concepts.md#pathless-layout-routes) guide. diff --git a/docs/router/routing/routing-concepts.md b/docs/router/routing/routing-concepts.md index 11674e69c2..88eebbd5f0 100644 --- a/docs/router/routing/routing-concepts.md +++ b/docs/router/routing/routing-concepts.md @@ -564,7 +564,7 @@ routes/ │ ├── ... ``` -We can import from the excluded files into our posts route: +We can import from the excluded files into our posts route diff --git a/docs/router/routing/virtual-file-routes.md b/docs/router/routing/virtual-file-routes.md index 2de0ded5df..79754685e1 100644 --- a/docs/router/routing/virtual-file-routes.md +++ b/docs/router/routing/virtual-file-routes.md @@ -187,8 +187,6 @@ export const routes = rootRoute('root.tsx', [ ]) ``` -Because `route` receives an explicit URL path, leading and trailing underscores are treated literally. Use `layout` to create pathless layout routes. - You can also define a virtual route without a file name. This allows to set a common path prefix for its children: ```tsx diff --git a/docs/start/config.json b/docs/start/config.json index 36af0e6e0d..4482e44855 100644 --- a/docs/start/config.json +++ b/docs/start/config.json @@ -21,6 +21,10 @@ "label": "Getting Started", "to": "framework/react/getting-started" }, + { + "label": "Quick Start", + "to": "framework/react/quick-start" + }, { "label": "Build from Scratch", "to": "framework/react/build-from-scratch" @@ -36,10 +40,6 @@ { "label": "Migrate from Next.js", "to": "framework/react/migrate-from-next-js" - }, - { - "label": "Migrate from the Release Candidate", - "to": "framework/react/migrate-from-release-candidate" } ] }, @@ -55,21 +55,20 @@ "to": "framework/solid/getting-started" }, { - "label": "Build from Scratch", - "to": "framework/solid/build-from-scratch" + "label": "Quick Start", + "to": "framework/solid/quick-start" }, { - "label": "Migrate from the Release Candidate", - "to": "framework/solid/migrate-from-release-candidate" + "label": "Build from Scratch", + "to": "framework/solid/build-from-scratch" } ] } ] }, { - "label": "Server & Execution", + "label": "Guides", "children": [], - "collapsible": true, "frameworks": [ { "label": "react", @@ -90,10 +89,6 @@ "label": "Import Protection", "to": "framework/react/guide/import-protection" }, - { - "label": "Path Aliases", - "to": "framework/react/guide/path-aliases" - }, { "label": "Environment Variables", "to": "framework/react/guide/environment-variables" @@ -102,14 +97,6 @@ "label": "Server Functions", "to": "framework/react/guide/server-functions" }, - { - "label": "Streaming Data from Server Functions", - "to": "framework/react/guide/streaming-data-from-server-functions" - }, - { - "label": "Server Components", - "to": "framework/react/guide/server-components" - }, { "label": "Static Server Functions", "to": "framework/react/guide/static-server-functions" @@ -129,6 +116,78 @@ { "label": "Server Routes", "to": "framework/react/guide/server-routes" + }, + { + "label": "Hydration Errors", + "to": "framework/react/guide/hydration-errors" + }, + { + "label": "Selective SSR", + "to": "framework/react/guide/selective-ssr" + }, + { + "label": "SPA Mode", + "to": "framework/react/guide/spa-mode" + }, + { + "label": "Static Prerendering", + "to": "framework/react/guide/static-prerendering" + }, + { + "label": "Incremental Static Regeneration (ISR)", + "to": "framework/react/guide/isr" + }, + { + "label": "Server Entry Point", + "to": "framework/react/guide/server-entry-point" + }, + { + "label": "CDN Asset URLs", + "to": "framework/react/guide/cdn-asset-urls" + }, + { + "label": "Client Entry Point", + "to": "framework/react/guide/client-entry-point" + }, + { + "label": "Hosting", + "to": "framework/react/guide/hosting" + }, + { + "label": "Authentication Overview", + "to": "framework/react/guide/authentication-overview" + }, + { + "label": "Authentication", + "to": "framework/react/guide/authentication" + }, + { + "label": "Databases", + "to": "framework/react/guide/databases" + }, + { + "label": "Observability", + "to": "framework/react/guide/observability" + }, + { + "label": "Path Aliases", + "to": "framework/react/guide/path-aliases" + }, + { + "label": "Tailwind CSS Integration", + "to": "framework/react/guide/tailwind-integration" + }, + { + "label": "Rendering Markdown", + "to": "framework/react/guide/rendering-markdown" + }, + { + "label": "SEO", + "to": "framework/react/guide/seo" + }, + { + "label": "LLM Optimization (LLMO)", + "to": "framework/react/guide/llmo" } ] }, @@ -151,10 +210,6 @@ "label": "Import Protection", "to": "framework/solid/guide/import-protection" }, - { - "label": "Path Aliases", - "to": "framework/solid/guide/path-aliases" - }, { "label": "Environment Variables", "to": "framework/solid/guide/environment-variables" @@ -182,72 +237,11 @@ { "label": "Server Routes", "to": "framework/solid/guide/server-routes" - } - ] - } - ] - }, - { - "label": "Rendering", - "children": [], - "collapsible": true, - "frameworks": [ - { - "label": "react", - "children": [ - { - "label": "Hydration Errors", - "to": "framework/react/guide/hydration-errors" }, - { - "label": "Deferred Hydration", - "to": "framework/react/guide/deferred-hydration" - }, - { - "label": "Selective SSR", - "to": "framework/react/guide/selective-ssr" - }, - { - "label": "SPA Mode", - "to": "framework/react/guide/spa-mode" - }, - { - "label": "Static Prerendering", - "to": "framework/react/guide/static-prerendering" - }, - { - "label": "Incremental Static Regeneration (ISR)", - "to": "framework/react/guide/isr" - }, - { - "label": "Server Entry Point", - "to": "framework/react/guide/server-entry-point" - }, - { - "label": "Client Entry Point", - "to": "framework/react/guide/client-entry-point" - }, - { - "label": "Early Hints", - "to": "framework/react/guide/early-hints" - }, - { - "label": "CDN Asset URLs", - "to": "framework/react/guide/cdn-asset-urls" - } - ] - }, - { - "label": "solid", - "children": [ { "label": "Hydration Errors", "to": "framework/solid/guide/hydration-errors" }, - { - "label": "Deferred Hydration", - "to": "framework/solid/guide/deferred-hydration" - }, { "label": "Selective SSR", "to": "framework/solid/guide/selective-ssr" @@ -268,140 +262,29 @@ "label": "Client Entry Point", "to": "framework/solid/guide/client-entry-point" }, - { - "label": "Early Hints", - "to": "framework/solid/guide/early-hints" - } - ] - } - ] - }, - { - "label": "Deployment & Operations", - "children": [], - "collapsible": true, - "frameworks": [ - { - "label": "react", - "children": [ - { - "label": "Production Checklist", - "to": "framework/react/guide/production-checklist" - }, - { - "label": "Hosting", - "to": "framework/react/guide/hosting" - }, - { - "label": "Observability", - "to": "framework/react/guide/observability" - } - ] - }, - { - "label": "solid", - "children": [ { "label": "Hosting", "to": "framework/solid/guide/hosting" }, { - "label": "Observability", - "to": "framework/solid/guide/observability" - } - ] - } - ] - }, - { - "label": "Authentication & Data", - "children": [], - "collapsible": true, - "frameworks": [ - { - "label": "react", - "children": [ - { - "label": "Choose Authentication", - "to": "framework/react/guide/authentication-overview" - }, - { - "label": "Authentication Server Primitives", - "to": "framework/react/guide/authentication-server-primitives" - }, - { - "label": "Implement Authentication", - "to": "framework/react/guide/authentication" - }, - { - "label": "Databases", - "to": "framework/react/guide/databases" - }, - { - "label": "TanStack Query", - "to": "framework/react/guide/tanstack-query" - } - ] - }, - { - "label": "solid", - "children": [ - { - "label": "Choose Authentication", + "label": "Authentication Overview", "to": "framework/solid/guide/authentication-overview" }, { - "label": "Authentication Server Primitives", - "to": "framework/solid/guide/authentication-server-primitives" - }, - { - "label": "Implement Authentication", + "label": "Authentication", "to": "framework/solid/guide/authentication" }, { "label": "Databases", "to": "framework/solid/guide/databases" - } - ] - } - ] - }, - { - "label": "Styling & Metadata", - "children": [], - "collapsible": true, - "frameworks": [ - { - "label": "react", - "children": [ - { - "label": "CSS Styling", - "to": "framework/react/guide/css-styling" }, { - "label": "Tailwind CSS Integration", - "to": "framework/react/guide/tailwind-integration" + "label": "Observability", + "to": "framework/solid/guide/observability" }, { - "label": "Rendering Markdown", - "to": "framework/react/guide/rendering-markdown" - }, - { - "label": "SEO", - "to": "framework/react/guide/seo" - }, - { - "label": "Generative Engine Optimization (GEO)", - "to": "framework/react/guide/geo" - } - ] - }, - { - "label": "solid", - "children": [ - { - "label": "CSS Styling", - "to": "framework/solid/guide/css-styling" + "label": "Path Aliases", + "to": "framework/solid/guide/path-aliases" }, { "label": "Tailwind CSS Integration", @@ -412,8 +295,8 @@ "to": "framework/solid/guide/seo" }, { - "label": "Generative Engine Optimization (GEO)", - "to": "framework/solid/guide/geo" + "label": "LLM Optimization (LLMO)", + "to": "framework/solid/guide/llmo" } ] } diff --git a/docs/start/eslint/eslint-plugin-start.md b/docs/start/eslint/eslint-plugin-start.md deleted file mode 100644 index 1b143e74a4..0000000000 --- a/docs/start/eslint/eslint-plugin-start.md +++ /dev/null @@ -1,107 +0,0 @@ ---- -id: eslint-plugin-start -title: ESLint Plugin Start ---- - -TanStack Start comes with its own ESLint plugin. This plugin is used to enforce best practices and help you avoid common mistakes when working with Server Components and server/client boundaries. - -## Installation - -The plugin is a separate package that you need to install: - -```sh -npm install -D @tanstack/eslint-plugin-start -``` - -or - -```sh -pnpm add -D @tanstack/eslint-plugin-start -``` - -or - -```sh -yarn add -D @tanstack/eslint-plugin-start -``` - -or - -```sh -bun add -D @tanstack/eslint-plugin-start -``` - -## Flat Config (`eslint.config.js`) - -The release of ESLint 9.0 introduced a new way to configure ESLint using a flat config format. The TanStack Start ESLint Plugin supports this format and provides a recommended config you can use to enable all recommended rules. - -### Recommended Flat Config setup - -To enable all recommended rules: - -```js -// eslint.config.js -import pluginStart from '@tanstack/eslint-plugin-start' - -export default [ - pluginStart.configs['flat/recommended'], - // Any other config... -] -``` - -### Custom Flat Config setup - -Alternatively, load the plugin and configure only the rules you want: - -```js -// eslint.config.js -import pluginStart from '@tanstack/eslint-plugin-start' - -export default [ - { - plugins: { - '@tanstack/start': pluginStart, - }, - rules: { - '@tanstack/start/no-client-code-in-server-component': 'error', - '@tanstack/start/no-async-client-component': 'error', - }, - }, - // Any other config... -] -``` - -## Legacy Config (`.eslintrc`) - -Prior to ESLint 9.0, the most common way to configure ESLint was using a `.eslintrc` file. The TanStack Start ESLint plugin still supports this configuration method. - -### Recommended Legacy Config setup - -To enable all recommended rules, add `plugin:@tanstack/eslint-plugin-start/recommended` in `extends`: - -```json -{ - "extends": ["plugin:@tanstack/eslint-plugin-start/recommended"] -} -``` - -### Custom Legacy Config setup - -Alternatively, add `@tanstack/eslint-plugin-start` to `plugins` and configure the rules you want: - -```json -{ - "plugins": ["@tanstack/eslint-plugin-start"], - "rules": { - "@tanstack/start/no-client-code-in-server-component": "error", - "@tanstack/start/no-async-client-component": "error" - } -} -``` - -## Rules - -The following rules are available in the TanStack Start ESLint plugin: - -- [@tanstack/start/no-client-code-in-server-component](./no-client-code-in-server-component.md) -- [@tanstack/start/no-async-client-component](./no-async-client-component.md) diff --git a/docs/start/eslint/no-async-client-component.md b/docs/start/eslint/no-async-client-component.md deleted file mode 100644 index b2007d31e8..0000000000 --- a/docs/start/eslint/no-async-client-component.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -id: no-async-client-component -title: Disallow async components in client context ---- - -Async React components are only valid within React Server Components. - -In TanStack Start, that means async components must only be used in server-component context, for example: - -- rendered by `renderServerComponent()` -- rendered inside a `createCompositeComponent((props) => )` callback - -This rule helps you catch async components that have become "client" (directly or transitively), which would otherwise crash at runtime. - -## Rule Details - -Examples of **incorrect** code for this rule: - -```tsx -/* eslint "@tanstack/start/no-async-client-component": "error" */ - -import { createFileRoute } from '@tanstack/react-router' - -export async function Page() { - return
-} - -export const Route = createFileRoute(undefined)({ - component: Page, -}) -``` - -Examples of **correct** code for this rule: - -```tsx -/* eslint "@tanstack/start/no-async-client-component": "error" */ - -import { createFileRoute } from '@tanstack/react-router' - -export function Page() { - return
-} - -export const Route = createFileRoute(undefined)({ - component: Page, -}) -``` - -```tsx -/* eslint "@tanstack/start/no-async-client-component": "error" */ - -import { createCompositeComponent } from '@tanstack/react-start/rsc' - -export const ServerPage = createCompositeComponent(async () => { - const message = await Promise.resolve('hello') - return
{message}
-}) -``` - -## Reporting location - -This rule can report in two ways: - -- **Usage-site**: if a component becomes client due to being referenced by route options, the error should be reported at the route option usage. -- **Definition-site**: if a component is client due to `'use client'` or being rendered by a client component, the error is reported at the component definition. - -## Attributes - -- [x] ✅ Recommended diff --git a/docs/start/eslint/no-client-code-in-server-component.md b/docs/start/eslint/no-client-code-in-server-component.md deleted file mode 100644 index 8f93590cc9..0000000000 --- a/docs/start/eslint/no-client-code-in-server-component.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -id: no-client-code-in-server-component -title: Disallow client-only code in server components ---- - -TanStack Start defines React Server Component boundaries via RSC helpers like `renderServerComponent()` and `createCompositeComponent()`. - -- `renderServerComponent()` is a server boundary around the element. -- `createCompositeComponent((props) => )` is a server boundary around the callback. - -Inside these boundaries (and anything rendered from them, unless it crosses a `'use client'` boundary) you must not use client-only code. - -This rule detects common client-only patterns in server components: - -- React client hooks (eg `useState`, `useEffect`) -- browser-only globals (eg `window`, `document`) -- React event handlers (`onClick`, etc.) -- function props (non-serializable across the server/client boundary) -- class components - -## Rule Details - -Examples of **incorrect** code for this rule: - -```tsx -/* eslint "@tanstack/start/no-client-code-in-server-component": "error" */ - -import { createCompositeComponent } from '@tanstack/react-start/rsc' -import { useState } from 'react' - -export const Server = createCompositeComponent(() => { - const [count] = useState(0) - return
{count}
-}) -``` - -```tsx -/* eslint "@tanstack/start/no-client-code-in-server-component": "error" */ - -import { createCompositeComponent } from '@tanstack/react-start/rsc' - -export const Server = createCompositeComponent(() => { - return
{window.location.href}
-}) -``` - -Examples of **correct** code for this rule: - -```tsx -/* eslint "@tanstack/start/no-client-code-in-server-component": "error" */ - -import { renderServerComponent } from '@tanstack/react-start/rsc' - -export const Server = renderServerComponent( - (async () => { - const msg = await Promise.resolve('ok') - return
{msg}
- })(), -) -``` - -## Attributes - -- [x] ✅ Recommended diff --git a/docs/start/framework/react/build-from-scratch.md b/docs/start/framework/react/build-from-scratch.md index a0a04f06d4..366374d514 100644 --- a/docs/start/framework/react/build-from-scratch.md +++ b/docs/start/framework/react/build-from-scratch.md @@ -4,7 +4,7 @@ title: Build a Project from Scratch --- > [!NOTE] -> If you already created a project with the CLI or by cloning an example from the [Getting Started](./getting-started) guide, you can skip this guide and move on to the [Routing](./guide/routing) guide. +> If you chose to quick start with an example or cloned project, you can skip this guide and move on to the [Routing](./guide/routing) guide. _So you want to build a TanStack Start project from scratch?_ @@ -49,39 +49,33 @@ We highly recommend using TypeScript with TanStack Start. Create a `tsconfig.jso ## Install Dependencies -TanStack Start is powered by [TanStack Router](https://tanstack.com/router) and supports [Vite](https://vite.dev/) or [Rsbuild](https://rsbuild.dev/) as the build tool. +TanStack Start is powered by [Vite](https://vite.dev/) and [TanStack Router](https://tanstack.com/router) and requires them as dependencies. -To install Start and Router, run: +To install them, run: ```shell npm i @tanstack/react-start @tanstack/react-router ``` +We also need vite as a devDependency: + +```shell +npm i -D vite +``` + You'll also need React: ```shell npm i react react-dom ``` -Install the build tool and React integration you want to use: - - - -# Vite +As well as React's Vite plugin: ```shell -npm i -D vite @vitejs/plugin-react +npm i -D @vitejs/plugin-react ``` -# Rsbuild - -```shell -npm i -D @rsbuild/core @rsbuild/plugin-react -``` - - - -If you use Vite, you can also use `@vitejs/plugin-react-swc` instead of `@vitejs/plugin-react`. +Alternatively, you can also use `@vitejs/plugin-react-swc`. and some TypeScript: @@ -91,11 +85,7 @@ npm i -D typescript @types/react @types/react-dom @types/node ## Update Configuration Files -We'll then update our `package.json` to use your build tool's CLI and set `"type": "module"`: - - - -# Vite +We'll then update our `package.json` to use Vite's CLI and set `"type": "module"`: ```json { @@ -108,28 +98,10 @@ We'll then update our `package.json` to use your build tool's CLI and set `"type } ``` -# Rsbuild +Then configure TanStack Start's Vite plugin in `vite.config.ts`: -```json -{ - // ... - "type": "module", - "scripts": { - "dev": "rsbuild dev", - "build": "rsbuild build" - } -} -``` - - - -Then configure TanStack Start's build tool plugin: - - - -# Vite - -```ts title="vite.config.ts" +```ts +// vite.config.ts import { defineConfig } from 'vite' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import viteReact from '@vitejs/plugin-react' @@ -149,23 +121,6 @@ export default defineConfig({ }) ``` -# Rsbuild - -```ts title="rsbuild.config.ts" -import { defineConfig } from '@rsbuild/core' -import { pluginReact } from '@rsbuild/plugin-react' -import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild' - -export default defineConfig({ - server: { - port: 3000, - }, - plugins: [pluginReact(), tanstackStart()], -}) -``` - - - ## Add the Basic Templating There are 2 required files for TanStack Start usage: @@ -182,7 +137,7 @@ Once configuration is done, we'll have a file tree that looks like the following │ │ └── `__root.tsx` │ ├── `router.tsx` │ ├── `routeTree.gen.ts` -├── `vite.config.ts` or `rsbuild.config.ts` +├── `vite.config.ts` ├── `package.json` └── `tsconfig.json` ``` @@ -216,6 +171,7 @@ Finally, we need to create the root of our application. This is the entry point ```tsx // src/routes/__root.tsx +/// import type { ReactNode } from 'react' import { Outlet, @@ -290,7 +246,7 @@ const getCount = createServerFn({ }) const updateCount = createServerFn({ method: 'POST' }) - .validator((d: number) => d) + .inputValidator((d: number) => d) .handler(async ({ data }) => { const count = await readCount() await fs.promises.writeFile(filePath, `${count + data}`) diff --git a/docs/start/framework/react/comparison.md b/docs/start/framework/react/comparison.md index b72e286a76..b68a1cc08e 100644 --- a/docs/start/framework/react/comparison.md +++ b/docs/start/framework/react/comparison.md @@ -1,61 +1,337 @@ --- title: Comparison | TanStack Start vs Next.js vs React Router -description: Compare rendering, server APIs, caching, forms, and deployment in TanStack Start, Next.js App Router, and React Router Framework Mode. toc: false --- -This matrix compares full-stack framework capabilities. For the choice between Start and Next.js, read [TanStack Start vs Next.js](./start-vs-nextjs). For navigation and URL-state APIs, see the [TanStack Router comparison](/router/latest/docs/comparison). +Choosing a full-stack React framework? This comparison focuses on the **full-stack framework features** that distinguish TanStack Start from Next.js and React Router (v7 Framework Mode). -Checked September 11, 2026 against the linked documentation: TanStack Start's current guides, Next.js 16.3 App Router, and React Router 8.3 Framework Mode. +> **🚨 IMPORTANT: Looking for routing features?** +> +> TanStack Start is built on **TanStack Router**, which provides industry-leading type-safe routing capabilities. For a comprehensive comparison of routing features (nested routes, search params, type safety, loaders, etc.), please see: +> +> ### [📖 TanStack Router Comparison vs React Router / Next.js →](/router/latest/docs/framework/react/comparison) +> +> That comparison covers all the routing features in detail. This page focuses specifically on **full-stack framework capabilities** like SSR, server functions, middleware, deployment, and more. -## Rendering and data +While we aim to provide an accurate and fair comparison, please note that this table may not capture every nuance or recent update of each framework. We recommend reviewing the official documentation and trying out each solution to make the most informed decision for your specific use case. -| Capability | TanStack Start | Next.js App Router | React Router Framework Mode | -| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | -| Server rendering | [SSR with hydration by default](./overview) | [Server and Client Components contribute to initial HTML](https://nextjs.org/docs/app/getting-started/server-and-client-components) | [Server rendering is configurable](https://reactrouter.com/start/framework/rendering) | -| Rendering control | [Per-route full, data-only, or disabled SSR](./guide/selective-ssr) | [Server/Client Component boundaries](https://nextjs.org/docs/app/getting-started/server-and-client-components); `use client` does not disable initial SSR | [Global SSR setting and route-level client loaders](https://reactrouter.com/start/framework/rendering) | -| SPA applications | [Dedicated SPA mode](./guide/spa-mode) | [Documented SPA patterns](https://nextjs.org/docs/app/guides/single-page-applications) | [`ssr: false`](https://reactrouter.com/start/framework/rendering) | -| Static output | [Prerendering configuration](./guide/static-prerendering) | [Static export](https://nextjs.org/docs/app/guides/static-exports), with server-feature limitations | [Prerender selected URLs](https://reactrouter.com/start/framework/rendering) | -| React Server Components | [Experimental, opt-in](./guide/server-components) | [Core App Router component model](https://nextjs.org/docs/app/getting-started/server-and-client-components) | [Unstable RSC integration](https://reactrouter.com/how-to/react-server-components) | -| Client data reuse | [Router loader caching](/router/latest/docs/guide/data-loading), plus [Query integration](/router/latest/docs/integrations/query) | [Navigation caching and server cache APIs](https://nextjs.org/docs/app/getting-started/caching); a query library can manage additional client data | [Loader/action revalidation](https://reactrouter.com/start/framework/actions); separate client-data tools can be added | -| Revalidation after deployment | [HTTP caching and provider-specific ISR configuration](./guide/isr) | [ISR and cache coordination](https://nextjs.org/docs/app/guides/self-hosting) | [HTTP response headers](https://reactrouter.com/how-to/headers) and deployment infrastructure | +If you find any discrepancies or have suggestions for improvement, please don't hesitate to contribute via the "Edit this page on GitHub" link at the bottom of this page or open an issue in the [TanStack Router GitHub repository](https://github.com/TanStack/router). -A client loader cache, a cached server result, and a cached HTML response are different things. Compare invalidation behavior, persistence, and multi-instance coordination for the layer your application needs. A CDN honoring `stale-while-revalidate` is not proof of identical ISR behavior across providers. +Feature/Capability Key: -## Server APIs and forms +- ✅ 1st-class, built-in, and ready to use with no added configuration or code +- 🟡 Partial Support (rated 1-5 where noted) +- 🟠 Supported via addon/community package +- 🔶 Possible, but requires custom code/implementation/casting +- 🛑 Not officially supported -| Capability | TanStack Start | Next.js App Router | React Router Framework Mode | -| -------------------------- | -------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | -| Server calls and mutations | [Typed server functions with GET or POST](./guide/server-functions) | [Server Actions](https://nextjs.org/docs/app/guides/forms) | [Route actions and fetchers](https://reactrouter.com/start/framework/actions) | -| Input validation | [Validator API with inferred types](./guide/server-functions) | [Validate action input with application code or a schema](https://nextjs.org/docs/app/guides/forms) | [Validate action input with application code](https://reactrouter.com/how-to/form-validation) | -| Middleware | [Request middleware and client/server function middleware](./guide/middleware) | [Request interception with Proxy](https://nextjs.org/docs/app/getting-started/proxy); action authorization belongs in server code | [Server and client route middleware](https://reactrouter.com/how-to/middleware) | -| Form handling | [Server functions](./guide/server-functions) can be called from event handlers; use a form library when needed | [Built-in `next/form`](https://nextjs.org/docs/app/api-reference/components/form), plus [Server Action forms](https://nextjs.org/docs/app/guides/forms) | [`Form`, actions, and fetchers](https://reactrouter.com/start/framework/actions) | -| Server endpoints | [Server routes](./guide/server-routes) | [Route Handlers](https://nextjs.org/docs/app/getting-started/route-handlers) | [Resource routes](https://reactrouter.com/how-to/resource-routes) | +| | TanStack Start | Next.js [_(Website)_][nextjs] | React Router [_(Website)_][react-router] | +| ----------------------------------------------------------------- | ------------------------------------------------ | --------------------------------------------- | ------------------------------------------ | +| Github Repo / Stars | [![][stars-tanstack-router]][gh-tanstack-router] | [![][stars-nextjs]][gh-nextjs] | [![][stars-react-router]][gh-react-router] | +| Bundle Size | [![][bp-tanstack-router]][bpl-tanstack-router] | ❓ | ❓ | +| -- | -- | -- | -- | +| **Routing Features** [_(See Full Comparison)_][router-comparison] | ✅ Built on TanStack Router | ✅ File-based App Router | ✅ File-based Nested Routes | +| -- | -- | -- | -- | +| **Full-Stack Features** | -- | -- | -- | +| SSR | ✅ | ✅ | ✅ | +| Streaming SSR | ✅ | ✅ | ✅ | +| Selective SSR (per-route) | ✅ | 🔶 | 🔶 | +| SPA Mode | ✅ | 🔶 (via "use client") | ✅ | +| Built-in Client-Side SWR Caching | ✅ (via TanStack Router) | 🔶 (fetch cache only) | 🛑 | +| Data Fetching Library Integration | ✅ (Official TanStack Query, Apollo, etc.) | 🔶 (manual integration) | 🔶 (manual integration) | +| Static Prerendering (SSG) | ✅ | ✅ | ✅ | +| Incremental Static Regeneration (ISR) | ✅ (via Cache-Control headers) | ✅ (Proprietary) | ✅ (via Cache-Control headers) | +| React Server Components | 🛑 (In active development) | ✅ | 🟡 (Experimental) | +| Server Functions | ✅ (RPC-based) | ✅ (Server Actions) | ✅ (Actions) | +| Server Function Client Middleware | ✅ | 🛑 | 🛑 | +| Server Function Server Middleware | ✅ | 🛑 | ✅ | +| Request Middleware (All Routes) | ✅ | ✅ | ✅ | +| Server Function Input Validation | ✅ | 🔶 (manual) | 🔶 (manual) | +| API Routes / Server Routes / Resource Routes | ✅ | ✅ | ✅ | +| `` API | 🛑 | 🟠 (via React 19 useActionState) | ✅ | +| -- | -- | -- | -- | +| **Developer Experience** | -- | -- | -- | +| Devtools | ✅ | 🛑 | 🟠 (3rd party) | +| CLI Tooling | ✅ | ✅ | ✅ | +| Dev Server Startup Speed | ✅ (Fast) | 🛑 (Slow) | ✅ (Fast) | +| HMR Speed | ✅ (Fast, Vite) | 🛑 (Slow, Webpack/Turbopack) | ✅ (Fast, Vite) | +| Dev Navigation Speed | ✅ | 🟡 | ✅ | +| Dev Resource Usage (CPU/RAM) | ✅ (Lightweight) | 🛑 (Heavy) | ✅ (Lightweight) | +| TypeScript Support | ✅ | ✅ | ✅ | +| Type-First Architecture | ✅ | 🛑 | 🛑 | +| -- | -- | -- | -- | +| **Deployment & Hosting** | -- | -- | -- | +| Deployment Flexibility | ✅ (Any Vite-compatible host) | 🟡 (Optimized for Vercel, possible elsewhere) | ✅ (Multiple adapters) | +| Edge Runtime Support | ✅ | ✅ | ✅ | +| Serverless Support | ✅ | ✅ | ✅ | +| Node.js Support | ✅ | ✅ | ✅ | +| Docker Support | ✅ | ✅ | ✅ | +| Static Export | ✅ | ✅ | ✅ | +| Official Cloudflare Support | ✅ | 🟡 | ✅ | +| Official Netlify Support | ✅ | 🟡 | ✅ | +| Official Vercel Support | ✅ (via Nitro) | ✅ | ✅ | -Type inference helps callers write valid code. It does not validate an incoming HTTP request or authorize access to a record. All three frameworks need runtime validation and server-side authorization for private operations. For Start, see [Authentication Server Primitives](./guide/authentication-server-primitives). +--- -## Tooling and deployment +> **⚠️ Remember:** For detailed comparisons of **routing features** (type safety, search params, loaders, navigation, etc.), see the [**TanStack Router Comparison**][router-comparison]. This page focuses on full-stack framework capabilities. -| Capability | TanStack Start | Next.js App Router | React Router Framework Mode | -| ----------------------- | ------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | -| Build integration | [Vite or Rsbuild](./build-from-scratch) | [Turbopack](https://nextjs.org/docs/app/api-reference/turbopack) | [Framework tooling](https://reactrouter.com/start/framework/installation) | -| Type support | [Router inference](/router/latest/docs/guide/type-safety) and [server function inference](./guide/server-functions) | [Stable opt-in typed links](https://nextjs.org/docs/app/api-reference/config/next-config-js/typedRoutes) and TypeScript APIs | [Generated route-module types](https://reactrouter.com/how-to/route-module-type-safety) | -| Metadata | [Route head management and SEO guide](./guide/seo) | [Metadata API and file conventions](https://nextjs.org/docs/app/getting-started/metadata-and-og-images) | [Route-module metadata](https://reactrouter.com/start/framework/route-module) | -| Image and font handling | Choose CSS, an image service, or an integration for your deployment | Built-in [`next/image`](https://nextjs.org/docs/app/api-reference/components/image) and [`next/font`](https://nextjs.org/docs/app/api-reference/components/font) | Choose CSS, an image service, or an integration for your deployment | -| Hosting | [Provider and runtime guides](./guide/hosting) | [Self-hosting](https://nextjs.org/docs/app/guides/self-hosting) or a deployment provider | [Deployment templates and hosting options](https://reactrouter.com/start/framework/deploying) | +--- -Deployment support depends on the adapter, runtime, and features you use. Check streaming, image processing, filesystem access, background work, and shared-cache behavior on your chosen target. Next.js self-hosting includes image optimization and ISR configuration; those features should not be labeled Vercel-only. +## Key Philosophical Differences -## Performance Considerations +### TanStack Start -This page does not establish a performance winner. Startup time, HMR, memory use, JavaScript shipped, and response latency require separate measurements. Comparing a router package's bundle size with an entire framework is not a valid application benchmark. +**Philosophy**: Maximum developer freedom with best-in-class type safety. -For a useful comparison, build the same representative application with recommended patterns in each framework. Record package versions, hardware, dependencies, route count, rendering and caching settings, deployment target, warm and cold runs, and the raw results. +- **Router-First**: Built on TanStack Router (see [full routing comparison][router-comparison]) +- **Deployment Agnostic**: Built on Vite, deploy anywhere without vendor lock-in +- **Composable Middleware**: Middleware system works at both the request level AND individual server function level (both client & server) +- **Selective SSR**: Fine-grained control over SSR behavior per route (full SSR, data-only, or client-only) +- **Developer Control**: Explicit, composable patterns over convention-based magic +- **Type Safety First**: End-to-end compile-time safety for server functions, loaders, and routing + +### Next.js + +**Philosophy**: Production-ready with optimal defaults, best with Vercel. + +- **RSC-First**: Deep integration with React Server Components as the primary paradigm +- **Vercel-Optimized**: Best performance and DX on Vercel's infrastructure +- **Convention over Configuration**: Opinionated structure with file-system routing conventions +- **Automatic Optimizations**: Many performance optimizations happen automatically +- **Production Grade**: Battle-tested at massive scale + +### React Router (v7 Framework Mode) + +**Philosophy**: Web fundamentals with progressive enhancement. + +- **Web Standards**: Embraces web platform primitives (fetch, FormData, Headers) +- **Progressive Enhancement**: Works without JavaScript by default +- **Nested Routes**: First-class support for nested routing and data loading +- **Action-Based**: Form submissions via actions follow web standards +- **Framework Evolution**: Successor to Remix, with Vite-based architecture ## When to Choose Each Framework -- **TanStack Start:** you want typed route context and URL state, explicit loaders and server functions, and control over per-route rendering. -- **Next.js:** you want its Server Component model and integrated image, font, metadata, and form facilities. Existing team experience and integrations can also make staying with Next.js the better choice. -- **React Router Framework Mode:** you want route loaders and actions, fetchers, and form-driven workflows. Read its [progressive enhancement guide](https://reactrouter.com/explanation/progressive-enhancement) if operation before JavaScript loads matters to your application. +### Choose TanStack Start if you: -Check Start's [overview](./overview) and [Server Components guide](./guide/server-components) for current release and experimental-feature status before adopting those features. To try Start, use [Getting Started](./getting-started) or [Migrate from Next.js](./migrate-from-next-js). +- Want the absolute best type safety for routing (see [Router Comparison][router-comparison]) +- Need deployment flexibility without vendor lock-in (works with any Vite-compatible host) +- Prefer composable, explicit patterns over convention +- Want fine-grained control over SSR behavior (selective SSR per route) +- Need composable middleware that works at both request and server function levels +- Are building a complex application that benefits from TanStack Router's advanced features +- Already use TanStack Query or other TanStack libraries + +### Choose Next.js if you: + +- Want to use React Server Components today with full ecosystem support +- Are deploying to Vercel or want a Vercel-optimized experience +- Prefer convention over configuration for faster initial development +- Want automatic image optimization and font loading + +### Choose React Router if you: + +- Prioritize progressive enhancement +- Want your app to work without JavaScript +- Prefer action-based mutations following web conventions + +## Feature Deep Dives + +### Built-in Client-Side Caching + +**TanStack Start** includes powerful built-in SWR (stale-while-revalidate) caching through TanStack Router: + +- **Out-of-the-box performance** - Loader data is automatically cached and revalidated +- **Fine-grained control** - Configure `staleTime`, `gcTime`, and revalidation per route +- **Structural sharing** - Efficient updates that only re-render what changed +- **Official integrations** - Turn-key support for TanStack Query, Apollo, and other data fetching libraries +- **More performant** - Optimized for the user experience with instant navigation and background updates + +```tsx +export const Route = createFileRoute('/posts/$postId')({ + loader: async ({ params }) => fetchPost(params.postId), + staleTime: 10_000, // Consider fresh for 10 seconds + gcTime: 5 * 60_000, // Keep in memory for 5 minutes +}) +``` + +For advanced scenarios, TanStack Start integrates seamlessly with TanStack Query: + +```tsx +import { queryOptions } from '@tanstack/react-query' + +const postQueryOptions = (postId: string) => + queryOptions({ + queryKey: ['post', postId], + queryFn: () => fetchPost(postId), + }) + +export const Route = createFileRoute('/posts/$postId')({ + loader: ({ context, params }) => + context.queryClient.ensureQueryData(postQueryOptions(params.postId)), +}) + +function Post() { + const { postId } = Route.useParams() + const { data } = useQuery(postQueryOptions(postId)) + // Automatically uses cached data from loader +} +``` + +**Next.js** has basic fetch caching but lacks fine-grained control and requires manual integration with libraries like React Query. + +**React Router** doesn't have built-in client-side caching - you need to manually integrate a caching solution. + +### Server Functions vs Server Actions + +**TanStack Start Server Functions**: + +```tsx +export const getTodos = createServerFn({ method: 'GET' }) + .inputValidator(zodValidator(z.object({ userId: z.string() }))) + .middleware([authMiddleware]) + .handler(async ({ data, context }) => { + // Fully typed data and context + return db.todos.findMany({ where: { userId: data.userId } }) + }) + +// Call from anywhere with full type safety +const todos = await getTodos({ data: { userId: '123' } }) +``` + +**Next.js Server Actions**: + +```tsx +'use server' +export async function getTodos(userId: string) { + // Runs on server, called from client + return db.todos.findMany({ where: { userId } }) +} + +// Call from client component +const todos = await getTodos('123') +``` + +Key differences: + +- Start's server functions support both client and server middleware +- Start has built-in input validation +- Start's approach is more explicit about the client/server boundary +- Next.js Server Actions integrate more seamlessly with forms + +### Middleware Architecture + +**TanStack Start** has two types of middleware: + +1. **Request Middleware**: Runs for all requests (SSR, API routes, server functions) +2. **Server Function Middleware**: Runs specifically for server functions, supports both client-side and server-side execution + +This composability allows for: + +```tsx +const authMiddleware = createMiddleware({ type: 'function' }) + .client(async ({ next }) => { + // Run auth checks on client + return next({ + headers: { Authorization: `Bearer ${getToken()}` }, + }) + }) + .server(async ({ next }) => { + // Validate auth on server + return next({ context: { user: await getUser() } }) + }) +``` + +**Next.js** has a single middleware.ts file that runs on the Edge Runtime for all requests. It cannot access server-only resources like databases and has limitations compared to the Node.js runtime. + +### Deployment Flexibility + +**TanStack Start** leverages Vite's ecosystem: + +- Deploy to Cloudflare Workers, Netlify, Vercel, Railway, Fly.io, AWS, etc. +- Use Nitro for universal deployment support +- No vendor-specific features or lock-in +- Same codebase works everywhere + +**Next.js** is optimized for Vercel: + +- Many features work best or only on Vercel (ISR, Image Optimization, Middleware) +- Self-hosting requires more configuration +- Deployment to other platforms may have limitations + +## React Server Components (RSC) + +**Current Status**: + +- **Next.js**: Full production support with extensive ecosystem +- **TanStack Start**: In active development, expected soon +- **React Router**: Experimental support available + +RSC is still evolving, and TanStack Start is taking time to ensure the best possible implementation that aligns with its type-safety-first philosophy. + +## Performance Considerations + +### Production Performance + +All three frameworks are capable of achieving excellent production performance and top Lighthouse scores. The differences come down to optimization strategies: + +- **TanStack Start**: Vite's optimized builds, SWR caching reduces server load, lightweight runtime +- **Next.js**: Automatic code splitting, image optimization, and built-in performance features +- **React Router**: Web standards-based caching and optimization + +### Development Performance + +This is where the frameworks differ significantly: + +**TanStack Start & React Router:** + +- ⚡ **Instant dev server startup** - Vite starts in milliseconds +- ⚡ **Lightning-fast HMR** - Changes reflect instantly without page refresh +- ⚡ **Fast dev navigation** - Full-speed routing during development +- ⚡ **Lightweight resource usage** - Minimal CPU and RAM consumption +- ⚡ **High dev throughput** - Handle many concurrent requests efficiently + +**Next.js:** + +- 🐌 **Slow dev server startup** - Can take many seconds to start, especially on larger projects +- 🐌 **Slow HMR** - Hot reloading is noticeably sluggish even with Turbopack +- 🐌 **Throttled dev navigation** - Navigation is artificially slowed during development +- 🐌 **Heavy resource usage** - Significant CPU and RAM consumption during development + +**Why This Matters:** + +Development performance directly impacts developer productivity. Faster feedback loops mean: + +- More iterations per hour +- Better flow state and focus +- Lower machine requirements +- Reduced frustration during development +- Faster CI/CD pipelines for development builds + +While Next.js's production performance is excellent, the development experience can be notably slower, especially on larger codebases or less powerful machines. + +## Community and Ecosystem + +- **Next.js**: Largest community, most third-party integrations, extensive learning resources +- **React Router**: One of the oldest and most widely used React libraries, strong community, excellent documentation +- **TanStack Start**: Growing community, part of TanStack ecosystem, excellent Discord support + +## Maturity + +- **Next.js**: Production-ready, used by thousands of companies, proven at scale +- **React Router**: Production-ready, powers millions of apps, v7 Framework Mode is the evolution of Remix +- **TanStack Start**: Release Candidate stage, feature-complete, rapidly stabilizing toward v1 + +[bp-tanstack-router]: https://badgen.net/bundlephobia/minzip/@tanstack/react-router +[bpl-tanstack-router]: https://bundlephobia.com/result?p=@tanstack/react-router +[gh-tanstack-router]: https://github.com/tanstack/router +[stars-tanstack-router]: https://img.shields.io/github/stars/tanstack/router?label=%F0%9F%8C%9F +[router-comparison]: /router/latest/docs/framework/react/comparison +[_]: _ +[nextjs]: https://nextjs.org/ +[gh-nextjs]: https://github.com/vercel/next.js +[stars-nextjs]: https://img.shields.io/github/stars/vercel/next.js?label=%F0%9F%8C%9F +[_]: _ +[react-router]: https://reactrouter.com/ +[gh-react-router]: https://github.com/remix-run/react-router +[stars-react-router]: https://img.shields.io/github/stars/remix-run/react-router?label=%F0%9F%8C%9F diff --git a/docs/start/framework/react/getting-started.md b/docs/start/framework/react/getting-started.md index 6e5bcd8841..5415d99da1 100644 --- a/docs/start/framework/react/getting-started.md +++ b/docs/start/framework/react/getting-started.md @@ -1,97 +1,24 @@ --- id: getting-started title: Getting Started -redirect_from: - - /framework/react/quick-start -description: Create a TanStack Start application with TanStack Builder, the CLI, or a working example, then run it locally and start adding routes. --- -## Start a new project - -### Use TanStack Builder - -The best way to get started with TanStack Start is [TanStack Builder](https://tanstack.com/builder). It's the AI-first setup flow and the easiest way to get to a working project fast. - -### Use the CLI - -If you'd rather scaffold locally or want a backup path, use the TanStack CLI: - -```bash -npx @tanstack/cli@latest create -``` - -You'll be prompted to choose your package manager and optional add-ons like Tailwind CSS and ESLint. - -### Start from an example - -If you'd rather begin from a working codebase, clone one of the official examples. - -To start with the [Basic](https://github.com/TanStack/router/tree/main/examples/react/start-basic) example: - -```bash -npx gitpick TanStack/router/tree/main/examples/react/start-basic start-basic -cd start-basic -npm install -npm run dev -``` - -To use a different example, replace `start-basic` with one of the slugs below. - -#### Examples - -- [Basic](https://github.com/TanStack/router/tree/main/examples/react/start-basic) (`start-basic`) -- [Basic + Rsbuild](https://github.com/TanStack/router/tree/main/examples/react/start-basic-rsbuild) (`start-basic-rsbuild`) -- [Basic + Auth](https://github.com/TanStack/router/tree/main/examples/react/start-basic-auth) (`start-basic-auth`) -- [Counter](https://github.com/TanStack/router/tree/main/examples/react/start-counter) (`start-counter`) -- [Basic + React Query](https://github.com/TanStack/router/tree/main/examples/react/start-basic-react-query) (`start-basic-react-query`) -- [Clerk Auth](https://github.com/TanStack/router/tree/main/examples/react/start-clerk-basic) (`start-clerk-basic`) -- [Convex + Trellaux](https://github.com/TanStack/router/tree/main/examples/react/start-convex-trellaux) (`start-convex-trellaux`) -- [Supabase](https://github.com/TanStack/router/tree/main/examples/react/start-supabase-basic) (`start-supabase-basic`) -- [Trellaux](https://github.com/TanStack/router/tree/main/examples/react/start-trellaux) (`start-trellaux`) -- [WorkOS](https://github.com/TanStack/router/tree/main/examples/react/start-workos) (`start-workos`) -- [Material UI](https://github.com/TanStack/router/tree/main/examples/react/start-material-ui) (`start-material-ui`) - -Each example page also includes a StackBlitz preview so you can inspect it before cloning. - -To clone a different example manually, replace `EXAMPLE_SLUG` below with the slug you want to use: - -```bash -npx gitpick TanStack/router/tree/main/examples/react/EXAMPLE_SLUG my-new-project -cd my-new-project -npm install -npm run dev -``` - -If you want to clone and deploy quickly, use the **Deploy to Netlify** button on an example's page. - -### Build from scratch - -If you want to wire everything up by hand, follow [Build a project from scratch](./build-from-scratch). - ## Migrate an existing project from another framework -- If you want to learn Start from a clean slate first, use one of the new-project options above. +- [Start a new project from scratch](#start-a-new-project-from-scratch) to quickly learn how Start works (see below) - Refer to a migration guide for your specific framework: - [Next.js](./migrate-from-next-js) - Remix 2 / React Router 7 "Framework Mode" (coming soon!) +## Start a new project from scratch + +Choose one of the following options to start building a _new_ TanStack Start project: + +- [TanStack Start CLI](https://tanstack.com/cli/latest) - Just run `npx @tanstack/cli@latest create`. Local, fast, and optionally customizable +- [TanStack Builder](https://tanstack.com/builder) - A visual interface to configure new TanStack projects with a few clicks +- [Quick Start Examples](./quick-start) Download or clone one of our official examples +- [Build a project from scratch](./build-from-scratch) - A guide to building a TanStack Start project line-by-line, file-by-file. + ## Next Steps -Once you've created, cloned, or deployed a project, continue to the [Routing](./guide/routing) guide. - -## Other Router Examples - -If you want Router-focused examples that are not Start-specific, these are useful references: - -- [Quickstart (file-based)](https://github.com/TanStack/router/tree/main/examples/react/quickstart-file-based) -- [Basic (file-based)](https://github.com/TanStack/router/tree/main/examples/react/basic-file-based) -- [Kitchen Sink (file-based)](https://github.com/TanStack/router/tree/main/examples/react/kitchen-sink-file-based) -- [Kitchen Sink + React Query (file-based)](https://github.com/TanStack/router/tree/main/examples/react/kitchen-sink-react-query-file-based) -- [Location Masking](https://github.com/TanStack/router/tree/main/examples/react/location-masking) -- [Authenticated Routes](https://github.com/TanStack/router/tree/main/examples/react/authenticated-routes) -- [Scroll Restoration](https://github.com/TanStack/router/tree/main/examples/react/scroll-restoration) -- [Deferred Data](https://github.com/TanStack/router/tree/main/examples/react/deferred-data) -- [Navigation Blocking](https://github.com/TanStack/router/tree/main/examples/react/navigation-blocking) -- [View Transitions](https://github.com/TanStack/router/tree/main/examples/react/view-transitions) -- [With tRPC](https://github.com/TanStack/router/tree/main/examples/react/with-trpc) -- [With tRPC + React Query](https://github.com/TanStack/router/tree/main/examples/react/with-trpc-react-query) +Unless you chose to build a project from scratch, you can now move on to the [Routing](./guide/routing) guide to learn how to use TanStack Start! diff --git a/docs/start/framework/react/guide/authentication-overview.md b/docs/start/framework/react/guide/authentication-overview.md index e80ba97f8c..16fc63090c 100644 --- a/docs/start/framework/react/guide/authentication-overview.md +++ b/docs/start/framework/react/guide/authentication-overview.md @@ -1,11 +1,8 @@ --- id: authentication-overview -title: Choose Authentication for React Apps -description: Compare hosted services, auth libraries, and custom authentication for React apps built with TanStack Start. Choose an approach before implementing sessions and authorization. +title: Authentication --- -Choose how your React app will handle identity, sessions, and permissions. This page compares approaches and providers. Once you have chosen an approach, use [Implement Authentication in React](./authentication.md) for the application workflow. - ## Authentication vs Authorization - **Authentication**: Who is this user? (Login/logout, identity verification) @@ -75,11 +72,11 @@ Choose how your React app will handle identity, sessions, and permissions. This - Good for mixed public/private content on same route - Requires careful handling to prevent layout shifts -**Data/API Protection (Security Boundary)** +**Server Function Guards** -- Authorize every server function, server route, or API endpoint that reads or writes private data -- Reject unauthorized requests even if no protected route was loaded first -- Treat route guards as UX and navigation control, not as the data boundary +- Server-side validation before executing sensitive operations +- Works alongside route-level protection +- Essential for API security regardless of client-side protection ### State Management Patterns @@ -112,11 +109,11 @@ Choose how your React app will handle identity, sessions, and permissions. This ### 🛠️ DIY Authentication -Build your own authentication system using TanStack Start's server functions and session management. Start with the [Authentication Server Primitives](./authentication-server-primitives.md) guide — it covers session cookies (`HttpOnly`/`Secure`/`SameSite`/`__Host-`), session lookup as middleware, OAuth `state` + PKCE, password-reset enumeration defense, CSRF, rate limiting, and session rotation, with the WRONG/CORRECT patterns that catch the common mistakes. +Build your own authentication system using TanStack Start's server functions and session management: - **Full Control**: Complete customization over authentication flow -- **Server Primitives**: Sessions, OAuth, CSRF, rate limiting — see [Authentication Server Primitives](./authentication-server-primitives.md) -- **Session Management**: HTTP-only cookies written with `setCookie`, read with `getCookie` +- **Server Functions**: Secure authentication logic on the server +- **Session Management**: Built-in session handling with HTTP-only cookies - **Type Safety**: End-to-end type safety for authentication state ### 🌐 Other Excellent Options @@ -210,17 +207,14 @@ Build your own authentication system using TanStack Start's server functions and - Specific business logic needs - Full ownership of authentication data -### Production Auth Checklist +### Security Considerations -- Use HTTPS in production and set a strong session secret. -- Store sessions in `HttpOnly`, `Secure`, `SameSite` cookies. Do not store session tokens in `localStorage` or `sessionStorage`. -- Enforce auth in every server function, server route, or API endpoint that reads or writes private user, tenant, or account data. Use `beforeLoad` for page UX, not as the data boundary. -- Use `.validator()` on every server function that accepts input. -- 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. +- Use HTTPS in production +- Use HTTP-only cookies when possible +- Validate all inputs on the server +- Keep secrets in server-only functions +- Implement rate limiting for auth endpoints +- Use CSRF protection for form submissions ## Next Steps @@ -232,9 +226,8 @@ Build your own authentication system using TanStack Start's server functions and **Implementation Guides:** -- [Authentication Server Primitives](./authentication-server-primitives.md) — sessions, cookies, OAuth, CSRF, rate limiting (the server half) - [Authentication Patterns](./authentication.md) -- [Router Authentication Guide](/router/latest/docs/framework/react/guide/authenticated-routes) +- [Router Authentication Guide](/router/latest/docs/framework/react/guide/authenticated-routes.md) **Foundation Concepts:** diff --git a/docs/start/framework/react/guide/authentication-server-primitives.md b/docs/start/framework/react/guide/authentication-server-primitives.md deleted file mode 100644 index 103e9c4455..0000000000 --- a/docs/start/framework/react/guide/authentication-server-primitives.md +++ /dev/null @@ -1,351 +0,0 @@ ---- -id: authentication-server-primitives -title: Authentication Server Primitives ---- - -This guide covers the **server-side primitives** for building authentication in TanStack Start: session cookies, session lookup, OAuth, password-reset hardening, CSRF, and rate limiting. It pairs with the [routing-side guide](/router/latest/docs/framework/react/guide/authenticated-routes) (`_authenticated` layout, `beforeLoad`, redirects, RBAC). - -If you can use a managed solution like [Clerk](https://go.clerk.com/wOwHtuJ) or [WorkOS](https://workos.com/), prefer that — they handle most of what this guide describes. Read on if you're rolling your own. - -## Protect Data First - -Authentication has a data/API boundary and a route/UI layer. The data boundary is the security boundary: every server function, server route, or API endpoint that reads or writes private data must authorize the request before returning data or mutating state. - -- **Data/API boundary** (this guide): issue and verify session cookies, exchange OAuth codes, hash and verify passwords, rate-limit credential endpoints, defeat user enumeration, and authorize private data access. -- **Route/UI layer** (`router-core/auth-and-guards`): redirect unauthenticated users away from screens they cannot use, gate UI on roles/permissions, surface a login form, and avoid triggering requests that would fail anyway. - -> **A route guard is not a data authorization boundary.** Server functions and server routes are API endpoints; they are reachable independently of the route that calls them. Auth must be enforced in the handler or middleware for the endpoint that touches private data. `beforeLoad` is for route UX. - -## Session Cookies - -The default session storage is an HTTP-only cookie. The cookie can hold: - -- An **opaque session ID** that the server looks up in a database (recommended — easy to revoke). -- A **signed/encrypted token** that carries the session payload itself (stateless, but revocation is harder). - -Whichever you choose, the cookie flags matter: - -```ts -// src/server/session.ts -import { - deleteCookie, - getCookie, - setCookie, -} from '@tanstack/react-start/server' - -const SESSION_COOKIE = '__Host-session' -const ONE_DAY = 60 * 60 * 24 - -const sessionCookieOptions = { - httpOnly: true, - secure: true, - sameSite: 'lax', - path: '/', -} as const - -export function setSessionCookie(token: string) { - 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 | Why | -| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `HttpOnly` | JavaScript can't read the cookie. An XSS bug can't exfiltrate the session. | -| `Secure` | HTTPS only. Required when using the `__Host-` prefix. | -| `SameSite=Lax` | Sent on top-level navigations; blocks most cross-site CSRF on POST. Use `Strict` for higher-risk apps where loss of cross-site GET navigation is acceptable. | -| `__Host-` prefix | Binds the cookie to the exact origin. No `Domain` attribute, `Path=/`, `Secure` required. Defeats subdomain-takeover session fixation. | -| `Path=/` | Required by `__Host-`. | -| `Max-Age` | Bounded lifetime. Pair with server-side rotation. | - -## Session Lookup as Middleware - -Centralize session loading in middleware so every protected handler sees a typed session: - -```ts -// 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 to every protected server function: - -```ts -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 } }) - }) -``` - -## Login - -```ts -// 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: 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 } - }) -``` - -The `Invalid email or password` message is identical for "user not found" and "wrong password". The dummy-hash technique above also makes the timing identical: without it, the no-user branch returns instantly while the wrong-password branch spends ~100ms on the hash compare, leaking account existence over the wire. - -## Logout - -```ts -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 random `state` parameter — prevents CSRF on the callback. -- Generate a PKCE `code_verifier`/`code_challenge` pair — defends against authorization-code interception. -- Store both in a short-lived signed cookie keyed to this exact attempt. - -```ts -// 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' - -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: - -1. Read the cookie, verify its signature, and extract `state` + `verifier`. -2. Compare cookie-state to the `state` query param. If they don't match, abort. -3. Exchange the authorization code for an access token, sending `code_verifier` along with it. -4. Fetch the user profile, find/create the local user record, issue a session. -5. Clear the OAuth cookie. - -If any of those checks fail, the request did not originate from your `startOAuth` and must be rejected. - -## Password Reset: defeat user enumeration - -The reset endpoint must NOT tell the caller whether a given email is registered. Returning 200 vs 404 — or even different copy — leaks user existence to anyone who can hit the endpoint. - -```ts -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) - } - // Same response, same body, regardless of existence. - return { ok: true } - }) -``` - -Do NOT: - -- Return 200 if exists, 404 if not. -- Vary the 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 explicit defense: - -1. **GET-that-mutates** — never. Use POST/PUT/DELETE for any mutation. -2. **POST from a sibling subdomain** — `SameSite=Lax` does not block this; verify the `Origin` header matches your app. - -```ts -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 in `src/start.ts` global `requestMiddleware` so it runs on 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 per-account if you can identify the user) with a sliding window or token bucket. - -```ts -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 allowed = await rateLimiter.consume( - `rl:${opts.key}:${ip}`, - opts.max, - opts.windowMs, - ) - if (!allowed) throw new Error('Too many requests') - return next() - }) -} - -export const login = createServerFn({ method: 'POST' }).middleware([ - rateLimitMiddleware({ key: 'login', max: 5, windowMs: 60_000 }), -]) -// ... -``` - -## Session Rotation - -Whenever the user's privileges change — login, logout, password change, role grant — 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 the privilege change. - -```ts -// On login: revoke any pre-login session, create fresh. -await db.sessions.revokeAllForUser(user.id) -const token = await db.sessions.create({ userId: user.id }) -setSessionCookie(token) - -// On password change / role grant: -await db.sessions.revokeAllForUser(user.id) -const token = await db.sessions.create({ userId: user.id }) -setSessionCookie(token) -``` - -## Read Cookies and Env Per Request, Not at Module Scope - -Module-scope reads are wrong on two axes: - -- **Security:** they can be inlined into the client bundle. -- **Correctness on edge runtimes:** Cloudflare Workers (and others) inject env at request time. Module-level reads run before any request exists and evaluate to `undefined` even on the server. - -```ts -// ❌ Wrong -const SESSION_SECRET = process.env.SESSION_SECRET -export function signSession(payload) { - return sign(payload, SESSION_SECRET) -} - -// ✅ Right -export function signSession(payload) { - return sign(payload, process.env.SESSION_SECRET) -} -``` - -See [Execution Model: Module-Level `process.env` Reads](./execution-model.md#module-level-processenv-reads) for the full rule. - -## See Also - -- [Authentication Overview](./authentication-overview.md) — choosing between partner solutions, OSS libraries, and DIY. -- [Authenticated Routes (Router)](/router/latest/docs/framework/react/guide/authenticated-routes) — the routing-side guide. -- [Server Functions](./server-functions.md) — the RPC primitive that auth lives inside. -- [Middleware](./middleware.md) — composing `authMiddleware`. -- [OWASP Cheat Sheets — Authentication](https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html), [Session Management](https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html), [CSRF](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html). -- [MDN — Set-Cookie](https://developer.mozilla.org/docs/Web/HTTP/Headers/Set-Cookie). diff --git a/docs/start/framework/react/guide/authentication.md b/docs/start/framework/react/guide/authentication.md index c77c681ee0..f42fbc220f 100644 --- a/docs/start/framework/react/guide/authentication.md +++ b/docs/start/framework/react/guide/authentication.md @@ -1,12 +1,11 @@ --- id: authentication -title: Implement Authentication in React -description: Implement sessions, sign-in, sign-out, protected routes, and server-side authorization in a TanStack Start React app. +title: Authentication --- -Implement the authentication workflow in your React app, from sessions and sign-in to protected routes and authorization. +This guide covers authentication patterns and shows how to implement your own authentication system with TanStack Start. -To compare libraries and hosted services, read [Choose Authentication for React Apps](./authentication-overview.md). +> **📋 Before You Start:** Check our [Authentication Overview](./authentication-overview.md) for all available options including partner solutions and hosted services. ## Authentication Approaches @@ -35,9 +34,7 @@ Authentication involves many considerations including password security, session - **Authentication**: Who is this user? (Login/logout) - **Authorization**: What can this user do? (Permissions/roles) -TanStack Start provides server functions, request and cookie utilities, and route protection. Session storage and authentication come from your application or a library you choose. - -> Protect the data/API boundary first. Any server function, server route, or other API endpoint that returns or mutates private data must authorize the request itself. `beforeLoad` is useful for route UX: it keeps users out of screens they cannot use and avoids triggering work that would fail anyway. It is not the security boundary for the data. See [Authentication Server Primitives](./authentication-server-primitives.md) for the server-side pattern. +TanStack Start provides the tools for both through server functions, sessions, and route protection. ## Essential Building Blocks @@ -48,11 +45,10 @@ Server functions handle sensitive authentication logic securely on the server: ```tsx import { createServerFn } from '@tanstack/react-start' import { redirect } from '@tanstack/react-router' -import { getAppSession } from '~/utils/session' // Login server function export const loginFn = createServerFn({ method: 'POST' }) - .validator((data: { email: string; password: string }) => data) + .inputValidator((data: { email: string; password: string }) => data) .handler(async ({ data }) => { // Verify credentials (replace with your auth logic) const user = await authenticateUser(data.email, data.password) @@ -62,9 +58,11 @@ export const loginFn = createServerFn({ method: 'POST' }) } // Create session - const session = await getAppSession() - session.userId = user.id - await session.save() + const session = await useAppSession() + await session.update({ + userId: user.id, + email: user.email, + }) // Redirect to protected area throw redirect({ to: '/dashboard' }) @@ -72,131 +70,98 @@ export const loginFn = createServerFn({ method: 'POST' }) // Logout server function export const logoutFn = createServerFn({ method: 'POST' }).handler(async () => { - const session = await getAppSession() - session.destroy() + const session = await useAppSession() + await session.clear() throw redirect({ to: '/' }) }) // Get current user export const getCurrentUserFn = createServerFn({ method: 'GET' }).handler( async () => { - const session = await getAppSession() - const userId = session.userId + const session = await useAppSession() + const userId = session.data.userId if (!userId) { return null } - const user = await getUserById(userId) - return user ? { id: user.id, email: user.email, role: user.role } : null + return await getUserById(userId) }, ) ``` ### 2. Session Management -Start does not provide a session API. This guide uses iron-session for encrypted cookie sessions. Start's cookie helpers connect it to server functions, server routes, and request middleware. - -For encrypted cookie sessions, install [iron-session](https://github.com/vvo/iron-session): - -```sh -pnpm add iron-session -``` - -This example uses iron-session 9's cookie adapter. Its Node runtime requires Node 22.13 or newer; check the library's runtime requirements for other deployment targets. +TanStack Start provides secure HTTP-only cookie sessions: ```tsx -// utils/session.ts — import only from server code -import { getIronSession } from 'iron-session' -import { getCookie, setCookie } from '@tanstack/react-start/server' +// utils/session.ts +import { useSession } from '@tanstack/react-start/server' type SessionData = { - userId: string - oauthState: string + userId?: string + email?: string + role?: string } -export function getAppSession(ttl = 7 * 24 * 60 * 60) { - const password = process.env.SESSION_SECRET - if (!password || password.length < 32) { - throw new Error('SESSION_SECRET must be at least 32 characters') - } - - return getIronSession( - { read: getCookie, write: setCookie }, - { - cookieName: 'app-session', - password, - ttl, - cookieOptions: { - secure: process.env.NODE_ENV === 'production', - sameSite: 'lax', - httpOnly: true, - path: '/', - }, +export function useAppSession() { + return useSession({ + // Session configuration + name: 'app-session', + password: process.env.SESSION_SECRET!, // At least 32 characters + // Optional: customize cookie settings + cookie: { + secure: process.env.NODE_ENV === 'production', + sameSite: 'lax', + httpOnly: true, }, - ) + }) } ``` -Read fields directly from the returned session, change them, then `await session.save()` before returning or redirecting. Missing or expired sessions have no user ID. `session.destroy()` removes the browser cookie. Keep one session object for the operation; another call to `getAppSession()` reads the incoming request again. For middleware, pass that object through request context when downstream code needs the same mutations. - -The `getAppSession` helper belongs to your application. Start does not cache sessions, choose expiration rules, or synchronize concurrent writes. Keep secrets and session objects in server code, and read request-specific configuration inside the active request. - ### 3. Authentication Context -Load the current user in your root route's `beforeLoad` so the initial server render and child routes receive the same authentication state. `useServerFn` returns a callable function, not an object with `data`, `isLoading`, or `refetch`. You can call a server function directly from `beforeLoad`. - -Merge this pattern into your existing root route, keeping its metadata and document shell: +Share authentication state across your application: ```tsx -// routes/__root.tsx -import { - createRootRoute, - HeadContent, - Outlet, - Scripts, -} from '@tanstack/react-router' -import type { ReactNode } from 'react' +// contexts/auth.tsx +import { createContext, useContext, ReactNode } from 'react' +import { useServerFn } from '@tanstack/react-start' import { getCurrentUserFn } from '../server/auth' -export const Route = createRootRoute({ - headers: () => ({ 'Cache-Control': 'private, no-store' }), - beforeLoad: async () => ({ user: await getCurrentUserFn() }), - component: Outlet, - shellComponent: RootDocument, -}) +type User = { + id: string + email: string + role: string +} + +type AuthContextType = { + user: User | null + isLoading: boolean + refetch: () => void +} + +const AuthContext = createContext(undefined) + +export function AuthProvider({ children }: { children: ReactNode }) { + const { data: user, isLoading, refetch } = useServerFn(getCurrentUserFn) -function RootDocument({ children }: { children: ReactNode }) { return ( - - - - - - {children} - - - + + {children} + ) } -``` -The root includes session-specific data, so its responses use `Cache-Control: private, no-store`. Keep that policy on child routes that render this data, and do not override it with public caching at your CDN. - -Read that state from a descendant component: - -```tsx -// components/AuthStatus.tsx -import { Route } from '../routes/__root' - -export function AuthStatus() { - const { user } = Route.useRouteContext() - return {user ? user.email : 'Signed out'} +export function useAuth() { + const context = useContext(AuthContext) + if (!context) { + throw new Error('useAuth must be used within AuthProvider') + } + return context } ``` -After login or logout changes the session, call `await router.invalidate()` to reload the current user and rerun route guards. Keep private-data authorization in the server function itself, even when a route already checks the user. - ### 4. Route Protection Protect routes using `beforeLoad`: @@ -254,7 +219,9 @@ import { createServerFn } from '@tanstack/react-start' // User registration export const registerFn = createServerFn({ method: 'POST' }) - .validator((data: { email: string; password: string; name: string }) => data) + .inputValidator( + (data: { email: string; password: string; name: string }) => data, + ) .handler(async ({ data }) => { // Check if user exists const existingUser = await getUserByEmail(data.email) @@ -273,9 +240,8 @@ export const registerFn = createServerFn({ method: 'POST' }) }) // Create session - const session = await getAppSession() - session.userId = user.id - await session.save() + const session = await useAppSession() + await session.update({ userId: user.id }) return { success: true, user: { id: user.id, email: user.email } } }) @@ -337,15 +303,14 @@ export const authProviders = { } export const initiateOAuthFn = createServerFn({ method: 'POST' }) - .validator((data: { provider: 'google' | 'github' }) => data) + .inputValidator((data: { provider: 'google' | 'github' }) => data) .handler(async ({ data }) => { const provider = authProviders[data.provider] const state = generateRandomState() // Store state in session for CSRF protection - const session = await getAppSession() - session.oauthState = state - await session.save() + const session = await useAppSession() + await session.update({ oauthState: state }) // Generate OAuth URL const authUrl = generateOAuthUrl(provider, state) @@ -359,7 +324,7 @@ export const initiateOAuthFn = createServerFn({ method: 'POST' }) ```tsx // Password reset request export const requestPasswordResetFn = createServerFn({ method: 'POST' }) - .validator((data: { email: string }) => data) + .inputValidator((data: { email: string }) => data) .handler(async ({ data }) => { const user = await getUserByEmail(data.email) if (!user) { @@ -378,7 +343,7 @@ export const requestPasswordResetFn = createServerFn({ method: 'POST' }) // Password reset confirmation export const resetPasswordFn = createServerFn({ method: 'POST' }) - .validator((data: { token: string; newPassword: string }) => data) + .inputValidator((data: { token: string; newPassword: string }) => data) .handler(async ({ data }) => { const resetToken = await getPasswordResetToken(data.token) @@ -408,9 +373,21 @@ const hashedPassword = await bcrypt.hash(password, saltRounds) ### 2. Session Security -Set the library's server-validated expiration as well as appropriate cookie attributes. In the iron-session example, `ttl` limits a sealed credential's lifetime from its latest save; saving again renews it. A numeric `cookieOptions.maxAge` controls browser retention. In iron-session 9, explicitly setting `maxAge: undefined` also disables seal expiry; omit the property to use the configured `ttl`. Use an application-validated timestamp or a server-side record if you also need an absolute lifetime that writes cannot extend. - -Use `httpOnly`, `sameSite`, and `path` deliberately, and require `secure: true` on HTTPS deployments. These cookie attributes complement server-side authorization and CSRF protections. Keep only the minimum session data and load current account permissions from their authoritative store. Logout removes a stateless cookie from the current browser; it cannot revoke a copy without server-side state. +```tsx +// Use secure session configuration +export function useAppSession() { + return useSession({ + name: 'app-session', + password: process.env.SESSION_SECRET!, // 32+ characters + cookie: { + secure: process.env.NODE_ENV === 'production', // HTTPS only in production + sameSite: 'lax', // CSRF protection + httpOnly: true, // XSS protection + maxAge: 7 * 24 * 60 * 60, // 7 days + }, + }) +} +``` ### 3. Rate Limiting @@ -447,7 +424,7 @@ const loginSchema = z.object({ }) export const loginFn = createServerFn({ method: 'POST' }) - .validator((data) => loginSchema.parse(data)) + .inputValidator((data) => loginSchema.parse(data)) .handler(async ({ data }) => { // data is now validated }) @@ -512,69 +489,28 @@ describe('Authentication Flow', () => { ### Loading States -Call the function returned by `useServerFn` with `{ data }`. Track pending state in the component, handle invalid credentials, and refresh route context after a successful login. This form uses the `loginFn` from the server-functions example above. It requires JavaScript, so the fields stay disabled until hydration; `method="post"` also prevents credentials appearing in a native GET submission. - ```tsx -// components/LoginForm.tsx -import { useState } from 'react' -import type { FormEvent } from 'react' -import { useHydrated, useRouter } from '@tanstack/react-router' -import { useServerFn } from '@tanstack/react-start' -import { loginFn } from '../server/auth' - -export function LoginForm() { - const hydrated = useHydrated() +function LoginForm() { const [isLoading, setIsLoading] = useState(false) - const [error, setError] = useState('') - const login = useServerFn(loginFn) - const router = useRouter() - - const handleSubmit = async (event: FormEvent) => { - event.preventDefault() - const formData = new FormData(event.currentTarget) - const email = formData.get('email') - const password = formData.get('password') - if (typeof email !== 'string' || typeof password !== 'string') { - return - } + const loginMutation = useServerFn(loginFn) + const handleSubmit = async (data: LoginData) => { setIsLoading(true) - setError('') try { - const result = await login({ data: { email, password } }) - if (result?.error) { - setError(result.error) - return - } - await router.invalidate() - } catch { - setError('Login failed. Please try again.') + await loginMutation.mutate(data) + } catch (error) { + // Handle error } finally { setIsLoading(false) } } return ( - -
- - - -
-

{error}

+ + {/* Form fields */} + ) } @@ -584,19 +520,21 @@ export function LoginForm() { ```tsx export const loginFn = createServerFn({ method: 'POST' }) - .validator( + .inputValidator( (data: { email: string; password: string; rememberMe?: boolean }) => data, ) .handler(async ({ data }) => { const user = await authenticateUser(data.email, data.password) - if (!user) { - return { error: 'Invalid credentials' } - } + if (!user) return { error: 'Invalid credentials' } - const ttl = data.rememberMe ? 30 * 24 * 60 * 60 : 8 * 60 * 60 - const session = await getAppSession(ttl) - session.userId = user.id - await session.save() + const session = await useAppSession() + await session.update( + { userId: user.id }, + { + // Extend session if remember me is checked + maxAge: data.rememberMe ? 30 * 24 * 60 * 60 : undefined, // 30 days vs session + }, + ) return { success: true } }) @@ -624,6 +562,7 @@ If you're migrating from client-side authentication (localStorage, context only) ### From Other Frameworks - **Next.js**: Replace API routes with server functions, migrate NextAuth sessions +- **Remix**: Convert loaders/actions to server functions, adapt session patterns - **SvelteKit**: Move form actions to server functions, update route protection ## Production Considerations diff --git a/docs/start/framework/react/guide/cdn-asset-urls.md b/docs/start/framework/react/guide/cdn-asset-urls.md index ac5f3e7b57..977c030c68 100644 --- a/docs/start/framework/react/guide/cdn-asset-urls.md +++ b/docs/start/framework/react/guide/cdn-asset-urls.md @@ -3,26 +3,25 @@ id: cdn-asset-urls title: CDN Asset URLs --- -> **Experimental:** `transformAssets` is experimental and subject to change. +# CDN Asset URLs -Use this guide when you need TanStack Start to rewrite manifest-managed asset URLs at runtime. The most common use case is serving JavaScript and CSS from a CDN whose origin is known only when the server starts, or varies per request. +> **Experimental:** `transformAssetUrls` is experimental and subject to change. -This guide is about asset URL rewriting. For choosing CSS import patterns and configuring CSS inlining, see the [CSS Styling guide](./css-styling). +When deploying to production, you may want to serve your static assets (JavaScript, CSS) from a CDN. The `transformAssetUrls` option on `createStartHandler` lets you rewrite asset URLs at runtime — for example, prepending a CDN origin that is only known when the server starts. -## What `transformAssets` Rewrites +## Why Runtime URL Rewriting? -The `transformAssets` option on `createStartHandler` rewrites URLs that Start manages in its SSR manifest: +Vite's `base` config is evaluated at build time. If your CDN URL is determined at deploy time (via environment variables, dynamic configuration, etc.), you need a way to rewrite URLs at runtime. `transformAssetUrls` solves this for the URLs that TanStack Start manages in its manifest: -- JavaScript preload links (`` for module output, or `` for IIFE output) -- `` tags for manifest-managed CSS -- The client entry script URL -- `url(...)` and `@import` URLs inside [inlined CSS](./css-styling#inline-route-css-in-production) when CSS URL templates are enabled +- `` tags (JS preloads) +- `` tags (CSS) +- The client entry ` - - - diff --git a/e2e/react-router/issue-4759/package.json b/e2e/react-router/issue-4759/package.json deleted file mode 100644 index ee6a105ad5..0000000000 --- a/e2e/react-router/issue-4759/package.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "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 deleted file mode 100644 index a301f62881..0000000000 --- a/e2e/react-router/issue-4759/playwright.config.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' - -const PORT = Number(process.env.E2E_APP_PORT ?? 0) -const baseURL = `http://localhost:${PORT}` - -export default defineConfig({ - testDir: './tests', - workers: 1, - reporter: [['line']], - 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 deleted file mode 100644 index e251178045..0000000000 --- a/e2e/react-router/issue-4759/src/main.tsx +++ /dev/null @@ -1,74 +0,0 @@ -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 deleted file mode 100644 index 95689010c8..0000000000 --- a/e2e/react-router/issue-4759/tests/issue-4759.spec.ts +++ /dev/null @@ -1,39 +0,0 @@ -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 deleted file mode 100644 index e4ba4788a3..0000000000 --- a/e2e/react-router/issue-4759/tsconfig.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "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 deleted file mode 100644 index 9ffcc67574..0000000000 --- a/e2e/react-router/issue-4759/vite.config.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 04a3530c9d..0000000000 --- a/e2e/react-router/issue-7120/index.html +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - Issues 7120 and 7367 - - - - diff --git a/e2e/react-router/issue-7120/package.json b/e2e/react-router/issue-7120/package.json deleted file mode 100644 index 979b32556c..0000000000 --- a/e2e/react-router/issue-7120/package.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "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 deleted file mode 100644 index a8ba116fb4..0000000000 --- a/e2e/react-router/issue-7120/playwright.config.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' - -const PORT = Number(process.env.E2E_APP_PORT ?? 0) -const baseURL = `http://localhost:${PORT}` - -export default defineConfig({ - testDir: './tests', - workers: 1, - reporter: [['line']], - 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 deleted file mode 100644 index 0c983251af..0000000000 --- a/e2e/react-router/issue-7120/src/main.tsx +++ /dev/null @@ -1,21 +0,0 @@ -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 deleted file mode 100644 index 399d303aac..0000000000 --- a/e2e/react-router/issue-7120/src/redirectGate.ts +++ /dev/null @@ -1,35 +0,0 @@ -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 deleted file mode 100644 index e8c6d92110..0000000000 --- a/e2e/react-router/issue-7120/src/routeTree.gen.ts +++ /dev/null @@ -1,77 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 2f01516a55..0000000000 --- a/e2e/react-router/issue-7120/src/routes/__root.tsx +++ /dev/null @@ -1,33 +0,0 @@ -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 deleted file mode 100644 index 1626ce706b..0000000000 --- a/e2e/react-router/issue-7120/src/routes/index.tsx +++ /dev/null @@ -1,5 +0,0 @@ -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 deleted file mode 100644 index dc0b0cfd7f..0000000000 --- a/e2e/react-router/issue-7120/src/routes/posts.lazy.tsx +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index cc0519b74e..0000000000 --- a/e2e/react-router/issue-7120/src/routes/posts.tsx +++ /dev/null @@ -1,3 +0,0 @@ -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 deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/react-router/issue-7120/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// 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 deleted file mode 100644 index 081ae73691..0000000000 --- a/e2e/react-router/issue-7120/tests/issue-7120.repro.spec.ts +++ /dev/null @@ -1,33 +0,0 @@ -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 deleted file mode 100644 index 4f6089bc08..0000000000 --- a/e2e/react-router/issue-7120/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "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 deleted file mode 100644 index 5b1c613906..0000000000 --- a/e2e/react-router/issue-7120/vite.config.ts +++ /dev/null @@ -1,7 +0,0 @@ -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 deleted file mode 100644 index 76369b5957..0000000000 --- a/e2e/react-router/issue-7457/index.html +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - Issue 7457 - - - - diff --git a/e2e/react-router/issue-7457/package.json b/e2e/react-router/issue-7457/package.json deleted file mode 100644 index 838f5173e2..0000000000 --- a/e2e/react-router/issue-7457/package.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "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 deleted file mode 100644 index a8ba116fb4..0000000000 --- a/e2e/react-router/issue-7457/playwright.config.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' - -const PORT = Number(process.env.E2E_APP_PORT ?? 0) -const baseURL = `http://localhost:${PORT}` - -export default defineConfig({ - testDir: './tests', - workers: 1, - reporter: [['line']], - 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 deleted file mode 100644 index 1b6805edc0..0000000000 --- a/e2e/react-router/issue-7457/src/main.tsx +++ /dev/null @@ -1,32 +0,0 @@ -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 deleted file mode 100644 index 04a2c94ce8..0000000000 --- a/e2e/react-router/issue-7457/src/routeTree.gen.ts +++ /dev/null @@ -1,77 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 988ba76263..0000000000 --- a/e2e/react-router/issue-7457/src/routes/__root.tsx +++ /dev/null @@ -1,25 +0,0 @@ -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 deleted file mode 100644 index 6b6caa55b3..0000000000 --- a/e2e/react-router/issue-7457/src/routes/another.tsx +++ /dev/null @@ -1,5 +0,0 @@ -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 deleted file mode 100644 index daaae2aeed..0000000000 --- a/e2e/react-router/issue-7457/src/routes/index.tsx +++ /dev/null @@ -1,8 +0,0 @@ -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 deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/react-router/issue-7457/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// 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 deleted file mode 100644 index 8b20fac1eb..0000000000 --- a/e2e/react-router/issue-7457/tests/issue-7457.repro.spec.ts +++ /dev/null @@ -1,35 +0,0 @@ -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 deleted file mode 100644 index 4f6089bc08..0000000000 --- a/e2e/react-router/issue-7457/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "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 deleted file mode 100644 index 9e39ea83d9..0000000000 --- a/e2e/react-router/issue-7457/vite.config.js +++ /dev/null @@ -1,10 +0,0 @@ -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/package.json b/e2e/react-router/js-only-file-based/package.json index 39742d9c84..a0ad89695d 100644 --- a/e2e/react-router/js-only-file-based/package.json +++ b/e2e/react-router/js-only-file-based/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -16,16 +16,16 @@ "@tanstack/react-router-devtools": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "catalog:", + "redaxios": "^0.5.1", "tailwindcss": "^4.2.2" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", "@tanstack/router-plugin": "workspace:^", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "vite": "^8.0.14" + "vite": "^8.0.0" } } diff --git a/e2e/react-router/js-only-file-based/playwright.config.ts b/e2e/react-router/js-only-file-based/playwright.config.ts index 0925936d55..4f93bc1413 100644 --- a/e2e/react-router/js-only-file-based/playwright.config.ts +++ b/e2e/react-router/js-only-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -13,15 +18,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-router/js-only-file-based/src/posts.js b/e2e/react-router/js-only-file-based/src/posts.js index 36c1c281f6..979e5e381c 100644 --- a/e2e/react-router/js-only-file-based/src/posts.js +++ b/e2e/react-router/js-only-file-based/src/posts.js @@ -2,7 +2,11 @@ import axios from 'redaxios' export class NotFoundError extends Error {} -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPosts = async () => { console.info('Fetching posts...') diff --git a/e2e/react-router/js-only-file-based/src/routeTree.gen.js b/e2e/react-router/js-only-file-based/src/routeTree.gen.js index 80683abb30..f2d42e5a6c 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,20 +9,15 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as PostsRouteRouteImport } from './routes/posts.route' -import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-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 PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +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' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -}) const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, @@ -32,11 +27,11 @@ const PostsRouteRoute = PostsRouteRouteImport.update({ path: '/posts', getParentRoute: () => rootRouteImport, }) -const PathlessLayoutNestedLayoutRoute = - PathlessLayoutNestedLayoutRouteImport.update({ - id: '/_nested-layout', - getParentRoute: () => PathlessLayoutRoute, - }) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +}) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -47,11 +42,10 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ path: '/$postId', getParentRoute: () => PostsRouteRoute, }) -const PathlessLayoutNestedLayoutRouteARoute = - PathlessLayoutNestedLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, +const PathlessLayoutNestedLayoutRoute = + PathlessLayoutNestedLayoutRouteImport.update({ + id: '/_nested-layout', + getParentRoute: () => PathlessLayoutRoute, }) const PathlessLayoutNestedLayoutRouteBRoute = PathlessLayoutNestedLayoutRouteBRouteImport.update({ @@ -59,6 +53,12 @@ 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/vite-env.d.ts b/e2e/react-router/js-only-file-based/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/react-router/js-only-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/react-router/js-only-file-based/tests/app.spec.ts b/e2e/react-router/js-only-file-based/tests/app.spec.ts index ced5ac9310..5a83a314f2 100644 --- a/e2e/react-router/js-only-file-based/tests/app.spec.ts +++ b/e2e/react-router/js-only-file-based/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/react-router/js-only-file-based/tests/setup/global.setup.ts b/e2e/react-router/js-only-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/js-only-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/react-router/js-only-file-based/tests/setup/global.teardown.ts b/e2e/react-router/js-only-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/js-only-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-router/match-params/.gitignore b/e2e/react-router/match-params/.gitignore deleted file mode 100644 index 4d2da67b50..0000000000 --- a/e2e/react-router/match-params/.gitignore +++ /dev/null @@ -1,11 +0,0 @@ -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 deleted file mode 100644 index cee534dbdb..0000000000 --- a/e2e/react-router/match-params/index.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - Match Params - - -
- - - diff --git a/e2e/react-router/match-params/package.json b/e2e/react-router/match-params/package.json deleted file mode 100644 index 908be67a9d..0000000000 --- a/e2e/react-router/match-params/package.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "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 deleted file mode 100644 index 9e8c1fab2b..0000000000 --- a/e2e/react-router/match-params/playwright.config.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' - -const PORT = Number(process.env.E2E_APP_PORT ?? 0) -const baseURL = `http://localhost:${PORT}` - -export default defineConfig({ - testDir: './tests', - workers: 1, - reporter: [['line']], - 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 deleted file mode 100644 index 33709cfcc2..0000000000 --- a/e2e/react-router/match-params/src/main.tsx +++ /dev/null @@ -1,229 +0,0 @@ -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 deleted file mode 100644 index 9b57061911..0000000000 --- a/e2e/react-router/match-params/tests/match-params.spec.ts +++ /dev/null @@ -1,81 +0,0 @@ -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 deleted file mode 100644 index 4f6089bc08..0000000000 --- a/e2e/react-router/match-params/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "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 deleted file mode 100644 index 4f1b25a0c3..0000000000 --- a/e2e/react-router/match-params/vite.config.js +++ /dev/null @@ -1,3 +0,0 @@ -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 deleted file mode 100644 index 0c5b6b471c..0000000000 --- a/e2e/react-router/react-compiler/index.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - React Compiler useMatchRoute test - - -
- - - diff --git a/e2e/react-router/react-compiler/package.json b/e2e/react-router/react-compiler/package.json deleted file mode 100644 index 82e6fbf86b..0000000000 --- a/e2e/react-router/react-compiler/package.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "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 deleted file mode 100644 index a8ba116fb4..0000000000 --- a/e2e/react-router/react-compiler/playwright.config.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' - -const PORT = Number(process.env.E2E_APP_PORT ?? 0) -const baseURL = `http://localhost:${PORT}` - -export default defineConfig({ - testDir: './tests', - workers: 1, - reporter: [['line']], - 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 deleted file mode 100644 index e6e549da83..0000000000 --- a/e2e/react-router/react-compiler/src/main.tsx +++ /dev/null @@ -1,73 +0,0 @@ -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 deleted file mode 100644 index b800e3c908..0000000000 --- a/e2e/react-router/react-compiler/tests/use-match-route.spec.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 4f6089bc08..0000000000 --- a/e2e/react-router/react-compiler/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "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 deleted file mode 100644 index b4478aced4..0000000000 --- a/e2e/react-router/react-compiler/vite.config.js +++ /dev/null @@ -1,7 +0,0 @@ -import { defineConfig } from 'vite' -import react, { reactCompilerPreset } from '@vitejs/plugin-react' -import babel from '@rolldown/plugin-babel' - -export default defineConfig({ - plugins: [react(), babel({ presets: [reactCompilerPreset()] })], -}) diff --git a/e2e/react-router/rspack-basic-file-based/package.json b/e2e/react-router/rspack-basic-file-based/package.json index 5ec9ed9862..e276a82cf1 100644 --- a/e2e/react-router/rspack-basic-file-based/package.json +++ b/e2e/react-router/rspack-basic-file-based/package.json @@ -7,19 +7,19 @@ "build": "rsbuild build && tsc --noEmit", "preview": "rsbuild preview", "start": "rsbuild preview", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", "@tanstack/react-router-devtools": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "catalog:" + "redaxios": "^0.5.1" }, "devDependencies": { - "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", - "@rsbuild/plugin-react": "^2.0.0", + "@playwright/test": "^1.50.1", + "@rsbuild/core": "^1.2.4", + "@rsbuild/plugin-react": "^1.1.0", "@tailwindcss/postcss": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@tanstack/router-plugin": "workspace:^", @@ -27,7 +27,6 @@ "@types/react-dom": "^19.0.3", "postcss": "^8.5.1", "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2" + "typescript": "^5.7.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 4eead86444..decceaef2f 100644 --- a/e2e/react-router/rspack-basic-file-based/playwright.config.ts +++ b/e2e/react-router/rspack-basic-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `PUBLIC_NODE_ENV="test" PUBLIC_EXTERNAL_PORT=${EXTERNAL_PORT} PUBLIC_SERVER_PORT=${PORT} pnpm build && PUBLIC_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-router/rspack-basic-file-based/src/posts.tsx b/e2e/react-router/rspack-basic-file-based/src/posts.tsx index 97c96d77eb..a1225b7fe7 100644 --- a/e2e/react-router/rspack-basic-file-based/src/posts.tsx +++ b/e2e/react-router/rspack-basic-file-based/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.PUBLIC_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.PUBLIC_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/react-router/rspack-basic-file-based/src/vite-env.d.ts b/e2e/react-router/rspack-basic-file-based/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/react-router/rspack-basic-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/react-router/rspack-basic-file-based/tests/app.spec.ts b/e2e/react-router/rspack-basic-file-based/tests/app.spec.ts index d230263bfe..10beff655f 100644 --- a/e2e/react-router/rspack-basic-file-based/tests/app.spec.ts +++ b/e2e/react-router/rspack-basic-file-based/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/react-router/rspack-basic-file-based/tests/setup/global.setup.ts b/e2e/react-router/rspack-basic-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/rspack-basic-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/react-router/rspack-basic-file-based/tests/setup/global.teardown.ts b/e2e/react-router/rspack-basic-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/rspack-basic-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-router/rspack-basic-file-based/tsconfig.json b/e2e/react-router/rspack-basic-file-based/tsconfig.json index 2f5f67eac7..76f578eb54 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", "tests"], + "include": ["src", "playwright.config.ts", "tests"], "exclude": ["node_modules", "dist"] } diff --git a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/package.json b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/package.json index 30c62d0af1..d4ca0606f1 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,19 +7,19 @@ "build": "rsbuild build && tsc --noEmit", "preview": "rsbuild preview", "start": "rsbuild preview", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", "@tanstack/react-router-devtools": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "catalog:" + "redaxios": "^0.5.1" }, "devDependencies": { - "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", - "@rsbuild/plugin-react": "^2.0.0", + "@playwright/test": "^1.50.1", + "@rsbuild/core": "^1.2.4", + "@rsbuild/plugin-react": "^1.1.0", "@tailwindcss/postcss": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@tanstack/router-plugin": "workspace:^", @@ -28,7 +28,6 @@ "@types/react-dom": "^19.0.3", "postcss": "^8.5.1", "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2" + "typescript": "^5.7.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 1c1d021f2f..bf3adc082c 100644 --- a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/playwright.config.ts +++ b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm start --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `PUBLIC_NODE_ENV="test" PUBLIC_EXTERNAL_PORT=${EXTERNAL_PORT} PUBLIC_SERVER_PORT=${PORT} pnpm build && PUBLIC_SERVER_PORT=${PORT} pnpm start --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/src/posts.tsx b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/src/posts.tsx index cc3cb0f9c8..b196982420 100644 --- a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/src/posts.tsx +++ b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.PUBLIC_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.PUBLIC_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/src/vite-env.d.ts b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts index 8b808782f6..a689f459e3 100644 --- a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts +++ b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-router/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 a32f07a8ef..7dc6d51cf9 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", "tests", "./routes.ts"], + "include": ["src", "playwright.config.ts", "tests", "./routes.ts"], "exclude": ["node_modules", "dist"] } diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/package.json b/e2e/react-router/scroll-restoration-sandbox-vite/package.json index 51e9e70cc5..d0e2ff534f 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/package.json +++ b/e2e/react-router/scroll-restoration-sandbox-vite/package.json @@ -11,35 +11,26 @@ "start": "vite", "test:e2e:browser": "VITE_APP_HISTORY=browser playwright test --config=playwright.browser.config.ts --project=chromium", "test:e2e:hash": "VITE_APP_HISTORY=hash playwright test --config=playwright.hash.config.ts --project=chromium", - "test:e2e": "pnpm run test:e2e:browser && pnpm run test:e2e:hash" + "test:e2e": "rm -rf port*.txt; pnpm run test:e2e:browser && pnpm run test:e2e:hash" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/react-router": "workspace:^", "@tanstack/react-router-devtools": "workspace:^", "@tanstack/router-plugin": "workspace:^", + "@tanstack/zod-adapter": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "catalog:", + "redaxios": "^0.5.1", "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "vite": "^8.0.14" - }, - "nx": { - "targets": { - "test:e2e": { - "outputs": [ - "...", - "{projectRoot}/dist-hash" - ] - } - } + "vite": "^8.0.0" } } diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts b/e2e/react-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts index eb31d94080..972124647c 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts +++ b/e2e/react-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts @@ -1,7 +1,15 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, + resolveRuntimeSuffix, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort( + packageJson.name + `-${resolveRuntimeSuffix('browser')}`, +) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -13,15 +21,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_APP_HISTORY=browser pnpm build && VITE_APP_HISTORY=browser pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} VITE_APP_HISTORY=browser pnpm build && VITE_SERVER_PORT=${PORT} VITE_APP_HISTORY=browser pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts b/e2e/react-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts index 6b160e3908..a6fa77afbf 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts +++ b/e2e/react-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts @@ -1,7 +1,15 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, + resolveRuntimeSuffix, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort( + packageJson.name + `-${resolveRuntimeSuffix('hash')}`, +) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -13,15 +21,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_APP_HISTORY=hash vite build --outDir dist-hash && VITE_APP_HISTORY=hash pnpm preview --port ${PORT} --outDir dist-hash`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} VITE_APP_HISTORY=hash vite build --outDir dist-hash && VITE_SERVER_PORT=${PORT} VITE_APP_HISTORY=hash pnpm preview --port ${PORT} --outDir dist-hash`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/src/posts.tsx b/e2e/react-router/scroll-restoration-sandbox-vite/src/posts.tsx index c4a2d0dcca..e45ef52969 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/src/posts.tsx +++ b/e2e/react-router/scroll-restoration-sandbox-vite/src/posts.tsx @@ -10,7 +10,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export class PostNotFoundError extends Error {} diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/src/routeTree.gen.ts b/e2e/react-router/scroll-restoration-sandbox-vite/src/routeTree.gen.ts index 0c6823c368..6664a9ddf7 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/src/routeTree.gen.ts +++ b/e2e/react-router/scroll-restoration-sandbox-vite/src/routeTree.gen.ts @@ -12,12 +12,10 @@ import { createFileRoute } from '@tanstack/react-router' import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' -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' +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' const testsVirtualPageLazyRouteImport = createFileRoute( '/(tests)/virtual-page', @@ -28,23 +26,23 @@ const IndexRoute = IndexRouteImport.update({ path: '/', getParentRoute: () => rootRouteImport, } as any) -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 +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)) +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) const testsLazyWithLoaderPageRoute = testsLazyWithLoaderPageRouteImport .update({ id: '/(tests)/lazy-with-loader-page', @@ -54,28 +52,16 @@ const testsLazyWithLoaderPageRoute = testsLazyWithLoaderPageRouteImport .lazy(() => import('./routes/(tests)/lazy-with-loader-page.lazy').then((d) => d.Route), ) -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 +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)) + .lazy(() => import('./routes/(tests)/lazy-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 @@ -84,8 +70,6 @@ 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 @@ -95,8 +79,6 @@ 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 @@ -107,8 +89,6 @@ export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath fullPaths: | '/' - | '/issue-7040-source' - | '/issue-7040-target' | '/lazy-page' | '/lazy-with-loader-page' | '/normal-page' @@ -117,8 +97,6 @@ export interface FileRouteTypes { fileRoutesByTo: FileRoutesByTo to: | '/' - | '/issue-7040-source' - | '/issue-7040-target' | '/lazy-page' | '/lazy-with-loader-page' | '/normal-page' @@ -127,8 +105,6 @@ export interface FileRouteTypes { id: | '__root__' | '/' - | '/(tests)/issue-7040-source' - | '/(tests)/issue-7040-target' | '/(tests)/lazy-page' | '/(tests)/lazy-with-loader-page' | '/(tests)/normal-page' @@ -138,8 +114,6 @@ export interface FileRouteTypes { } export interface RootRouteChildren { IndexRoute: typeof IndexRoute - testsIssue7040SourceRoute: typeof testsIssue7040SourceRoute - testsIssue7040TargetRoute: typeof testsIssue7040TargetRoute testsLazyPageRoute: typeof testsLazyPageRoute testsLazyWithLoaderPageRoute: typeof testsLazyWithLoaderPageRoute testsNormalPageRoute: typeof testsNormalPageRoute @@ -156,39 +130,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/(tests)/issue-7040-source': { - id: '/(tests)/issue-7040-source' - path: '/issue-7040-source' - fullPath: '/issue-7040-source' - preLoaderRoute: typeof testsIssue7040SourceRouteImport - parentRoute: typeof rootRouteImport - } - '/(tests)/issue-7040-target': { - id: '/(tests)/issue-7040-target' - path: '/issue-7040-target' - fullPath: '/issue-7040-target' - preLoaderRoute: typeof testsIssue7040TargetRouteImport - parentRoute: typeof rootRouteImport - } - '/(tests)/lazy-page': { - id: '/(tests)/lazy-page' - path: '/lazy-page' - fullPath: '/lazy-page' - preLoaderRoute: typeof testsLazyPageRouteImport - parentRoute: typeof rootRouteImport - } - '/(tests)/lazy-with-loader-page': { - id: '/(tests)/lazy-with-loader-page' - path: '/lazy-with-loader-page' - fullPath: '/lazy-with-loader-page' - preLoaderRoute: typeof testsLazyWithLoaderPageRouteImport - parentRoute: typeof rootRouteImport - } - '/(tests)/normal-page': { - id: '/(tests)/normal-page' - path: '/normal-page' - fullPath: '/normal-page' - preLoaderRoute: typeof testsNormalPageRouteImport + '/(tests)/virtual-page': { + id: '/(tests)/virtual-page' + path: '/virtual-page' + fullPath: '/virtual-page' + preLoaderRoute: typeof testsVirtualPageLazyRouteImport parentRoute: typeof rootRouteImport } '/(tests)/page-with-search': { @@ -198,11 +144,25 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof testsPageWithSearchRouteImport parentRoute: typeof rootRouteImport } - '/(tests)/virtual-page': { - id: '/(tests)/virtual-page' - path: '/virtual-page' - fullPath: '/virtual-page' - preLoaderRoute: typeof testsVirtualPageLazyRouteImport + '/(tests)/normal-page': { + id: '/(tests)/normal-page' + path: '/normal-page' + fullPath: '/normal-page' + preLoaderRoute: typeof testsNormalPageRouteImport + parentRoute: typeof rootRouteImport + } + '/(tests)/lazy-with-loader-page': { + id: '/(tests)/lazy-with-loader-page' + path: '/lazy-with-loader-page' + fullPath: '/lazy-with-loader-page' + preLoaderRoute: typeof testsLazyWithLoaderPageRouteImport + parentRoute: typeof rootRouteImport + } + '/(tests)/lazy-page': { + id: '/(tests)/lazy-page' + path: '/lazy-page' + fullPath: '/lazy-page' + preLoaderRoute: typeof testsLazyPageRouteImport parentRoute: typeof rootRouteImport } } @@ -210,8 +170,6 @@ declare module '@tanstack/react-router' { 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 deleted file mode 100644 index 3c1702a942..0000000000 --- a/e2e/react-router/scroll-restoration-sandbox-vite/src/routes/(tests)/issue-7040-source.tsx +++ /dev/null @@ -1,49 +0,0 @@ -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 deleted file mode 100644 index df541c6dbb..0000000000 --- a/e2e/react-router/scroll-restoration-sandbox-vite/src/routes/(tests)/issue-7040-target.tsx +++ /dev/null @@ -1,40 +0,0 @@ -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 427b6f12b0..d9591671f5 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,9 +1,10 @@ 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: z.object({ where: z.string() }), + validateSearch: zodValidator(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 ed80300a68..18726e1168 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,8 +45,6 @@ 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/vite-env.d.ts b/e2e/react-router/scroll-restoration-sandbox-vite/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/react-router/scroll-restoration-sandbox-vite/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/tests/app.spec.ts b/e2e/react-router/scroll-restoration-sandbox-vite/tests/app.spec.ts index e396c28686..6b59842625 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,23 +1,7 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' import { linkOptions } from '@tanstack/react-router' import { toRuntimePath } from '@tanstack/router-e2e-utils' -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( @@ -25,236 +9,6 @@ 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 deleted file mode 100644 index 2db25517c8..0000000000 --- a/e2e/react-router/scroll-restoration-sandbox-vite/tests/issue-7040.repro.spec.ts +++ /dev/null @@ -1,152 +0,0 @@ -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 new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/scroll-restoration-sandbox-vite/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/tests/setup/global.teardown.ts b/e2e/react-router/scroll-restoration-sandbox-vite/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/scroll-restoration-sandbox-vite/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/tsconfig.json b/e2e/react-router/scroll-restoration-sandbox-vite/tsconfig.json index 5d58406b2e..f33b5a7aa3 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/tsconfig.json +++ b/e2e/react-router/scroll-restoration-sandbox-vite/tsconfig.json @@ -11,5 +11,5 @@ "allowJs": true, "types": ["vite/client", "node"] }, - "exclude": ["node_modules", "dist", "dist-hash"] + "exclude": ["node_modules", "dist"] } diff --git a/e2e/react-router/sentry-integration/package.json b/e2e/react-router/sentry-integration/package.json index 5ebbdf31d9..d11ee604aa 100644 --- a/e2e/react-router/sentry-integration/package.json +++ b/e2e/react-router/sentry-integration/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@sentry/react": "^10.32.0", @@ -19,15 +19,15 @@ "@tanstack/react-router-devtools": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "catalog:", + "redaxios": "^0.5.1", "tailwindcss": "^4.2.2" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@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" + "vite": "^8.0.0" } } diff --git a/e2e/react-router/sentry-integration/playwright.config.ts b/e2e/react-router/sentry-integration/playwright.config.ts index 6a684ac89e..0c5cee43e4 100644 --- a/e2e/react-router/sentry-integration/playwright.config.ts +++ b/e2e/react-router/sentry-integration/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-router/sentry-integration/src/vite-env.d.ts b/e2e/react-router/sentry-integration/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/react-router/sentry-integration/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/react-router/view-transitions/package.json b/e2e/react-router/view-transitions/package.json index e2d7a181e1..bfba8a5de7 100644 --- a/e2e/react-router/view-transitions/package.json +++ b/e2e/react-router/view-transitions/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -17,18 +17,17 @@ "@tanstack/router-plugin": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "catalog:", + "redaxios": "^0.5.1", "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", "@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" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/e2e/react-router/view-transitions/playwright.config.ts b/e2e/react-router/view-transitions/playwright.config.ts index 4eead86444..c5de6b5611 100644 --- a/e2e/react-router/view-transitions/playwright.config.ts +++ b/e2e/react-router/view-transitions/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,10 +22,13 @@ export default defineConfig({ baseURL, }, + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-router/view-transitions/src/routeTree.gen.ts b/e2e/react-router/view-transitions/src/routeTree.gen.ts index 8982fca68f..20ee76a1a5 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 IndexRouteImport } from './routes/index' -import { Route as ExploreRouteImport } from './routes/explore' 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 PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const HowItWorksRoute = HowItWorksRouteImport.update({ + id: '/how-it-works', + path: '/how-it-works', 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 { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/how-it-works': { + id: '/how-it-works' + path: '/how-it-works' + fullPath: '/how-it-works' + preLoaderRoute: typeof HowItWorksRouteImport parentRoute: typeof rootRouteImport } '/explore': { @@ -115,13 +115,6 @@ 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' @@ -129,6 +122,13 @@ 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/vite-env.d.ts b/e2e/react-router/view-transitions/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/react-router/view-transitions/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/react-router/view-transitions/tests/app.spec.ts b/e2e/react-router/view-transitions/tests/app.spec.ts index 6c1ccf1a6e..472bd6ed0b 100644 --- a/e2e/react-router/view-transitions/tests/app.spec.ts +++ b/e2e/react-router/view-transitions/tests/app.spec.ts @@ -1,4 +1,4 @@ -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/react-router/view-transitions/tests/setup/global.setup.ts b/e2e/react-router/view-transitions/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/view-transitions/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/react-router/view-transitions/tests/setup/global.teardown.ts b/e2e/react-router/view-transitions/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/view-transitions/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-start/basic-auth/package.json b/e2e/react-start/basic-auth/package.json index f7ff609e76..e00c3fd2a2 100644 --- a/e2e/react-start/basic-auth/package.json +++ b/e2e/react-start/basic-auth/package.json @@ -10,7 +10,7 @@ "preview": "vite preview", "start": "node .output/server/index.mjs", "prisma-generate": "prisma generate", - "test:e2e": "exit 0; pnpm run prisma-generate && playwright test --project=chromium" + "test:e2e": "exit 0; rm -rf port*.txt; pnpm run prisma-generate && playwright test --project=chromium" }, "dependencies": { "@libsql/client": "^0.15.15", @@ -19,14 +19,14 @@ "@tanstack/react-router": "workspace:^", "@tanstack/react-router-devtools": "workspace:^", "@tanstack/react-start": "workspace:^", - "iron-session": "^9.0.1", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "catalog:", - "tailwind-merge": "^3.6.0" + "redaxios": "^0.5.1", + "tailwind-merge": "^2.6.0", + "vite": "^8.0.0" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", @@ -36,8 +36,6 @@ "dotenv": "^17.2.3", "prisma": "^7.0.0", "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "typescript": "^5.7.2" } } diff --git a/e2e/react-start/basic-auth/playwright.config.ts b/e2e/react-start/basic-auth/playwright.config.ts index 82678ac00b..18b8905468 100644 --- a/e2e/react-start/basic-auth/playwright.config.ts +++ b/e2e/react-start/basic-auth/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/basic-auth/src/components/DefaultCatchBoundary.tsx b/e2e/react-start/basic-auth/src/components/DefaultCatchBoundary.tsx index 405fb5f4a7..ef2daa1ea1 100644 --- a/e2e/react-start/basic-auth/src/components/DefaultCatchBoundary.tsx +++ b/e2e/react-start/basic-auth/src/components/DefaultCatchBoundary.tsx @@ -1,15 +1,17 @@ import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, 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 === '/', + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, }) console.error(error) diff --git a/e2e/react-start/basic-auth/src/routeTree.gen.ts b/e2e/react-start/basic-auth/src/routeTree.gen.ts index 998d34a709..6be84444eb 100644 --- a/e2e/react-start/basic-auth/src/routeTree.gen.ts +++ b/e2e/react-start/basic-auth/src/routeTree.gen.ts @@ -9,27 +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 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 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 AuthedPostsRouteImport } from './routes/_authed/posts' import { Route as AuthedPostsIndexRouteImport } from './routes/_authed/posts.index' import { Route as AuthedPostsPostIdRouteImport } from './routes/_authed/posts.$postId' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const AuthedRoute = AuthedRouteImport.update({ - id: '/_authed', - getParentRoute: () => rootRouteImport, -} as any) -const LoginRoute = LoginRouteImport.update({ - id: '/login', - path: '/login', +const SignupRoute = SignupRouteImport.update({ + id: '/signup', + path: '/signup', getParentRoute: () => rootRouteImport, } as any) const LogoutRoute = LogoutRouteImport.update({ @@ -37,9 +28,18 @@ const LogoutRoute = LogoutRouteImport.update({ path: '/logout', getParentRoute: () => rootRouteImport, } as any) -const SignupRoute = SignupRouteImport.update({ - id: '/signup', - path: '/signup', +const LoginRoute = LoginRouteImport.update({ + id: '/login', + path: '/login', + getParentRoute: () => rootRouteImport, +} as any) +const AuthedRoute = AuthedRouteImport.update({ + id: '/_authed', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AuthedPostsRoute = AuthedPostsRouteImport.update({ @@ -120,25 +120,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_authed': { - id: '/_authed' - path: '' - fullPath: '/' - preLoaderRoute: typeof AuthedRouteImport - parentRoute: typeof rootRouteImport - } - '/login': { - id: '/login' - path: '/login' - fullPath: '/login' - preLoaderRoute: typeof LoginRouteImport + '/signup': { + id: '/signup' + path: '/signup' + fullPath: '/signup' + preLoaderRoute: typeof SignupRouteImport parentRoute: typeof rootRouteImport } '/logout': { @@ -148,11 +134,25 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof LogoutRouteImport parentRoute: typeof rootRouteImport } - '/signup': { - id: '/signup' - path: '/signup' - fullPath: '/signup' - preLoaderRoute: typeof SignupRouteImport + '/login': { + id: '/login' + path: '/login' + fullPath: '/login' + preLoaderRoute: typeof LoginRouteImport + parentRoute: typeof rootRouteImport + } + '/_authed': { + id: '/_authed' + path: '' + fullPath: '/' + preLoaderRoute: typeof AuthedRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport 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 fb7868435d..76e5f8b1d6 100644 --- a/e2e/react-start/basic-auth/src/routes/__root.tsx +++ b/e2e/react-start/basic-auth/src/routes/__root.tsx @@ -14,18 +14,18 @@ import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary.js' import { NotFound } from '~/components/NotFound.js' import appCss from '~/styles/app.css?url' import { seo } from '~/utils/seo.js' -import { getAppSession } from '~/utils/session.js' +import { useAppSession } from '~/utils/session.js' const fetchUser = createServerFn({ method: 'GET' }).handler(async () => { // We need to auth on the server so we have access to secure cookies - const session = await getAppSession() + const session = await useAppSession() - if (!session.userEmail) { + if (!session.data.userEmail) { return null } return { - email: session.userEmail, + email: session.data.userEmail, } }) diff --git a/e2e/react-start/basic-auth/src/routes/_authed.tsx b/e2e/react-start/basic-auth/src/routes/_authed.tsx index fe73185136..221627851a 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 { getAppSession } from '~/utils/session' +import { useAppSession } from '~/utils/session' export const loginFn = createServerFn({ method: 'POST', }) - .validator((payload: { email: string; password: string }) => payload) + .inputValidator((payload: { email: string; password: string }) => payload) .handler(async ({ data }) => { // Find the user const user = await prismaClient.user.findUnique({ @@ -37,11 +37,12 @@ export const loginFn = createServerFn({ } // Create a session - const session = await getAppSession() + const session = await useAppSession() // Store the user's email in the session - session.userEmail = user.email - await session.save() + await session.update({ + userEmail: user.email, + }) }) export const Route = createFileRoute('/_authed')({ @@ -51,7 +52,7 @@ export const Route = createFileRoute('/_authed')({ } }, errorComponent: ({ error }) => { - if (error instanceof Error && error.message === 'Not authenticated') { + if (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 0f86b0d4e3..a08f9c737e 100644 --- a/e2e/react-start/basic-auth/src/routes/logout.tsx +++ b/e2e/react-start/basic-auth/src/routes/logout.tsx @@ -1,12 +1,12 @@ import { redirect, createFileRoute } from '@tanstack/react-router' import { createServerFn } from '@tanstack/react-start' -import { getAppSession } from '~/utils/session' +import { useAppSession } from '~/utils/session' const logoutFn = createServerFn({ method: 'POST' }).handler(async () => { - const session = await getAppSession() + const session = await useAppSession() - session.destroy() + session.clear() throw redirect({ href: '/', diff --git a/e2e/react-start/basic-auth/src/routes/signup.tsx b/e2e/react-start/basic-auth/src/routes/signup.tsx index d7d5d40129..d6ef153786 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 { getAppSession } from '~/utils/session' +import { useAppSession } from '~/utils/session' export const signupFn = createServerFn({ method: 'POST', }) - .validator( + .inputValidator( (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 getAppSession() + const session = await useAppSession() if (found) { if (found.password !== password) { @@ -36,8 +36,9 @@ export const signupFn = createServerFn({ } // Store the user's email in the session - session.userEmail = found.email - await session.save() + await session.update({ + userEmail: found.email, + }) // Redirect to the prev page stored in the "redirect" search param throw redirect({ @@ -54,8 +55,9 @@ export const signupFn = createServerFn({ }) // Store the user's email in the session - session.userEmail = user.email - await session.save() + await session.update({ + userEmail: user.email, + }) // Redirect to the prev page stored in the "redirect" search param throw redirect({ diff --git a/e2e/react-start/basic-auth/src/utils/posts.ts b/e2e/react-start/basic-auth/src/utils/posts.ts index 532e883ac0..b30810a5a3 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' }) - .validator((postId: string) => postId) + .inputValidator((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 f1deacf85b..c38bac1e48 100644 --- a/e2e/react-start/basic-auth/src/utils/session.ts +++ b/e2e/react-start/basic-auth/src/utils/session.ts @@ -1,25 +1,13 @@ -import { getIronSession } from 'iron-session' -import { getCookie, setCookie } from '@tanstack/react-start/server' +// src/services/session.server.ts +import { useSession } from '@tanstack/react-start/server' import type { User } from '@prisma/client' type SessionUser = { userEmail: User['email'] } -export function getAppSession() { - return getIronSession( - { read: getCookie, write: setCookie }, - { - cookieName: 'test-auth-session', - // This fixture only runs locally with test credentials. - password: 'local-e2e-only-session-password-at-least-32-characters', - ttl: 60 * 60, - cookieOptions: { - httpOnly: true, - secure: false, - sameSite: 'lax', - path: '/', - }, - }, - ) +export function useAppSession() { + return useSession({ + password: 'ChangeThisBeforeShippingToProdOrYouWillBeFired', + }) } diff --git a/e2e/react-start/basic-auth/tsconfig.json b/e2e/react-start/basic-auth/tsconfig.json index cef9369516..3a9fb7cd71 100644 --- a/e2e/react-start/basic-auth/tsconfig.json +++ b/e2e/react-start/basic-auth/tsconfig.json @@ -13,6 +13,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/react-start/basic-cloudflare/package.json b/e2e/react-start/basic-cloudflare/package.json index b9b8031ac4..d0e0d42d5a 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": "WRANGLER_LOG=warn npm run --silent cf-typegen", - "test:e2e": "playwright test --project=chromium" + "postinstall": "npm run cf-typegen", + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -21,7 +21,7 @@ }, "devDependencies": { "@cloudflare/vite-plugin": "^1.29.0", - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", @@ -29,19 +29,8 @@ "@types/react-dom": "^19.0.3", "@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", + "typescript": "^5.7.2", + "vite": "^8.0.0", "wrangler": "^4.74.0" - }, - "nx": { - "targets": { - "test:e2e": { - "outputs": [ - "...", - "{projectRoot}/.wrangler/deploy" - ] - } - } } } diff --git a/e2e/react-start/basic-cloudflare/playwright.config.ts b/e2e/react-start/basic-cloudflare/playwright.config.ts index 0925936d55..a545dff891 100644 --- a/e2e/react-start/basic-cloudflare/playwright.config.ts +++ b/e2e/react-start/basic-cloudflare/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -13,6 +14,9 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, @@ -20,8 +24,8 @@ export default defineConfig({ webServer: { command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/basic-cloudflare/src/components/DefaultCatchBoundary.tsx b/e2e/react-start/basic-cloudflare/src/components/DefaultCatchBoundary.tsx index 405fb5f4a7..ef2daa1ea1 100644 --- a/e2e/react-start/basic-cloudflare/src/components/DefaultCatchBoundary.tsx +++ b/e2e/react-start/basic-cloudflare/src/components/DefaultCatchBoundary.tsx @@ -1,15 +1,17 @@ import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, 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 === '/', + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, }) 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 b29f0d8d68..4219501f5e 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 IndexRouteImport } from './routes/index' import { Route as StaticRouteImport } from './routes/static' +import { Route as IndexRouteImport } from './routes/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const StaticRoute = StaticRouteImport.update({ id: '/static', path: '/static', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/static': { id: '/static' path: '/static' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof StaticRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/e2e/react-start/basic-cloudflare/tests/app.spec.ts b/e2e/react-start/basic-cloudflare/tests/app.spec.ts index c9497070dd..add28cb73e 100644 --- a/e2e/react-start/basic-cloudflare/tests/app.spec.ts +++ b/e2e/react-start/basic-cloudflare/tests/app.spec.ts @@ -1,5 +1,3 @@ -import { execFileSync } from 'node:child_process' -import { fileURLToPath } from 'node:url' import { existsSync } from 'node:fs' import { join } from 'node:path' import { expect } from '@playwright/test' @@ -31,19 +29,3 @@ test('prerender with Cloudflare Workers runtime', async ({ page }) => { 'The value is Hello from Cloudflare', ) }) - -test('the built Cloudflare app passes a deployment dry run', () => { - const wrangler = fileURLToPath( - new URL('../node_modules/wrangler/bin/wrangler.js', import.meta.url), - ) - const output = execFileSync( - process.execPath, - [wrangler, 'deploy', '--dry-run'], - { - encoding: 'utf8', - env: { ...process.env, WRANGLER_SEND_METRICS: 'false' }, - }, - ) - expect(output).toContain('dist/server/wrangler.json') - expect(output).toContain('--dry-run: exiting now.') -}) diff --git a/e2e/react-start/basic-cloudflare/tests/setup/global.setup.ts b/e2e/react-start/basic-cloudflare/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-start/basic-cloudflare/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/react-start/basic-cloudflare/tests/setup/global.teardown.ts b/e2e/react-start/basic-cloudflare/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-start/basic-cloudflare/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-start/basic-cloudflare/tsconfig.json b/e2e/react-start/basic-cloudflare/tsconfig.json index cef9369516..3a9fb7cd71 100644 --- a/e2e/react-start/basic-cloudflare/tsconfig.json +++ b/e2e/react-start/basic-cloudflare/tsconfig.json @@ -13,6 +13,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/react-start/basic-react-query/package.json b/e2e/react-start/basic-react-query/package.json index ee37b82ba6..5335ebcd93 100644 --- a/e2e/react-start/basic-react-query/package.json +++ b/e2e/react-start/basic-react-query/package.json @@ -9,7 +9,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-query": "^5.90.0", @@ -20,22 +20,21 @@ "@tanstack/react-start": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "catalog:", - "tailwind-merge": "^3.6.0", - "zod": "^4.4.3" + "redaxios": "^0.5.1", + "tailwind-merge": "^2.6.0", + "vite": "^8.0.0", + "zod": "^4.1.12" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "typescript": "^5.7.2" } } diff --git a/e2e/react-start/basic-react-query/playwright.config.ts b/e2e/react-start/basic-react-query/playwright.config.ts index 216fade4d5..fd2150e435 100644 --- a/e2e/react-start/basic-react-query/playwright.config.ts +++ b/e2e/react-start/basic-react-query/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -13,19 +18,19 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', - env: { - NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, - }, }, projects: [ diff --git a/e2e/react-start/basic-react-query/src/components/DefaultCatchBoundary.tsx b/e2e/react-start/basic-react-query/src/components/DefaultCatchBoundary.tsx index 405fb5f4a7..ef2daa1ea1 100644 --- a/e2e/react-start/basic-react-query/src/components/DefaultCatchBoundary.tsx +++ b/e2e/react-start/basic-react-query/src/components/DefaultCatchBoundary.tsx @@ -1,15 +1,17 @@ import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, 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 === '/', + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, }) 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 72bd9579f6..a1bed86dfa 100644 --- a/e2e/react-start/basic-react-query/src/routeTree.gen.ts +++ b/e2e/react-start/basic-react-query/src/routeTree.gen.ts @@ -9,47 +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 IndexRouteImport } from './routes/index' -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 ApiUsersRouteImport } from './routes/api.users' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +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 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 PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as ApiUsersRouteImport } from './routes/api.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 LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', - 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', +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', getParentRoute: () => rootRouteImport, } as any) const SuspenseTransitionRoute = SuspenseTransitionRouteImport.update({ @@ -57,64 +38,83 @@ const SuspenseTransitionRoute = SuspenseTransitionRouteImport.update({ path: '/suspense-transition', getParentRoute: () => rootRouteImport, } as any) -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const RedirectRoute = RedirectRouteImport.update({ + id: '/redirect', + path: '/redirect', 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', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ +const DeferredRoute = DeferredRouteImport.update({ + id: '/deferred', + path: '/deferred', + getParentRoute: () => rootRouteImport, +} as any) +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', - getParentRoute: () => PostsRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, + 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 LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => LayoutLayout2Route, +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, } as any) -const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ - id: '/layout-b', - path: '/layout-b', - getParentRoute: () => LayoutLayout2Route, +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/users', + getParentRoute: () => rootRouteImport, } as any) -const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => ApiUsersRoute, +const LayoutLayout2Route = LayoutLayout2RouteImport.update({ + id: '/_layout-2', + getParentRoute: () => LayoutRoute, +} as any) +const TransitionCountQueryRoute = TransitionCountQueryRouteImport.update({ + id: '/transition/count/query', + path: '/transition/count/query', + getParentRoute: () => rootRouteImport, } 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, +const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => ApiUsersRoute, +} as any) +const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ + id: '/layout-b', + path: '/layout-b', + getParentRoute: () => LayoutLayout2Route, +} as any) +const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => LayoutLayout2Route, } as any) export interface FileRoutesByFullPath { @@ -244,39 +244,11 @@ export interface RootRouteChildren { 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 - } - '/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 + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport parentRoute: typeof rootRouteImport } '/suspense-transition': { @@ -286,11 +258,74 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof SuspenseTransitionRouteImport parentRoute: typeof rootRouteImport } - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport + '/redirect': { + id: '/redirect' + path: '/redirect' + fullPath: '/redirect' + preLoaderRoute: typeof RedirectRouteImport + parentRoute: typeof rootRouteImport + } + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout': { + id: '/_layout' + 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 + } + '/api/users': { + id: '/api/users' + path: '/api/users' + fullPath: '/api/users' + preLoaderRoute: typeof ApiUsersRouteImport parentRoute: typeof rootRouteImport } '/_layout/_layout-2': { @@ -300,62 +335,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof LayoutLayout2RouteImport parentRoute: typeof LayoutRoute } - '/api/users': { - id: '/api/users' - path: '/api/users' - fullPath: '/api/users' - preLoaderRoute: typeof ApiUsersRouteImport + '/transition/count/query': { + id: '/transition/count/query' + path: '/transition/count/query' + fullPath: '/transition/count/query' + preLoaderRoute: typeof TransitionCountQueryRouteImport 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 - } - '/_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 - } '/posts_/$postId/deep': { id: '/posts_/$postId/deep' path: '/posts/$postId/deep' @@ -363,12 +349,26 @@ declare module '@tanstack/react-router' { 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 + '/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 } } } diff --git a/e2e/react-start/basic-react-query/src/routes/api.users.ts b/e2e/react-start/basic-react-query/src/routes/api.users.ts index 924c5b6860..bb37c6e68d 100644 --- a/e2e/react-start/basic-react-query/src/routes/api.users.ts +++ b/e2e/react-start/basic-react-query/src/routes/api.users.ts @@ -2,7 +2,11 @@ import { createFileRoute } from '@tanstack/react-router' import axios from 'redaxios' import type { User } from '../utils/users' -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const Route = createFileRoute('/api/users')({ server: { diff --git a/e2e/react-start/basic-react-query/src/routes/api/users.$id.ts b/e2e/react-start/basic-react-query/src/routes/api/users.$id.ts index febea309ea..e11e039652 100644 --- a/e2e/react-start/basic-react-query/src/routes/api/users.$id.ts +++ b/e2e/react-start/basic-react-query/src/routes/api/users.$id.ts @@ -2,7 +2,11 @@ import { createFileRoute } from '@tanstack/react-router' import axios from 'redaxios' import type { User } from '../../utils/users' -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const Route = createFileRoute('/api/users/$id')({ server: { diff --git a/e2e/react-start/basic-react-query/src/routes/deferred.tsx b/e2e/react-start/basic-react-query/src/routes/deferred.tsx index 11af82ed27..0380f79aca 100644 --- a/e2e/react-start/basic-react-query/src/routes/deferred.tsx +++ b/e2e/react-start/basic-react-query/src/routes/deferred.tsx @@ -1,5 +1,6 @@ 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/utils/posts.tsx b/e2e/react-start/basic-react-query/src/utils/posts.tsx index abb6e95b92..2574bf10d1 100644 --- a/e2e/react-start/basic-react-query/src/utils/posts.tsx +++ b/e2e/react-start/basic-react-query/src/utils/posts.tsx @@ -9,7 +9,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPosts = createServerFn({ method: 'GET' }).handler( async () => { @@ -27,7 +31,7 @@ export const postsQueryOptions = () => }) export const fetchPost = createServerFn({ method: 'GET' }) - .validator((postId: string) => postId) + .inputValidator((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 15216680e9..26b934fcb3 100644 --- a/e2e/react-start/basic-react-query/src/utils/users.tsx +++ b/e2e/react-start/basic-react-query/src/utils/users.tsx @@ -1,6 +1,4 @@ import { queryOptions } from '@tanstack/react-query' -import { createIsomorphicFn } from '@tanstack/react-start' -import { getRequestUrl } from '@tanstack/react-start/server' import axios from 'redaxios' export type User = { @@ -9,16 +7,17 @@ export type User = { email: string } -const getOrigin = createIsomorphicFn() - .server(() => getRequestUrl().origin) - .client(() => window.location.origin) +const PORT = + import.meta.env.VITE_SERVER_PORT || process.env.VITE_SERVER_PORT || 3000 + +export const DEPLOY_URL = `http://localhost:${PORT}` export const usersQueryOptions = () => queryOptions({ queryKey: ['users'], queryFn: () => axios - .get>(getOrigin() + '/api/users') + .get>(DEPLOY_URL + '/api/users') .then((r) => r.data) .catch(() => { throw new Error('Failed to fetch users') @@ -30,7 +29,7 @@ export const userQueryOptions = (id: string) => queryKey: ['users', id], queryFn: () => axios - .get(getOrigin() + '/api/users/' + id) + .get(DEPLOY_URL + '/api/users/' + id) .then((r) => r.data) .catch(() => { throw new Error('Failed to fetch user') diff --git a/e2e/react-start/basic-react-query/tests/setup/global.setup.ts b/e2e/react-start/basic-react-query/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-start/basic-react-query/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/react-start/basic-react-query/tests/setup/global.teardown.ts b/e2e/react-start/basic-react-query/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-start/basic-react-query/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-start/basic-react-query/tsconfig.json b/e2e/react-start/basic-react-query/tsconfig.json index c7a0597e4b..a07911fe5f 100644 --- a/e2e/react-start/basic-react-query/tsconfig.json +++ b/e2e/react-start/basic-react-query/tsconfig.json @@ -13,6 +13,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/react/start-basic-rsbuild/.devcontainer/devcontainer.json b/e2e/react-start/basic-rsc/.devcontainer/devcontainer.json similarity index 100% rename from examples/react/start-basic-rsbuild/.devcontainer/devcontainer.json rename to e2e/react-start/basic-rsc/.devcontainer/devcontainer.json diff --git a/e2e/react-start/basic-rsc/.gitignore b/e2e/react-start/basic-rsc/.gitignore new file mode 100644 index 0000000000..3c8e6870b3 --- /dev/null +++ b/e2e/react-start/basic-rsc/.gitignore @@ -0,0 +1,14 @@ +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-rsbuild/.prettierignore b/e2e/react-start/basic-rsc/.prettierignore similarity index 100% rename from examples/react/start-basic-rsbuild/.prettierignore rename to e2e/react-start/basic-rsc/.prettierignore diff --git a/e2e/react-start/basic-rsc/package.json b/e2e/react-start/basic-rsc/package.json new file mode 100644 index 0000000000..1785fe3c84 --- /dev/null +++ b/e2e/react-start/basic-rsc/package.json @@ -0,0 +1,34 @@ +{ + "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": "^8.0.0" + }, + "devDependencies": { + "@tailwindcss/vite": "^4.2.2", + "@types/react": "^19.0.8", + "@types/react-dom": "^19.0.3", + "@vitejs/plugin-react": "^6.0.1", + "tailwindcss": "^4.2.2", + "typescript": "^5.7.2" + }, + "overrides": { + "react": "0.0.0-experimental-035a41c4e-20230704", + "react-dom": "0.0.0-experimental-035a41c4e-20230704" + } +} diff --git a/examples/react/start-basic-rsbuild/public/android-chrome-192x192.png b/e2e/react-start/basic-rsc/public/android-chrome-192x192.png similarity index 100% rename from examples/react/start-basic-rsbuild/public/android-chrome-192x192.png rename to e2e/react-start/basic-rsc/public/android-chrome-192x192.png diff --git a/examples/react/start-basic-rsbuild/public/android-chrome-512x512.png b/e2e/react-start/basic-rsc/public/android-chrome-512x512.png similarity index 100% rename from examples/react/start-basic-rsbuild/public/android-chrome-512x512.png rename to e2e/react-start/basic-rsc/public/android-chrome-512x512.png diff --git a/examples/react/start-basic-rsbuild/public/apple-touch-icon.png b/e2e/react-start/basic-rsc/public/apple-touch-icon.png similarity index 100% rename from examples/react/start-basic-rsbuild/public/apple-touch-icon.png rename to e2e/react-start/basic-rsc/public/apple-touch-icon.png diff --git a/examples/react/start-basic-rsbuild/public/favicon-16x16.png b/e2e/react-start/basic-rsc/public/favicon-16x16.png similarity index 100% rename from examples/react/start-basic-rsbuild/public/favicon-16x16.png rename to e2e/react-start/basic-rsc/public/favicon-16x16.png diff --git a/examples/react/start-basic-rsbuild/public/favicon-32x32.png b/e2e/react-start/basic-rsc/public/favicon-32x32.png similarity index 100% rename from examples/react/start-basic-rsbuild/public/favicon-32x32.png rename to e2e/react-start/basic-rsc/public/favicon-32x32.png diff --git a/examples/react/start-basic-rsbuild/public/favicon.ico b/e2e/react-start/basic-rsc/public/favicon.ico similarity index 100% rename from examples/react/start-basic-rsbuild/public/favicon.ico rename to e2e/react-start/basic-rsc/public/favicon.ico diff --git a/examples/react/start-basic-rsbuild/public/favicon.png b/e2e/react-start/basic-rsc/public/favicon.png similarity index 100% rename from examples/react/start-basic-rsbuild/public/favicon.png rename to e2e/react-start/basic-rsc/public/favicon.png diff --git a/examples/react/start-basic-rsbuild/public/site.webmanifest b/e2e/react-start/basic-rsc/public/site.webmanifest similarity index 100% rename from examples/react/start-basic-rsbuild/public/site.webmanifest rename to e2e/react-start/basic-rsc/public/site.webmanifest diff --git a/e2e/react-start/basic-rsc/src/components/DefaultCatchBoundary.tsx b/e2e/react-start/basic-rsc/src/components/DefaultCatchBoundary.tsx new file mode 100644 index 0000000000..ef2daa1ea1 --- /dev/null +++ b/e2e/react-start/basic-rsc/src/components/DefaultCatchBoundary.tsx @@ -0,0 +1,53 @@ +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-rsbuild/src/components/NotFound.tsx b/e2e/react-start/basic-rsc/src/components/NotFound.tsx similarity index 100% rename from examples/react/start-basic-rsbuild/src/components/NotFound.tsx rename to e2e/react-start/basic-rsc/src/components/NotFound.tsx diff --git a/e2e/react-start/basic-rsc/src/routeTree.gen.ts b/e2e/react-start/basic-rsc/src/routeTree.gen.ts new file mode 100644 index 0000000000..500f71a9f7 --- /dev/null +++ b/e2e/react-start/basic-rsc/src/routeTree.gen.ts @@ -0,0 +1,254 @@ +/* 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 new file mode 100644 index 0000000000..fef35c9e06 --- /dev/null +++ b/e2e/react-start/basic-rsc/src/router.tsx @@ -0,0 +1,16 @@ +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 new file mode 100644 index 0000000000..7e5ac89786 --- /dev/null +++ b/e2e/react-start/basic-rsc/src/routes/__root.tsx @@ -0,0 +1,125 @@ +/// +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 new file mode 100644 index 0000000000..02ddbb1cd9 --- /dev/null +++ b/e2e/react-start/basic-rsc/src/routes/_layout.tsx @@ -0,0 +1,16 @@ +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 new file mode 100644 index 0000000000..3b7dbf2903 --- /dev/null +++ b/e2e/react-start/basic-rsc/src/routes/_layout/_layout-2.tsx @@ -0,0 +1,34 @@ +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 new file mode 100644 index 0000000000..ed2dea8800 --- /dev/null +++ b/e2e/react-start/basic-rsc/src/routes/_layout/_layout-2/layout-a.tsx @@ -0,0 +1,8 @@ +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 new file mode 100644 index 0000000000..4799d403e9 --- /dev/null +++ b/e2e/react-start/basic-rsc/src/routes/_layout/_layout-2/layout-b.tsx @@ -0,0 +1,8 @@ +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 new file mode 100644 index 0000000000..d531858f8c --- /dev/null +++ b/e2e/react-start/basic-rsc/src/routes/index.tsx @@ -0,0 +1,12 @@ +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 new file mode 100644 index 0000000000..a7f2a551b2 --- /dev/null +++ b/e2e/react-start/basic-rsc/src/routes/posts.$postId.tsx @@ -0,0 +1,46 @@ +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 new file mode 100644 index 0000000000..c659274567 --- /dev/null +++ b/e2e/react-start/basic-rsc/src/routes/posts.index.tsx @@ -0,0 +1,8 @@ +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 new file mode 100644 index 0000000000..a3ef2a2e20 --- /dev/null +++ b/e2e/react-start/basic-rsc/src/routes/posts.tsx @@ -0,0 +1,16 @@ +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 new file mode 100644 index 0000000000..13d368cf9c --- /dev/null +++ b/e2e/react-start/basic-rsc/src/routes/posts_.$postId.deep.tsx @@ -0,0 +1,26 @@ +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/custom-server-rsbuild/src/styles/app.css b/e2e/react-start/basic-rsc/src/styles/app.css similarity index 100% rename from e2e/react-start/custom-server-rsbuild/src/styles/app.css rename to e2e/react-start/basic-rsc/src/styles/app.css diff --git a/e2e/react-start/basic-rsc/src/utils/posts.tsx b/e2e/react-start/basic-rsc/src/utils/posts.tsx new file mode 100644 index 0000000000..16fc1744e6 --- /dev/null +++ b/e2e/react-start/basic-rsc/src/utils/posts.tsx @@ -0,0 +1,35 @@ +// 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 new file mode 100644 index 0000000000..37c0661217 --- /dev/null +++ b/e2e/react-start/basic-rsc/src/utils/renderPosts.tsx @@ -0,0 +1,63 @@ +'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/examples/react/start-basic-rsbuild/src/utils/seo.ts b/e2e/react-start/basic-rsc/src/utils/seo.ts similarity index 100% rename from examples/react/start-basic-rsbuild/src/utils/seo.ts rename to e2e/react-start/basic-rsc/src/utils/seo.ts diff --git a/e2e/react-start/early-hints/tsconfig.json b/e2e/react-start/basic-rsc/tsconfig.json similarity index 100% rename from e2e/react-start/early-hints/tsconfig.json rename to e2e/react-start/basic-rsc/tsconfig.json diff --git a/e2e/react-start/basic-rsc/vite.config.ts b/e2e/react-start/basic-rsc/vite.config.ts new file mode 100644 index 0000000000..6c9a4c347a --- /dev/null +++ b/e2e/react-start/basic-rsc/vite.config.ts @@ -0,0 +1,9 @@ +import { defineConfig } from 'vite' +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: [tailwindcss(), tanstackStart(), viteReact()], +}) diff --git a/e2e/react-start/basic-tsr-config/package.json b/e2e/react-start/basic-tsr-config/package.json index 99e681ac9d..af90af8060 100644 --- a/e2e/react-start/basic-tsr-config/package.json +++ b/e2e/react-start/basic-tsr-config/package.json @@ -8,23 +8,21 @@ "dev:e2e": "vite dev", "build": "rimraf ./count.txt && vite build && tsc --noEmit", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", "@tanstack/react-start": "workspace:^", "react": "^19.0.0", - "react-dom": "^19.0.0" + "react-dom": "^19.0.0", + "vite": "^8.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": "^1.0.0", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", - "rimraf": "catalog:" + "srvx": "^0.11.9", + "typescript": "^5.7.2" } } diff --git a/e2e/react-start/basic-tsr-config/playwright.config.ts b/e2e/react-start/basic-tsr-config/playwright.config.ts index 82678ac00b..18b8905468 100644 --- a/e2e/react-start/basic-tsr-config/playwright.config.ts +++ b/e2e/react-start/basic-tsr-config/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/basic-tsr-config/src/routes/index.tsx b/e2e/react-start/basic-tsr-config/src/routes/index.tsx index aaa4bdfdb3..413617217d 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' }) - .validator((d: number) => d) + .inputValidator((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 f3895f6eb1..3558337b0c 100644 --- a/e2e/react-start/basic-tsr-config/tsconfig.json +++ b/e2e/react-start/basic-tsr-config/tsconfig.json @@ -13,6 +13,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/app/*"] }, diff --git a/e2e/react-start/basic/.gitignore b/e2e/react-start/basic/.gitignore index a5f07919aa..a79d5cf129 100644 --- a/e2e/react-start/basic/.gitignore +++ b/e2e/react-start/basic/.gitignore @@ -18,5 +18,3 @@ 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 3a1a4ea9c8..f85cdae20b 100644 --- a/e2e/react-start/basic/package.json +++ b/e2e/react-start/basic/package.json @@ -4,36 +4,35 @@ "sideEffects": false, "type": "module", "scripts": { - "dev": "pnpm dev:vite --port 3000", - "dev:e2e": "pnpm dev:vite", - "dev:vite": "vite dev", - "dev:rsbuild": "rsbuild dev", - "build": "pnpm build:vite", - "build:vite": "vite build && tsc --noEmit", - "build:rsbuild": "rsbuild build && tsc --noEmit", + "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", "preview": "vite preview", - "preview:rsbuild": "rsbuild preview", "start": "node server.js", - "test:e2e:local": "playwright test --project=chromium" + "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 dist; rm -rf port*.txt; MODE=spa playwright test --project=chromium", + "test:e2e:ssrMode": "rm -rf dist; rm -rf port*.txt; playwright test --project=chromium", + "test:e2e:prerender": "rm -rf dist; rm -rf port*.txt; MODE=prerender playwright test --project=chromium", + "test:e2e:preview": "rm -rf dist; 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" }, "dependencies": { "@tanstack/react-router": "workspace:^", "@tanstack/react-router-devtools": "workspace:^", "@tanstack/react-start": "workspace:^", - "express": "^5.2.1", + "express": "^5.1.0", "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": "catalog:", - "tailwind-merge": "^3.6.0" + "redaxios": "^0.5.1", + "tailwind-merge": "^2.6.0" }, "devDependencies": { - "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", - "@rsbuild/plugin-react": "^2.0.0", - "@tailwindcss/postcss": "^4.2.2", + "@playwright/test": "^1.50.1", "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@types/js-cookie": "^3.0.6", @@ -42,91 +41,10 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "combinate": "^1.1.11", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "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" - } - ] - } + "typescript": "^5.7.2", + "vite": "^8.0.0", + "zod": "^3.24.2" } } diff --git a/e2e/react-start/basic/playwright.config.ts b/e2e/react-start/basic/playwright.config.ts index bb4c2cb761..86c58bc1ce 100644 --- a/e2e/react-start/basic/playwright.config.ts +++ b/e2e/react-start/basic/playwright.config.ts @@ -1,62 +1,63 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +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' } -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 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 baseURL = `http://localhost:${PORT}` -const previewCommand = - toolchain === 'rsbuild' - ? `pnpm preview:rsbuild --host 0.0.0.0 --port ${PORT}` - : `pnpm preview --host 0.0.0.0 --outDir ${distDir} --port ${PORT}` -const devCommand = - toolchain === 'rsbuild' - ? `pnpm dev:rsbuild --port ${PORT}` - : `pnpm dev:vite --port ${PORT}` -const commandByMode = devServer - ? devCommand - : mode === 'preview' - ? previewCommand - : 'pnpm start' +const spaModeCommand = `pnpm build:spa && pnpm start` +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()) /** * 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: commandByMode, - wait: appServerReady, - reuseExistingServer: false, + command: getCommand(), + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { - NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, - MODE: mode, - E2E_TOOLCHAIN: toolchain, - START_PORT: '0', + MODE: process.env.MODE || '', + VITE_NODE_ENV: 'test', + VITE_EXTERNAL_PORT: String(EXTERNAL_PORT), + VITE_SERVER_PORT: String(PORT), + START_PORT: String(START_PORT), PORT: String(PORT), - E2E_DIST_DIR: distDir, - ...(process.env.TSS_RSB_CLIENT_OUTPUT - ? { TSS_RSB_CLIENT_OUTPUT: process.env.TSS_RSB_CLIENT_OUTPUT } - : {}), }, }, diff --git a/e2e/react-start/basic/postcss.config.mjs b/e2e/react-start/basic/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/e2e/react-start/basic/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/e2e/react-start/basic/rsbuild.config.ts b/e2e/react-start/basic/rsbuild.config.ts deleted file mode 100644 index 23072b6c1b..0000000000 --- a/e2e/react-start/basic/rsbuild.config.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 3e1ddab400..83f5ff0079 100644 --- a/e2e/react-start/basic/server.js +++ b/e2e/react-start/basic/server.js @@ -1,42 +1,24 @@ -import fs from 'node:fs' -import path from 'node:path' import { toNodeHandler } from 'srvx/node' +import path from 'node:path' import express from 'express' import { createProxyMiddleware } from 'http-proxy-middleware' -const port = Number(process.env.PORT ?? 3000) +const port = process.env.PORT || 3000 -const startPort = Number(process.env.START_PORT ?? 0) +const startPort = process.env.START_PORT || 3001 const isSpaMode = process.env.MODE === 'spa' const isPrerender = process.env.MODE === 'prerender' -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 distServerEntryPath = resolveDistServerEntryPath() - const server = (await import(distServerEntryPath)).default + const server = (await import('./dist/server/server.js')).default const nodeHandler = toNodeHandler(server.fetch) const app = express() // 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(express.static('./dist/client', { redirect: !isPrerender })) app.use(async (req, res, next) => { try { @@ -49,13 +31,13 @@ export async function createStartServer() { return { app } } -export async function createSpaServer(backendPort) { +export async function createSpaServer() { const app = express() app.use( '/api', createProxyMiddleware({ - target: `http://localhost:${backendPort}/api`, // Replace with your target server's URL + target: `http://localhost:${startPort}/api`, // Replace with your target server's URL changeOrigin: false, // Needed for virtual hosted sites, }), ) @@ -63,36 +45,36 @@ export async function createSpaServer(backendPort) { app.use( '/_serverFn', createProxyMiddleware({ - target: `http://localhost:${backendPort}/_serverFn`, // Replace with your target server's URL + target: `http://localhost:${startPort}/_serverFn`, // Replace with your target server's URL changeOrigin: false, // Needed for virtual hosted sites, }), ) - app.use(express.static(distClientDir)) + app.use(express.static('./dist/client')) app.get('/{*splat}', (req, res) => { - res.sendFile('index.html', { root: distClientDir }) + res.sendFile(path.resolve('./dist/client/index.html')) }) return { app } } -// Bind the backend first so the SPA proxy receives the port actually held by it. -const { app: startApp } = await createStartServer() -const backend = startApp.listen(isSpaMode ? startPort : port, async (error) => { - if (error) { - throw error - } - const backendPort = backend.address().port - if (isSpaMode) { - const { app } = await createSpaServer(backendPort) - const frontend = app.listen(port, (frontendError) => { - if (frontendError) { - throw frontendError - } - console.info(`E2E app: http://localhost:${frontend.address().port}`) - }) - } else { - console.info(`E2E app: http://localhost:${backendPort}`) - } -}) +if (isSpaMode) { + createSpaServer().then(async ({ app }) => + app.listen(port, () => { + console.info(`Client Server: http://localhost:${port}`) + }), + ) + + createStartServer().then(async ({ app }) => + app.listen(startPort, () => { + console.info(`Start Server: http://localhost:${startPort}`) + }), + ) +} else { + createStartServer().then(async ({ app }) => + app.listen(port, () => { + console.info(`Start Server: http://localhost:${port}`) + }), + ) +} diff --git a/e2e/react-start/basic/src/components/DefaultCatchBoundary.tsx b/e2e/react-start/basic/src/components/DefaultCatchBoundary.tsx index 405fb5f4a7..ef2daa1ea1 100644 --- a/e2e/react-start/basic/src/components/DefaultCatchBoundary.tsx +++ b/e2e/react-start/basic/src/components/DefaultCatchBoundary.tsx @@ -1,15 +1,17 @@ import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, 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 === '/', + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, }) console.error(error) diff --git a/e2e/react-start/basic/src/components/throwRedirect.ts b/e2e/react-start/basic/src/components/throwRedirect.ts index 6a7a011912..0081a3c560 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() - .validator( + .inputValidator( (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 index 912837c218..b0a3b51ef8 100644 --- a/e2e/react-start/basic/src/raw-stream-fns.ts +++ b/e2e/react-start/basic/src/raw-stream-fns.ts @@ -364,93 +364,6 @@ export const errorStreamFn = createServerFn().handler(async () => { } }) -// ============================================================================ -// 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. diff --git a/e2e/react-start/basic/src/routeTree.gen.ts b/e2e/react-start/basic/src/routeTree.gen.ts index b6603dd01d..2c101bb9da 100644 --- a/e2e/react-start/basic/src/routeTree.gen.ts +++ b/e2e/react-start/basic/src/routeTree.gen.ts @@ -9,176 +9,78 @@ // Additionally, you should also exclude this file 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 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 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 TypeOnlyReexportRouteImport } from './routes/type-only-reexport' +import { Route as StreamRouteImport } from './routes/stream' +import { Route as ScriptsRouteImport } from './routes/scripts' +import { Route as RawStreamRouteImport } from './routes/raw-stream' +import { Route as 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 ClientOnlyRouteImport } from './routes/client-only' +import { Route as AsyncScriptsRouteImport } from './routes/async-scripts' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as SpecialCharsRouteRouteImport } from './routes/specialChars/route' +import { Route as SearchParamsRouteRouteImport } from './routes/search-params/route' +import { Route as NotFoundRouteRouteImport } from './routes/not-found/route' +import { Route as IndexRouteImport } from './routes/index' import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as SearchParamsIndexRouteImport } from './routes/search-params/index' +import { Route as RedirectIndexRouteImport } from './routes/redirect/index' +import { Route as RawStreamIndexRouteImport } from './routes/raw-stream/index' +import { Route as PostsIndexRouteImport } from './routes/posts.index' +import { Route as NotFoundIndexRouteImport } from './routes/not-found/index' +import { Route as MultiCookieRedirectIndexRouteImport } from './routes/multi-cookie-redirect/index' import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' -import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' -import { Route as ApiUsersIdRouteImport } from './routes/api/users.$id' -import { Route as Issue6221ArticleIdRouteImport } from './routes/issue-6221.article.$id' -import { Route as NotFoundDeepIndexRouteImport } from './routes/not-found/deep/index' -import { Route as NotFoundDeepBRouteRouteImport } from './routes/not-found/deep/b/route' -import { Route as 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 SpecialCharsChar45824Char54620Char48124Char44397RouteImport } from './routes/specialChars/대한민국' +import { Route as SpecialCharsSearchRouteImport } from './routes/specialChars/search' +import { Route as SpecialCharsHashRouteImport } from './routes/specialChars/hash' +import { Route as SpecialCharsParamRouteImport } from './routes/specialChars/$param' +import { Route as SearchParamsLoaderThrowsRedirectRouteImport } from './routes/search-params/loader-throws-redirect' +import { Route as SearchParamsDefaultRouteImport } from './routes/search-params/default' +import { Route as RedirectTargetRouteImport } from './routes/redirect/$target' +import { Route as RawStreamSsrTextHintRouteImport } from './routes/raw-stream/ssr-text-hint' +import { Route as RawStreamSsrSingleRouteImport } from './routes/raw-stream/ssr-single' +import { Route as RawStreamSsrMultipleRouteImport } from './routes/raw-stream/ssr-multiple' +import { Route as RawStreamSsrMixedRouteImport } from './routes/raw-stream/ssr-mixed' +import { Route as RawStreamSsrBinaryHintRouteImport } from './routes/raw-stream/ssr-binary-hint' +import { Route as RawStreamClientCallRouteImport } from './routes/raw-stream/client-call' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as NotFoundViaLoaderRouteImport } from './routes/not-found/via-loader' +import { Route as NotFoundViaBeforeLoadTargetRootRouteImport } from './routes/not-found/via-beforeLoad-target-root' +import { Route as NotFoundViaBeforeLoadRouteImport } from './routes/not-found/via-beforeLoad' +import { Route as MultiCookieRedirectTargetRouteImport } from './routes/multi-cookie-redirect/target' +import { Route as ApiUsersRouteImport } from './routes/api.users' +import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' +import { Route as SpecialCharsMalformedRouteRouteImport } from './routes/specialChars/malformed/route' +import { Route as NotFoundParentBoundaryRouteRouteImport } from './routes/not-found/parent-boundary/route' +import { Route as NotFoundDeepRouteRouteImport } from './routes/not-found/deep/route' 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 NotFoundParentBoundaryIndexRouteImport } from './routes/not-found/parent-boundary/index' +import { Route as NotFoundDeepIndexRouteImport } from './routes/not-found/deep/index' import { Route as SpecialCharsMalformedSearchRouteImport } from './routes/specialChars/malformed/search' +import { Route as SpecialCharsMalformedParamRouteImport } from './routes/specialChars/malformed/$param' +import { Route as RedirectTargetViaLoaderRouteImport } from './routes/redirect/$target/via-loader' +import { Route as RedirectTargetViaBeforeLoadRouteImport } from './routes/redirect/$target/via-beforeLoad' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' +import { Route as NotFoundParentBoundaryViaBeforeLoadRouteImport } from './routes/not-found/parent-boundary/via-beforeLoad' +import { Route as ApiUsersIdRouteImport } from './routes/api/users.$id' +import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' +import { Route as NotFoundDeepBRouteRouteImport } from './routes/not-found/deep/b/route' +import { Route as RedirectTargetServerFnIndexRouteImport } from './routes/redirect/$target/serverFn/index' +import { Route as RedirectTargetServerFnViaUseServerFnRouteImport } from './routes/redirect/$target/serverFn/via-useServerFn' +import { Route as RedirectTargetServerFnViaLoaderRouteImport } from './routes/redirect/$target/serverFn/via-loader' +import { Route as RedirectTargetServerFnViaBeforeLoadRouteImport } from './routes/redirect/$target/serverFn/via-beforeLoad' import { Route as 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 IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', - getParentRoute: () => rootRouteImport, -} as any) -const AsyncScriptsRoute = AsyncScriptsRouteImport.update({ - id: '/async-scripts', - path: '/async-scripts', - getParentRoute: () => rootRouteImport, -} as any) -const AuthDocsRoute = AuthDocsRouteImport.update({ - id: '/auth-docs', - path: '/auth-docs', - getParentRoute: () => rootRouteImport, -} as any) -const ClientOnlyRoute = ClientOnlyRouteImport.update({ - id: '/client-only', - path: '/client-only', - getParentRoute: () => rootRouteImport, -} as any) -const DeferredRoute = DeferredRouteImport.update({ - id: '/deferred', - path: '/deferred', - getParentRoute: () => rootRouteImport, -} as any) -const ExecutionLocalRoute = ExecutionLocalRouteImport.update({ - id: '/execution-local', - path: '/execution-local', - getParentRoute: () => rootRouteImport, -} as any) -const ExecutionRpcRoute = ExecutionRpcRouteImport.update({ - id: '/execution-rpc', - path: '/execution-rpc', - getParentRoute: () => rootRouteImport, -} as any) -const InlineScriptsRoute = InlineScriptsRouteImport.update({ - id: '/inline-scripts', - path: '/inline-scripts', - getParentRoute: () => rootRouteImport, -} as any) -const LinksRoute = LinksRouteImport.update({ - id: '/links', - path: '/links', - getParentRoute: () => rootRouteImport, -} as any) -const NotFoundRouteRoute = NotFoundRouteRouteImport.update({ - id: '/not-found', - path: '/not-found', - getParentRoute: () => rootRouteImport, -} as any) -const PlainTsTypeAssertionRoute = PlainTsTypeAssertionRouteImport.update({ - id: '/plain-ts-type-assertion', - path: '/plain-ts-type-assertion', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) -const PrimitiveBeforeloadErrorRoute = - 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 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', +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', getParentRoute: () => rootRouteImport, } as any) const TypeOnlyReexportRoute = TypeOnlyReexportRouteImport.update({ @@ -186,61 +88,191 @@ const TypeOnlyReexportRoute = TypeOnlyReexportRouteImport.update({ path: '/type-only-reexport', getParentRoute: () => rootRouteImport, } as any) -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const StreamRoute = StreamRouteImport.update({ + id: '/stream', + path: '/stream', 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', +const ScriptsRoute = ScriptsRouteImport.update({ + id: '/scripts', + path: '/scripts', 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', +const RawStreamRoute = RawStreamRouteImport.update({ + id: '/raw-stream', + path: '/raw-stream', getParentRoute: () => rootRouteImport, } as any) +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', + getParentRoute: () => rootRouteImport, +} as any) +const LinksRoute = LinksRouteImport.update({ + id: '/links', + path: '/links', + getParentRoute: () => rootRouteImport, +} as any) +const InlineScriptsRoute = InlineScriptsRouteImport.update({ + id: '/inline-scripts', + path: '/inline-scripts', + getParentRoute: () => rootRouteImport, +} as any) +const DeferredRoute = DeferredRouteImport.update({ + id: '/deferred', + path: '/deferred', + getParentRoute: () => rootRouteImport, +} as any) +const ClientOnlyRoute = ClientOnlyRouteImport.update({ + id: '/client-only', + path: '/client-only', + getParentRoute: () => rootRouteImport, +} as any) +const AsyncScriptsRoute = AsyncScriptsRouteImport.update({ + id: '/async-scripts', + path: '/async-scripts', + getParentRoute: () => rootRouteImport, +} as any) +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', + getParentRoute: () => rootRouteImport, +} as any) +const SpecialCharsRouteRoute = SpecialCharsRouteRouteImport.update({ + id: '/specialChars', + path: '/specialChars', + getParentRoute: () => rootRouteImport, +} as any) +const SearchParamsRouteRoute = SearchParamsRouteRouteImport.update({ + id: '/search-params', + path: '/search-params', + getParentRoute: () => rootRouteImport, +} as any) +const NotFoundRouteRoute = NotFoundRouteRouteImport.update({ + id: '/not-found', + path: '/not-found', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + 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/', + getParentRoute: () => rootRouteImport, +} as any) +const RawStreamIndexRoute = RawStreamIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => RawStreamRoute, +} as any) +const PostsIndexRoute = PostsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PostsRoute, +} as any) +const NotFoundIndexRoute = NotFoundIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => NotFoundRouteRoute, +} as any) const MultiCookieRedirectIndexRoute = MultiCookieRedirectIndexRouteImport.update({ id: '/multi-cookie-redirect/', path: '/multi-cookie-redirect/', getParentRoute: () => rootRouteImport, } as any) -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, +const UsersUserIdRoute = UsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => UsersRoute, } 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, +const SpecialCharsChar45824Char54620Char48124Char44397Route = + SpecialCharsChar45824Char54620Char48124Char44397RouteImport.update({ + id: '/대한민국', + path: '/대한민국', + getParentRoute: () => SpecialCharsRouteRoute, } as any) -const NotFoundViaBeforeLoadRoute = NotFoundViaBeforeLoadRouteImport.update({ - id: '/via-beforeLoad', - path: '/via-beforeLoad', +const SpecialCharsSearchRoute = SpecialCharsSearchRouteImport.update({ + id: '/search', + path: '/search', + getParentRoute: () => SpecialCharsRouteRoute, +} as any) +const SpecialCharsHashRoute = SpecialCharsHashRouteImport.update({ + id: '/hash', + path: '/hash', + getParentRoute: () => SpecialCharsRouteRoute, +} as any) +const SpecialCharsParamRoute = SpecialCharsParamRouteImport.update({ + id: '/$param', + path: '/$param', + getParentRoute: () => SpecialCharsRouteRoute, +} as any) +const SearchParamsLoaderThrowsRedirectRoute = + SearchParamsLoaderThrowsRedirectRouteImport.update({ + id: '/loader-throws-redirect', + path: '/loader-throws-redirect', + getParentRoute: () => SearchParamsRouteRoute, + } as any) +const SearchParamsDefaultRoute = SearchParamsDefaultRouteImport.update({ + id: '/default', + path: '/default', + getParentRoute: () => SearchParamsRouteRoute, +} as any) +const RedirectTargetRoute = RedirectTargetRouteImport.update({ + id: '/redirect/$target', + path: '/redirect/$target', + getParentRoute: () => rootRouteImport, +} as any) +const RawStreamSsrTextHintRoute = RawStreamSsrTextHintRouteImport.update({ + id: '/ssr-text-hint', + path: '/ssr-text-hint', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamSsrSingleRoute = RawStreamSsrSingleRouteImport.update({ + id: '/ssr-single', + path: '/ssr-single', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamSsrMultipleRoute = RawStreamSsrMultipleRouteImport.update({ + id: '/ssr-multiple', + path: '/ssr-multiple', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamSsrMixedRoute = RawStreamSsrMixedRouteImport.update({ + id: '/ssr-mixed', + path: '/ssr-mixed', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamSsrBinaryHintRoute = RawStreamSsrBinaryHintRouteImport.update({ + id: '/ssr-binary-hint', + path: '/ssr-binary-hint', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamClientCallRoute = RawStreamClientCallRouteImport.update({ + id: '/client-call', + path: '/client-call', + getParentRoute: () => RawStreamRoute, +} as any) +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, +} as any) +const NotFoundViaLoaderRoute = NotFoundViaLoaderRouteImport.update({ + id: '/via-loader', + path: '/via-loader', getParentRoute: () => NotFoundRouteRoute, } as any) const NotFoundViaBeforeLoadTargetRootRoute = @@ -249,91 +281,25 @@ const NotFoundViaBeforeLoadTargetRootRoute = path: '/via-beforeLoad-target-root', getParentRoute: () => NotFoundRouteRoute, } as any) -const NotFoundViaLoaderRoute = NotFoundViaLoaderRouteImport.update({ - id: '/via-loader', - path: '/via-loader', +const NotFoundViaBeforeLoadRoute = NotFoundViaBeforeLoadRouteImport.update({ + id: '/via-beforeLoad', + path: '/via-beforeLoad', getParentRoute: () => NotFoundRouteRoute, } as any) -const 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({ - id: '/loader-throws-redirect', - path: '/loader-throws-redirect', - getParentRoute: () => SearchParamsRouteRoute, +const MultiCookieRedirectTargetRoute = + MultiCookieRedirectTargetRouteImport.update({ + id: '/multi-cookie-redirect/target', + path: '/multi-cookie-redirect/target', + getParentRoute: () => rootRouteImport, } as any) -const SpecialCharsParamRoute = SpecialCharsParamRouteImport.update({ - id: '/$param', - path: '/$param', - getParentRoute: () => SpecialCharsRouteRoute, +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/users', + getParentRoute: () => rootRouteImport, } as any) -const SpecialCharsHashRoute = SpecialCharsHashRouteImport.update({ - id: '/hash', - path: '/hash', - getParentRoute: () => SpecialCharsRouteRoute, +const LayoutLayout2Route = LayoutLayout2RouteImport.update({ + id: '/_layout-2', + getParentRoute: () => LayoutRoute, } as any) const SpecialCharsMalformedRouteRoute = SpecialCharsMalformedRouteRouteImport.update({ @@ -341,56 +307,21 @@ const SpecialCharsMalformedRouteRoute = path: '/malformed', getParentRoute: () => SpecialCharsRouteRoute, } as any) -const SpecialCharsSearchRoute = SpecialCharsSearchRouteImport.update({ - id: '/search', - path: '/search', - getParentRoute: () => SpecialCharsRouteRoute, -} as any) -const SpecialCharsChar45824Char54620Char48124Char44397Route = - SpecialCharsChar45824Char54620Char48124Char44397RouteImport.update({ - id: '/대한민국', - path: '/대한민국', - getParentRoute: () => SpecialCharsRouteRoute, +const NotFoundParentBoundaryRouteRoute = + NotFoundParentBoundaryRouteRouteImport.update({ + id: '/parent-boundary', + path: '/parent-boundary', + getParentRoute: () => NotFoundRouteRoute, } as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ +const NotFoundDeepRouteRoute = NotFoundDeepRouteRouteImport.update({ + id: '/deep', + path: '/deep', + getParentRoute: () => NotFoundRouteRoute, +} as any) +const RedirectTargetIndexRoute = RedirectTargetIndexRouteImport.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 NotFoundDeepIndexRoute = NotFoundDeepIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => NotFoundDeepRouteRoute, -} as any) -const NotFoundDeepBRouteRoute = NotFoundDeepBRouteRouteImport.update({ - id: '/b', - path: '/b', - getParentRoute: () => NotFoundDeepRouteRoute, + getParentRoute: () => RedirectTargetRoute, } as any) const NotFoundParentBoundaryIndexRoute = NotFoundParentBoundaryIndexRouteImport.update({ @@ -398,20 +329,26 @@ const NotFoundParentBoundaryIndexRoute = 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({ +const NotFoundDeepIndexRoute = NotFoundDeepIndexRouteImport.update({ id: '/', path: '/', + getParentRoute: () => NotFoundDeepRouteRoute, +} as any) +const SpecialCharsMalformedSearchRoute = + SpecialCharsMalformedSearchRouteImport.update({ + id: '/search', + path: '/search', + getParentRoute: () => SpecialCharsMalformedRouteRoute, + } as any) +const SpecialCharsMalformedParamRoute = + SpecialCharsMalformedParamRouteImport.update({ + id: '/$param', + path: '/$param', + getParentRoute: () => SpecialCharsMalformedRouteRoute, + } as any) +const RedirectTargetViaLoaderRoute = RedirectTargetViaLoaderRouteImport.update({ + id: '/via-loader', + path: '/via-loader', getParentRoute: () => RedirectTargetRoute, } as any) const RedirectTargetViaBeforeLoadRoute = @@ -420,22 +357,60 @@ const RedirectTargetViaBeforeLoadRoute = path: '/via-beforeLoad', getParentRoute: () => RedirectTargetRoute, } as any) -const RedirectTargetViaLoaderRoute = RedirectTargetViaLoaderRouteImport.update({ - id: '/via-loader', - path: '/via-loader', - getParentRoute: () => RedirectTargetRoute, +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', + getParentRoute: () => rootRouteImport, } as any) -const SpecialCharsMalformedParamRoute = - SpecialCharsMalformedParamRouteImport.update({ - id: '/$param', - path: '/$param', - getParentRoute: () => SpecialCharsMalformedRouteRoute, +const NotFoundParentBoundaryViaBeforeLoadRoute = + NotFoundParentBoundaryViaBeforeLoadRouteImport.update({ + id: '/via-beforeLoad', + path: '/via-beforeLoad', + getParentRoute: () => NotFoundParentBoundaryRouteRoute, } as any) -const SpecialCharsMalformedSearchRoute = - SpecialCharsMalformedSearchRouteImport.update({ - id: '/search', - path: '/search', - getParentRoute: () => SpecialCharsMalformedRouteRoute, +const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => ApiUsersRoute, +} as any) +const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ + id: '/layout-b', + path: '/layout-b', + getParentRoute: () => LayoutLayout2Route, +} as any) +const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => LayoutLayout2Route, +} as any) +const NotFoundDeepBRouteRoute = NotFoundDeepBRouteRouteImport.update({ + id: '/b', + path: '/b', + getParentRoute: () => NotFoundDeepRouteRoute, +} as any) +const RedirectTargetServerFnIndexRoute = + RedirectTargetServerFnIndexRouteImport.update({ + id: '/serverFn/', + path: '/serverFn/', + getParentRoute: () => RedirectTargetRoute, + } as any) +const RedirectTargetServerFnViaUseServerFnRoute = + RedirectTargetServerFnViaUseServerFnRouteImport.update({ + id: '/serverFn/via-useServerFn', + path: '/serverFn/via-useServerFn', + getParentRoute: () => RedirectTargetRoute, + } as any) +const RedirectTargetServerFnViaLoaderRoute = + RedirectTargetServerFnViaLoaderRouteImport.update({ + id: '/serverFn/via-loader', + path: '/serverFn/via-loader', + getParentRoute: () => RedirectTargetRoute, + } as any) +const RedirectTargetServerFnViaBeforeLoadRoute = + RedirectTargetServerFnViaBeforeLoadRouteImport.update({ + id: '/serverFn/via-beforeLoad', + path: '/serverFn/via-beforeLoad', + getParentRoute: () => RedirectTargetRoute, } as any) const FooBarQuxHereRoute = FooBarQuxHereRouteImport.update({ id: '/foo/$bar/$qux/_here', @@ -447,30 +422,6 @@ const NotFoundDeepBCRouteRoute = NotFoundDeepBCRouteRouteImport.update({ path: '/c', getParentRoute: () => NotFoundDeepBRouteRoute, } as any) -const RedirectTargetServerFnIndexRoute = - RedirectTargetServerFnIndexRouteImport.update({ - id: '/serverFn/', - path: '/serverFn/', - getParentRoute: () => RedirectTargetRoute, - } as any) -const RedirectTargetServerFnViaBeforeLoadRoute = - RedirectTargetServerFnViaBeforeLoadRouteImport.update({ - id: '/serverFn/via-beforeLoad', - path: '/serverFn/via-beforeLoad', - getParentRoute: () => RedirectTargetRoute, - } as any) -const RedirectTargetServerFnViaLoaderRoute = - RedirectTargetServerFnViaLoaderRouteImport.update({ - id: '/serverFn/via-loader', - path: '/serverFn/via-loader', - getParentRoute: () => RedirectTargetRoute, - } as any) -const RedirectTargetServerFnViaUseServerFnRoute = - RedirectTargetServerFnViaUseServerFnRouteImport.update({ - id: '/serverFn/via-useServerFn', - path: '/serverFn/via-useServerFn', - getParentRoute: () => RedirectTargetRoute, - } as any) const FooBarQuxHereIndexRoute = FooBarQuxHereIndexRouteImport.update({ id: '/', path: '/', @@ -488,16 +439,11 @@ export interface FileRoutesByFullPath { '/search-params': typeof SearchParamsRouteRouteWithChildren '/specialChars': typeof SpecialCharsRouteRouteWithChildren '/async-scripts': typeof AsyncScriptsRoute - '/auth-docs': typeof AuthDocsRouteWithChildren '/client-only': typeof ClientOnlyRoute '/deferred': typeof DeferredRoute - '/execution-local': typeof ExecutionLocalRoute - '/execution-rpc': typeof ExecutionRpcRoute '/inline-scripts': typeof InlineScriptsRoute '/links': typeof LinksRoute - '/plain-ts-type-assertion': typeof PlainTsTypeAssertionRoute '/posts': typeof PostsRouteWithChildren - '/primitive-beforeload-error': typeof PrimitiveBeforeloadErrorRoute '/raw-stream': typeof RawStreamRouteWithChildren '/scripts': typeof ScriptsRoute '/stream': typeof StreamRoute @@ -507,8 +453,6 @@ export interface FileRoutesByFullPath { '/not-found/parent-boundary': typeof NotFoundParentBoundaryRouteRouteWithChildren '/specialChars/malformed': typeof SpecialCharsMalformedRouteRouteWithChildren '/api/users': typeof ApiUsersRouteWithChildren - '/auth-docs/private': typeof AuthDocsPrivateRoute - '/issue-6221/dashboard': typeof Issue6221DashboardRoute '/multi-cookie-redirect/target': typeof MultiCookieRedirectTargetRoute '/not-found/via-beforeLoad': typeof NotFoundViaBeforeLoadRoute '/not-found/via-beforeLoad-target-root': typeof NotFoundViaBeforeLoadTargetRootRoute @@ -539,7 +483,6 @@ export interface FileRoutesByFullPath { '/layout-a': typeof LayoutLayout2LayoutARoute '/layout-b': typeof LayoutLayout2LayoutBRoute '/api/users/$id': typeof ApiUsersIdRoute - '/issue-6221/article/$id': typeof Issue6221ArticleIdRoute '/not-found/parent-boundary/via-beforeLoad': typeof NotFoundParentBoundaryViaBeforeLoadRoute '/posts/$postId/deep': typeof PostsPostIdDeepRoute '/redirect/$target/via-beforeLoad': typeof RedirectTargetViaBeforeLoadRoute @@ -562,22 +505,15 @@ 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 '/type-only-reexport': typeof TypeOnlyReexportRoute '/specialChars/malformed': typeof SpecialCharsMalformedRouteRouteWithChildren '/api/users': typeof ApiUsersRouteWithChildren - '/auth-docs/private': typeof AuthDocsPrivateRoute - '/issue-6221/dashboard': typeof Issue6221DashboardRoute '/multi-cookie-redirect/target': typeof MultiCookieRedirectTargetRoute '/not-found/via-beforeLoad': typeof NotFoundViaBeforeLoadRoute '/not-found/via-beforeLoad-target-root': typeof NotFoundViaBeforeLoadTargetRootRoute @@ -607,7 +543,6 @@ export interface FileRoutesByTo { '/layout-a': typeof LayoutLayout2LayoutARoute '/layout-b': typeof LayoutLayout2LayoutBRoute '/api/users/$id': typeof ApiUsersIdRoute - '/issue-6221/article/$id': typeof Issue6221ArticleIdRoute '/not-found/parent-boundary/via-beforeLoad': typeof NotFoundParentBoundaryViaBeforeLoadRoute '/posts/$postId/deep': typeof PostsPostIdDeepRoute '/redirect/$target/via-beforeLoad': typeof RedirectTargetViaBeforeLoadRoute @@ -633,16 +568,11 @@ export interface FileRoutesById { '/specialChars': typeof SpecialCharsRouteRouteWithChildren '/_layout': typeof LayoutRouteWithChildren '/async-scripts': typeof AsyncScriptsRoute - '/auth-docs': typeof AuthDocsRouteWithChildren '/client-only': typeof ClientOnlyRoute '/deferred': typeof DeferredRoute - '/execution-local': typeof ExecutionLocalRoute - '/execution-rpc': typeof ExecutionRpcRoute '/inline-scripts': typeof InlineScriptsRoute '/links': typeof LinksRoute - '/plain-ts-type-assertion': typeof PlainTsTypeAssertionRoute '/posts': typeof PostsRouteWithChildren - '/primitive-beforeload-error': typeof PrimitiveBeforeloadErrorRoute '/raw-stream': typeof RawStreamRouteWithChildren '/scripts': typeof ScriptsRoute '/stream': typeof StreamRoute @@ -653,8 +583,6 @@ export interface FileRoutesById { '/specialChars/malformed': typeof SpecialCharsMalformedRouteRouteWithChildren '/_layout/_layout-2': typeof LayoutLayout2RouteWithChildren '/api/users': typeof ApiUsersRouteWithChildren - '/auth-docs/private': typeof AuthDocsPrivateRoute - '/issue-6221/dashboard': typeof Issue6221DashboardRoute '/multi-cookie-redirect/target': typeof MultiCookieRedirectTargetRoute '/not-found/via-beforeLoad': typeof NotFoundViaBeforeLoadRoute '/not-found/via-beforeLoad-target-root': typeof NotFoundViaBeforeLoadTargetRootRoute @@ -685,7 +613,6 @@ export interface FileRoutesById { '/_layout/_layout-2/layout-a': typeof LayoutLayout2LayoutARoute '/_layout/_layout-2/layout-b': typeof LayoutLayout2LayoutBRoute '/api/users/$id': typeof ApiUsersIdRoute - '/issue-6221/article/$id': typeof Issue6221ArticleIdRoute '/not-found/parent-boundary/via-beforeLoad': typeof NotFoundParentBoundaryViaBeforeLoadRoute '/posts_/$postId/deep': typeof PostsPostIdDeepRoute '/redirect/$target/via-beforeLoad': typeof RedirectTargetViaBeforeLoadRoute @@ -712,16 +639,11 @@ export interface FileRouteTypes { | '/search-params' | '/specialChars' | '/async-scripts' - | '/auth-docs' | '/client-only' | '/deferred' - | '/execution-local' - | '/execution-rpc' | '/inline-scripts' | '/links' - | '/plain-ts-type-assertion' | '/posts' - | '/primitive-beforeload-error' | '/raw-stream' | '/scripts' | '/stream' @@ -731,8 +653,6 @@ export interface FileRouteTypes { | '/not-found/parent-boundary' | '/specialChars/malformed' | '/api/users' - | '/auth-docs/private' - | '/issue-6221/dashboard' | '/multi-cookie-redirect/target' | '/not-found/via-beforeLoad' | '/not-found/via-beforeLoad-target-root' @@ -763,7 +683,6 @@ export interface FileRouteTypes { | '/layout-a' | '/layout-b' | '/api/users/$id' - | '/issue-6221/article/$id' | '/not-found/parent-boundary/via-beforeLoad' | '/posts/$postId/deep' | '/redirect/$target/via-beforeLoad' @@ -786,22 +705,15 @@ export interface FileRouteTypes { | '/' | '/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-beforeLoad-target-root' @@ -831,7 +743,6 @@ export interface FileRouteTypes { | '/layout-a' | '/layout-b' | '/api/users/$id' - | '/issue-6221/article/$id' | '/not-found/parent-boundary/via-beforeLoad' | '/posts/$postId/deep' | '/redirect/$target/via-beforeLoad' @@ -856,16 +767,11 @@ export interface FileRouteTypes { | '/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' @@ -876,8 +782,6 @@ export interface FileRouteTypes { | '/specialChars/malformed' | '/_layout/_layout-2' | '/api/users' - | '/auth-docs/private' - | '/issue-6221/dashboard' | '/multi-cookie-redirect/target' | '/not-found/via-beforeLoad' | '/not-found/via-beforeLoad-target-root' @@ -908,7 +812,6 @@ export interface FileRouteTypes { | '/_layout/_layout-2/layout-a' | '/_layout/_layout-2/layout-b' | '/api/users/$id' - | '/issue-6221/article/$id' | '/not-found/parent-boundary/via-beforeLoad' | '/posts_/$postId/deep' | '/redirect/$target/via-beforeLoad' @@ -935,165 +838,32 @@ export interface RootRouteChildren { SpecialCharsRouteRoute: typeof SpecialCharsRouteRouteWithChildren LayoutRoute: typeof LayoutRouteWithChildren AsyncScriptsRoute: typeof AsyncScriptsRoute - AuthDocsRoute: typeof AuthDocsRouteWithChildren ClientOnlyRoute: typeof ClientOnlyRoute DeferredRoute: typeof DeferredRoute - ExecutionLocalRoute: typeof ExecutionLocalRoute - ExecutionRpcRoute: typeof ExecutionRpcRoute InlineScriptsRoute: typeof InlineScriptsRoute LinksRoute: typeof LinksRoute - PlainTsTypeAssertionRoute: typeof PlainTsTypeAssertionRoute PostsRoute: typeof PostsRouteWithChildren - PrimitiveBeforeloadErrorRoute: typeof PrimitiveBeforeloadErrorRoute RawStreamRoute: typeof RawStreamRouteWithChildren ScriptsRoute: typeof ScriptsRoute StreamRoute: typeof StreamRoute TypeOnlyReexportRoute: typeof TypeOnlyReexportRoute UsersRoute: typeof UsersRouteWithChildren ApiUsersRoute: typeof ApiUsersRouteWithChildren - Issue6221DashboardRoute: typeof Issue6221DashboardRoute MultiCookieRedirectTargetRoute: typeof MultiCookieRedirectTargetRoute RedirectTargetRoute: typeof RedirectTargetRouteWithChildren MultiCookieRedirectIndexRoute: typeof MultiCookieRedirectIndexRoute RedirectIndexRoute: typeof RedirectIndexRoute - Issue6221ArticleIdRoute: typeof Issue6221ArticleIdRoute PostsPostIdDeepRoute: typeof PostsPostIdDeepRoute FooBarQuxHereRoute: typeof FooBarQuxHereRouteWithChildren } declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_layout': { - id: '/_layout' - path: '' - fullPath: '/' - preLoaderRoute: typeof LayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/async-scripts': { - id: '/async-scripts' - path: '/async-scripts' - fullPath: '/async-scripts' - preLoaderRoute: typeof AsyncScriptsRouteImport - parentRoute: typeof rootRouteImport - } - '/auth-docs': { - id: '/auth-docs' - path: '/auth-docs' - fullPath: '/auth-docs' - preLoaderRoute: typeof AuthDocsRouteImport - parentRoute: typeof rootRouteImport - } - '/client-only': { - id: '/client-only' - path: '/client-only' - fullPath: '/client-only' - preLoaderRoute: typeof ClientOnlyRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport - parentRoute: typeof rootRouteImport - } - '/execution-local': { - id: '/execution-local' - path: '/execution-local' - fullPath: '/execution-local' - preLoaderRoute: typeof ExecutionLocalRouteImport - parentRoute: typeof rootRouteImport - } - '/execution-rpc': { - id: '/execution-rpc' - path: '/execution-rpc' - fullPath: '/execution-rpc' - preLoaderRoute: typeof ExecutionRpcRouteImport - parentRoute: typeof rootRouteImport - } - '/inline-scripts': { - id: '/inline-scripts' - path: '/inline-scripts' - fullPath: '/inline-scripts' - preLoaderRoute: typeof InlineScriptsRouteImport - parentRoute: typeof rootRouteImport - } - '/links': { - id: '/links' - path: '/links' - fullPath: '/links' - preLoaderRoute: typeof LinksRouteImport - parentRoute: typeof rootRouteImport - } - '/not-found': { - id: '/not-found' - path: '/not-found' - fullPath: '/not-found' - preLoaderRoute: typeof NotFoundRouteRouteImport - parentRoute: typeof rootRouteImport - } - '/plain-ts-type-assertion': { - id: '/plain-ts-type-assertion' - path: '/plain-ts-type-assertion' - fullPath: '/plain-ts-type-assertion' - preLoaderRoute: typeof PlainTsTypeAssertionRouteImport - parentRoute: typeof rootRouteImport - } - '/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 + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport parentRoute: typeof rootRouteImport } '/type-only-reexport': { @@ -1103,173 +873,110 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof TypeOnlyReexportRouteImport parentRoute: typeof rootRouteImport } - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport + '/stream': { + id: '/stream' + path: '/stream' + fullPath: '/stream' + preLoaderRoute: typeof StreamRouteImport parentRoute: typeof rootRouteImport } - '/_layout/_layout-2': { - id: '/_layout/_layout-2' + '/scripts': { + id: '/scripts' + path: '/scripts' + fullPath: '/scripts' + preLoaderRoute: typeof ScriptsRouteImport + parentRoute: typeof rootRouteImport + } + '/raw-stream': { + id: '/raw-stream' + path: '/raw-stream' + fullPath: '/raw-stream' + preLoaderRoute: typeof RawStreamRouteImport + parentRoute: typeof rootRouteImport + } + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } + '/links': { + id: '/links' + path: '/links' + fullPath: '/links' + preLoaderRoute: typeof LinksRouteImport + parentRoute: typeof rootRouteImport + } + '/inline-scripts': { + id: '/inline-scripts' + path: '/inline-scripts' + fullPath: '/inline-scripts' + preLoaderRoute: typeof InlineScriptsRouteImport + parentRoute: typeof rootRouteImport + } + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport + parentRoute: typeof rootRouteImport + } + '/client-only': { + id: '/client-only' + path: '/client-only' + fullPath: '/client-only' + preLoaderRoute: typeof ClientOnlyRouteImport + parentRoute: typeof rootRouteImport + } + '/async-scripts': { + id: '/async-scripts' + path: '/async-scripts' + fullPath: '/async-scripts' + preLoaderRoute: typeof AsyncScriptsRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout': { + id: '/_layout' path: '' fullPath: '/' - preLoaderRoute: typeof LayoutLayout2RouteImport - parentRoute: typeof LayoutRoute - } - '/api/users': { - id: '/api/users' - path: '/api/users' - fullPath: '/api/users' - preLoaderRoute: typeof ApiUsersRouteImport + preLoaderRoute: typeof LayoutRouteImport parentRoute: typeof rootRouteImport } - '/auth-docs/private': { - id: '/auth-docs/private' - path: '/private' - fullPath: '/auth-docs/private' - preLoaderRoute: typeof AuthDocsPrivateRouteImport - parentRoute: typeof AuthDocsRoute - } - '/issue-6221/dashboard': { - id: '/issue-6221/dashboard' - path: '/issue-6221/dashboard' - fullPath: '/issue-6221/dashboard' - preLoaderRoute: typeof Issue6221DashboardRouteImport + '/specialChars': { + id: '/specialChars' + path: '/specialChars' + fullPath: '/specialChars' + preLoaderRoute: typeof SpecialCharsRouteRouteImport parentRoute: typeof rootRouteImport } - '/multi-cookie-redirect/': { - id: '/multi-cookie-redirect/' - path: '/multi-cookie-redirect' - fullPath: '/multi-cookie-redirect/' - preLoaderRoute: typeof MultiCookieRedirectIndexRouteImport + '/search-params': { + id: '/search-params' + path: '/search-params' + fullPath: '/search-params' + preLoaderRoute: typeof SearchParamsRouteRouteImport 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 + '/not-found': { + id: '/not-found' + path: '/not-found' + fullPath: '/not-found' + preLoaderRoute: typeof NotFoundRouteRouteImport parentRoute: typeof rootRouteImport } - '/not-found/': { - id: '/not-found/' + '/': { + id: '/' path: '/' - fullPath: '/not-found/' - preLoaderRoute: typeof NotFoundIndexRouteImport - parentRoute: typeof NotFoundRouteRoute - } - '/not-found/deep': { - id: '/not-found/deep' - path: '/deep' - fullPath: '/not-found/deep' - preLoaderRoute: typeof NotFoundDeepRouteRouteImport - parentRoute: typeof NotFoundRouteRoute - } - '/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': { - id: '/not-found/via-beforeLoad' - path: '/via-beforeLoad' - fullPath: '/not-found/via-beforeLoad' - preLoaderRoute: typeof NotFoundViaBeforeLoadRouteImport - parentRoute: typeof NotFoundRouteRoute - } - '/not-found/via-beforeLoad-target-root': { - id: '/not-found/via-beforeLoad-target-root' - path: '/via-beforeLoad-target-root' - fullPath: '/not-found/via-beforeLoad-target-root' - preLoaderRoute: typeof NotFoundViaBeforeLoadTargetRootRouteImport - parentRoute: typeof NotFoundRouteRoute - } - '/not-found/via-loader': { - id: '/not-found/via-loader' - path: '/via-loader' - fullPath: '/not-found/via-loader' - preLoaderRoute: typeof NotFoundViaLoaderRouteImport - parentRoute: typeof NotFoundRouteRoute - } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute - } - '/raw-stream/': { - id: '/raw-stream/' - path: '/' - fullPath: '/raw-stream/' - preLoaderRoute: typeof RawStreamIndexRouteImport - parentRoute: typeof RawStreamRoute - } - '/raw-stream/client-call': { - id: '/raw-stream/client-call' - path: '/client-call' - fullPath: '/raw-stream/client-call' - preLoaderRoute: typeof RawStreamClientCallRouteImport - parentRoute: typeof RawStreamRoute - } - '/raw-stream/ssr-binary-hint': { - id: '/raw-stream/ssr-binary-hint' - path: '/ssr-binary-hint' - fullPath: '/raw-stream/ssr-binary-hint' - preLoaderRoute: typeof RawStreamSsrBinaryHintRouteImport - parentRoute: typeof RawStreamRoute - } - '/raw-stream/ssr-mixed': { - id: '/raw-stream/ssr-mixed' - path: '/ssr-mixed' - fullPath: '/raw-stream/ssr-mixed' - preLoaderRoute: typeof RawStreamSsrMixedRouteImport - parentRoute: typeof RawStreamRoute - } - '/raw-stream/ssr-multiple': { - id: '/raw-stream/ssr-multiple' - path: '/ssr-multiple' - fullPath: '/raw-stream/ssr-multiple' - preLoaderRoute: typeof RawStreamSsrMultipleRouteImport - parentRoute: typeof RawStreamRoute - } - '/raw-stream/ssr-single': { - id: '/raw-stream/ssr-single' - path: '/ssr-single' - fullPath: '/raw-stream/ssr-single' - preLoaderRoute: typeof RawStreamSsrSingleRouteImport - parentRoute: typeof RawStreamRoute - } - '/raw-stream/ssr-text-hint': { - id: '/raw-stream/ssr-text-hint' - path: '/ssr-text-hint' - fullPath: '/raw-stream/ssr-text-hint' - preLoaderRoute: typeof RawStreamSsrTextHintRouteImport - parentRoute: typeof RawStreamRoute - } - '/redirect/': { - id: '/redirect/' - path: '/redirect' - fullPath: '/redirect/' - preLoaderRoute: typeof RedirectIndexRouteImport + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/redirect/$target': { - id: '/redirect/$target' - path: '/redirect/$target' - fullPath: '/redirect/$target' - preLoaderRoute: typeof RedirectTargetRouteImport - parentRoute: typeof rootRouteImport + '/users/': { + id: '/users/' + path: '/' + fullPath: '/users/' + preLoaderRoute: typeof UsersIndexRouteImport + parentRoute: typeof UsersRoute } '/search-params/': { id: '/search-params/' @@ -1278,39 +985,53 @@ declare module '@tanstack/react-router' { 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 + '/redirect/': { + id: '/redirect/' + path: '/redirect' + fullPath: '/redirect/' + preLoaderRoute: typeof RedirectIndexRouteImport + parentRoute: typeof rootRouteImport } - '/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 + '/raw-stream/': { + id: '/raw-stream/' + path: '/' + fullPath: '/raw-stream/' + preLoaderRoute: typeof RawStreamIndexRouteImport + parentRoute: typeof RawStreamRoute } - '/specialChars/$param': { - id: '/specialChars/$param' - path: '/$param' - fullPath: '/specialChars/$param' - preLoaderRoute: typeof SpecialCharsParamRouteImport - parentRoute: typeof SpecialCharsRouteRoute + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRoute } - '/specialChars/hash': { - id: '/specialChars/hash' - path: '/hash' - fullPath: '/specialChars/hash' - preLoaderRoute: typeof SpecialCharsHashRouteImport - parentRoute: typeof SpecialCharsRouteRoute + '/not-found/': { + id: '/not-found/' + path: '/' + fullPath: '/not-found/' + preLoaderRoute: typeof NotFoundIndexRouteImport + parentRoute: typeof NotFoundRouteRoute } - '/specialChars/malformed': { - id: '/specialChars/malformed' - path: '/malformed' - fullPath: '/specialChars/malformed' - preLoaderRoute: typeof SpecialCharsMalformedRouteRouteImport + '/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 + } + '/specialChars/대한민국': { + id: '/specialChars/대한민국' + path: '/대한민국' + fullPath: '/specialChars/대한민국' + preLoaderRoute: typeof SpecialCharsChar45824Char54620Char48124Char44397RouteImport parentRoute: typeof SpecialCharsRouteRoute } '/specialChars/search': { @@ -1320,68 +1041,159 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof SpecialCharsSearchRouteImport parentRoute: typeof SpecialCharsRouteRoute } - '/specialChars/대한민국': { - id: '/specialChars/대한민국' - path: '/대한민국' - fullPath: '/specialChars/대한민국' - preLoaderRoute: typeof SpecialCharsChar45824Char54620Char48124Char44397RouteImport + '/specialChars/hash': { + id: '/specialChars/hash' + path: '/hash' + fullPath: '/specialChars/hash' + preLoaderRoute: typeof SpecialCharsHashRouteImport parentRoute: typeof SpecialCharsRouteRoute } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute + '/specialChars/$param': { + id: '/specialChars/$param' + path: '/$param' + fullPath: '/specialChars/$param' + preLoaderRoute: typeof SpecialCharsParamRouteImport + parentRoute: typeof SpecialCharsRouteRoute } - '/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 } - '/_layout/_layout-2/layout-a': { - id: '/_layout/_layout-2/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof LayoutLayout2LayoutARouteImport - parentRoute: typeof LayoutLayout2Route + '/search-params/default': { + id: '/search-params/default' + path: '/default' + fullPath: '/search-params/default' + preLoaderRoute: typeof SearchParamsDefaultRouteImport + parentRoute: typeof SearchParamsRouteRoute } - '/_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 + '/redirect/$target': { + id: '/redirect/$target' + path: '/redirect/$target' + fullPath: '/redirect/$target' + preLoaderRoute: typeof RedirectTargetRouteImport parentRoute: typeof rootRouteImport } - '/not-found/deep/': { - id: '/not-found/deep/' - path: '/' - fullPath: '/not-found/deep/' - preLoaderRoute: typeof NotFoundDeepIndexRouteImport - parentRoute: typeof NotFoundDeepRouteRoute + '/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 } - '/not-found/deep/b': { - id: '/not-found/deep/b' - path: '/b' - fullPath: '/not-found/deep/b' - preLoaderRoute: typeof NotFoundDeepBRouteRouteImport - parentRoute: typeof NotFoundDeepRouteRoute + '/raw-stream/ssr-single': { + id: '/raw-stream/ssr-single' + path: '/ssr-single' + fullPath: '/raw-stream/ssr-single' + preLoaderRoute: typeof RawStreamSsrSingleRouteImport + parentRoute: typeof RawStreamRoute + } + '/raw-stream/ssr-multiple': { + id: '/raw-stream/ssr-multiple' + path: '/ssr-multiple' + fullPath: '/raw-stream/ssr-multiple' + preLoaderRoute: typeof RawStreamSsrMultipleRouteImport + parentRoute: typeof RawStreamRoute + } + '/raw-stream/ssr-mixed': { + id: '/raw-stream/ssr-mixed' + path: '/ssr-mixed' + fullPath: '/raw-stream/ssr-mixed' + preLoaderRoute: typeof RawStreamSsrMixedRouteImport + parentRoute: typeof RawStreamRoute + } + '/raw-stream/ssr-binary-hint': { + id: '/raw-stream/ssr-binary-hint' + path: '/ssr-binary-hint' + fullPath: '/raw-stream/ssr-binary-hint' + preLoaderRoute: typeof RawStreamSsrBinaryHintRouteImport + parentRoute: typeof RawStreamRoute + } + '/raw-stream/client-call': { + id: '/raw-stream/client-call' + path: '/client-call' + fullPath: '/raw-stream/client-call' + preLoaderRoute: typeof RawStreamClientCallRouteImport + parentRoute: typeof RawStreamRoute + } + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRoute + } + '/not-found/via-loader': { + id: '/not-found/via-loader' + path: '/via-loader' + fullPath: '/not-found/via-loader' + preLoaderRoute: typeof NotFoundViaLoaderRouteImport + parentRoute: typeof NotFoundRouteRoute + } + '/not-found/via-beforeLoad-target-root': { + id: '/not-found/via-beforeLoad-target-root' + path: '/via-beforeLoad-target-root' + fullPath: '/not-found/via-beforeLoad-target-root' + preLoaderRoute: typeof NotFoundViaBeforeLoadTargetRootRouteImport + parentRoute: typeof NotFoundRouteRoute + } + '/not-found/via-beforeLoad': { + id: '/not-found/via-beforeLoad' + path: '/via-beforeLoad' + fullPath: '/not-found/via-beforeLoad' + preLoaderRoute: typeof NotFoundViaBeforeLoadRouteImport + parentRoute: typeof NotFoundRouteRoute + } + '/multi-cookie-redirect/target': { + id: '/multi-cookie-redirect/target' + path: '/multi-cookie-redirect/target' + fullPath: '/multi-cookie-redirect/target' + preLoaderRoute: typeof MultiCookieRedirectTargetRouteImport + parentRoute: typeof rootRouteImport + } + '/api/users': { + id: '/api/users' + path: '/api/users' + fullPath: '/api/users' + preLoaderRoute: typeof ApiUsersRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout/_layout-2': { + id: '/_layout/_layout-2' + path: '' + fullPath: '/' + preLoaderRoute: typeof LayoutLayout2RouteImport + parentRoute: typeof LayoutRoute + } + '/specialChars/malformed': { + id: '/specialChars/malformed' + path: '/malformed' + fullPath: '/specialChars/malformed' + preLoaderRoute: typeof SpecialCharsMalformedRouteRouteImport + parentRoute: typeof SpecialCharsRouteRoute + } + '/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/deep': { + id: '/not-found/deep' + path: '/deep' + fullPath: '/not-found/deep' + preLoaderRoute: typeof NotFoundDeepRouteRouteImport + parentRoute: typeof NotFoundRouteRoute + } + '/redirect/$target/': { + id: '/redirect/$target/' + path: '/' + fullPath: '/redirect/$target/' + preLoaderRoute: typeof RedirectTargetIndexRouteImport + parentRoute: typeof RedirectTargetRoute } '/not-found/parent-boundary/': { id: '/not-found/parent-boundary/' @@ -1390,25 +1202,32 @@ declare module '@tanstack/react-router' { 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/' + '/not-found/deep/': { + id: '/not-found/deep/' path: '/' - fullPath: '/redirect/$target/' - preLoaderRoute: typeof RedirectTargetIndexRouteImport + fullPath: '/not-found/deep/' + preLoaderRoute: typeof NotFoundDeepIndexRouteImport + parentRoute: typeof NotFoundDeepRouteRoute + } + '/specialChars/malformed/search': { + id: '/specialChars/malformed/search' + path: '/search' + fullPath: '/specialChars/malformed/search' + preLoaderRoute: typeof SpecialCharsMalformedSearchRouteImport + parentRoute: typeof SpecialCharsMalformedRouteRoute + } + '/specialChars/malformed/$param': { + id: '/specialChars/malformed/$param' + path: '/$param' + fullPath: '/specialChars/malformed/$param' + preLoaderRoute: typeof SpecialCharsMalformedParamRouteImport + parentRoute: typeof SpecialCharsMalformedRouteRoute + } + '/redirect/$target/via-loader': { + id: '/redirect/$target/via-loader' + path: '/via-loader' + fullPath: '/redirect/$target/via-loader' + preLoaderRoute: typeof RedirectTargetViaLoaderRouteImport parentRoute: typeof RedirectTargetRoute } '/redirect/$target/via-beforeLoad': { @@ -1418,26 +1237,75 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof RedirectTargetViaBeforeLoadRouteImport parentRoute: typeof RedirectTargetRoute } - '/redirect/$target/via-loader': { - id: '/redirect/$target/via-loader' - path: '/via-loader' - fullPath: '/redirect/$target/via-loader' - preLoaderRoute: typeof RedirectTargetViaLoaderRouteImport + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport + parentRoute: typeof rootRouteImport + } + '/not-found/parent-boundary/via-beforeLoad': { + id: '/not-found/parent-boundary/via-beforeLoad' + path: '/via-beforeLoad' + fullPath: '/not-found/parent-boundary/via-beforeLoad' + preLoaderRoute: typeof NotFoundParentBoundaryViaBeforeLoadRouteImport + parentRoute: typeof NotFoundParentBoundaryRouteRoute + } + '/api/users/$id': { + id: '/api/users/$id' + path: '/$id' + fullPath: '/api/users/$id' + preLoaderRoute: typeof ApiUsersIdRouteImport + parentRoute: typeof ApiUsersRoute + } + '/_layout/_layout-2/layout-b': { + id: '/_layout/_layout-2/layout-b' + path: '/layout-b' + fullPath: '/layout-b' + preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport + parentRoute: typeof LayoutLayout2Route + } + '/_layout/_layout-2/layout-a': { + id: '/_layout/_layout-2/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof LayoutLayout2LayoutARouteImport + parentRoute: typeof LayoutLayout2Route + } + '/not-found/deep/b': { + id: '/not-found/deep/b' + path: '/b' + fullPath: '/not-found/deep/b' + preLoaderRoute: typeof NotFoundDeepBRouteRouteImport + parentRoute: typeof NotFoundDeepRouteRoute + } + '/redirect/$target/serverFn/': { + id: '/redirect/$target/serverFn/' + path: '/serverFn' + fullPath: '/redirect/$target/serverFn/' + preLoaderRoute: typeof RedirectTargetServerFnIndexRouteImport parentRoute: typeof RedirectTargetRoute } - '/specialChars/malformed/$param': { - id: '/specialChars/malformed/$param' - path: '/$param' - fullPath: '/specialChars/malformed/$param' - preLoaderRoute: typeof SpecialCharsMalformedParamRouteImport - parentRoute: typeof SpecialCharsMalformedRouteRoute + '/redirect/$target/serverFn/via-useServerFn': { + id: '/redirect/$target/serverFn/via-useServerFn' + path: '/serverFn/via-useServerFn' + fullPath: '/redirect/$target/serverFn/via-useServerFn' + preLoaderRoute: typeof RedirectTargetServerFnViaUseServerFnRouteImport + parentRoute: typeof RedirectTargetRoute } - '/specialChars/malformed/search': { - id: '/specialChars/malformed/search' - path: '/search' - fullPath: '/specialChars/malformed/search' - preLoaderRoute: typeof SpecialCharsMalformedSearchRouteImport - parentRoute: typeof SpecialCharsMalformedRouteRoute + '/redirect/$target/serverFn/via-loader': { + id: '/redirect/$target/serverFn/via-loader' + path: '/serverFn/via-loader' + fullPath: '/redirect/$target/serverFn/via-loader' + preLoaderRoute: typeof RedirectTargetServerFnViaLoaderRouteImport + parentRoute: typeof RedirectTargetRoute + } + '/redirect/$target/serverFn/via-beforeLoad': { + id: '/redirect/$target/serverFn/via-beforeLoad' + path: '/serverFn/via-beforeLoad' + fullPath: '/redirect/$target/serverFn/via-beforeLoad' + preLoaderRoute: typeof RedirectTargetServerFnViaBeforeLoadRouteImport + parentRoute: typeof RedirectTargetRoute } '/foo/$bar/$qux/_here': { id: '/foo/$bar/$qux/_here' @@ -1453,34 +1321,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof NotFoundDeepBCRouteRouteImport parentRoute: typeof NotFoundDeepBRouteRoute } - '/redirect/$target/serverFn/': { - id: '/redirect/$target/serverFn/' - path: '/serverFn' - fullPath: '/redirect/$target/serverFn/' - preLoaderRoute: typeof RedirectTargetServerFnIndexRouteImport - parentRoute: typeof RedirectTargetRoute - } - '/redirect/$target/serverFn/via-beforeLoad': { - id: '/redirect/$target/serverFn/via-beforeLoad' - path: '/serverFn/via-beforeLoad' - fullPath: '/redirect/$target/serverFn/via-beforeLoad' - preLoaderRoute: typeof RedirectTargetServerFnViaBeforeLoadRouteImport - parentRoute: typeof RedirectTargetRoute - } - '/redirect/$target/serverFn/via-loader': { - id: '/redirect/$target/serverFn/via-loader' - path: '/serverFn/via-loader' - fullPath: '/redirect/$target/serverFn/via-loader' - preLoaderRoute: typeof RedirectTargetServerFnViaLoaderRouteImport - parentRoute: typeof RedirectTargetRoute - } - '/redirect/$target/serverFn/via-useServerFn': { - id: '/redirect/$target/serverFn/via-useServerFn' - path: '/serverFn/via-useServerFn' - fullPath: '/redirect/$target/serverFn/via-useServerFn' - preLoaderRoute: typeof RedirectTargetServerFnViaUseServerFnRouteImport - parentRoute: typeof RedirectTargetRoute - } '/foo/$bar/$qux/_here/': { id: '/foo/$bar/$qux/_here/' path: '/' @@ -1649,18 +1489,6 @@ 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 @@ -1766,28 +1594,21 @@ const rootRouteChildren: RootRouteChildren = { SpecialCharsRouteRoute: SpecialCharsRouteRouteWithChildren, LayoutRoute: LayoutRouteWithChildren, AsyncScriptsRoute: AsyncScriptsRoute, - AuthDocsRoute: AuthDocsRouteWithChildren, ClientOnlyRoute: ClientOnlyRoute, DeferredRoute: DeferredRoute, - ExecutionLocalRoute: ExecutionLocalRoute, - ExecutionRpcRoute: ExecutionRpcRoute, InlineScriptsRoute: InlineScriptsRoute, LinksRoute: LinksRoute, - PlainTsTypeAssertionRoute: PlainTsTypeAssertionRoute, PostsRoute: PostsRouteWithChildren, - PrimitiveBeforeloadErrorRoute: PrimitiveBeforeloadErrorRoute, RawStreamRoute: RawStreamRouteWithChildren, ScriptsRoute: ScriptsRoute, StreamRoute: StreamRoute, TypeOnlyReexportRoute: TypeOnlyReexportRoute, UsersRoute: UsersRouteWithChildren, ApiUsersRoute: ApiUsersRouteWithChildren, - Issue6221DashboardRoute: Issue6221DashboardRoute, MultiCookieRedirectTargetRoute: MultiCookieRedirectTargetRoute, RedirectTargetRoute: RedirectTargetRouteWithChildren, MultiCookieRedirectIndexRoute: MultiCookieRedirectIndexRoute, RedirectIndexRoute: RedirectIndexRoute, - Issue6221ArticleIdRoute: Issue6221ArticleIdRoute, PostsPostIdDeepRoute: PostsPostIdDeepRoute, FooBarQuxHereRoute: FooBarQuxHereRouteWithChildren, } diff --git a/e2e/react-start/basic/src/routes/__root.tsx b/e2e/react-start/basic/src/routes/__root.tsx index ed521817d6..fe0d374888 100644 --- a/e2e/react-start/basic/src/routes/__root.tsx +++ b/e2e/react-start/basic/src/routes/__root.tsx @@ -1,18 +1,16 @@ /// 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 '~/styles/app.css' +import appCss from '~/styles/app.css?url' import { seo } from '~/utils/seo' export const Route = createRootRoute({ @@ -32,6 +30,7 @@ export const Route = createRootRoute({ }), ], links: [ + { rel: 'stylesheet', href: appCss }, { rel: 'apple-touch-icon', sizes: '180x180', @@ -94,11 +93,6 @@ const RouterDevtools = ) function RootDocument({ children }: { children: React.ReactNode }) { - const { isLoading, status } = useRouterState({ - select: (state) => ({ isLoading: state.isLoading, status: state.status }), - structuralSharing: true, - }) - return ( @@ -197,9 +191,6 @@ function RootDocument({ children }: { children: React.ReactNode }) { > Client Only {' '} - - Server function loader - {' '}

- - - {children}
This is an inline styled div
diff --git a/e2e/react-start/basic/src/routes/api.users.ts b/e2e/react-start/basic/src/routes/api.users.ts index d6fff7c5af..9e055549ef 100644 --- a/e2e/react-start/basic/src/routes/api.users.ts +++ b/e2e/react-start/basic/src/routes/api.users.ts @@ -3,14 +3,18 @@ import axios from 'redaxios' import type { User } from '~/utils/users' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} + export const Route = createFileRoute('/api/users')({ server: { handlers: { GET: async ({ request }) => { console.info('Fetching users... @', request.url) - const res = await axios.get>( - 'https://jsonplaceholder.typicode.com/users', - ) + const res = await axios.get>(`${queryURL}/users`) const list = res.data.slice(0, 10) diff --git a/e2e/react-start/basic/src/routes/api/users.$id.ts b/e2e/react-start/basic/src/routes/api/users.$id.ts index 797dffb637..ac665381f1 100644 --- a/e2e/react-start/basic/src/routes/api/users.$id.ts +++ b/e2e/react-start/basic/src/routes/api/users.$id.ts @@ -2,15 +2,19 @@ import { createFileRoute } from '@tanstack/react-router' import axios from 'redaxios' import type { User } from '~/utils/users' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} + export const Route = createFileRoute('/api/users/$id')({ server: { handlers: { GET: async ({ request, params }) => { console.info(`Fetching users by id=${params.id}... @`, request.url) try { - const res = await axios.get( - `https://jsonplaceholder.typicode.com/users/${params.id}`, - ) + const res = await axios.get(`${queryURL}/users/` + params.id) return Response.json({ id: res.data.id, diff --git a/e2e/react-start/basic/src/routes/auth-docs.private.tsx b/e2e/react-start/basic/src/routes/auth-docs.private.tsx deleted file mode 100644 index 85fc8a0fc9..0000000000 --- a/e2e/react-start/basic/src/routes/auth-docs.private.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import { createFileRoute, redirect } from '@tanstack/react-router' -import { getPrivateDataFn } from '../utils/auth-docs' - -export const Route = createFileRoute('/auth-docs/private')({ - beforeLoad: ({ context }) => { - if (!context.user) { - throw redirect({ to: '/auth-docs' }) - } - }, - loader: () => getPrivateDataFn(), - component: PrivatePage, -}) - -function PrivatePage() { - const message = Route.useLoaderData() - return

{message}

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

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

-
-
- - - -
-

{error}

-
- - -

{privateResult}

- -
- ) -} diff --git a/e2e/react-start/basic/src/routes/deferred.tsx b/e2e/react-start/basic/src/routes/deferred.tsx index a6bd45f8c2..9c6e3064b8 100644 --- a/e2e/react-start/basic/src/routes/deferred.tsx +++ b/e2e/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' }) - .validator((data: { name: string }) => data) + .inputValidator((data: { name: string }) => data) .handler(({ data }) => { return { name: data.name, randomNumber: Math.floor(Math.random() * 100) } }) const slowServerFn = createServerFn({ method: 'GET' }) - .validator((data: { name: string }) => data) + .inputValidator((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/react-start/basic/src/routes/execution-local.tsx b/e2e/react-start/basic/src/routes/execution-local.tsx deleted file mode 100644 index 477cd81740..0000000000 --- a/e2e/react-start/basic/src/routes/execution-local.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { readOnlyOnServer } from '~/utils/execution-functions' - -// This intentionally fails during browser navigation. It is the negative case -// for the environment-functions troubleshooting guide. -export const Route = createFileRoute('/execution-local')({ - loader: () => readOnlyOnServer(), - component: Result, - errorComponent: ({ error }) => ( -

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

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

{Route.useLoaderData()}

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

{Route.useLoaderData()}

- - Call the server-only helper directly - - - ) -} diff --git a/e2e/react-start/basic/src/routes/issue-6221.article.$id.tsx b/e2e/react-start/basic/src/routes/issue-6221.article.$id.tsx deleted file mode 100644 index c923a5f1cb..0000000000 --- a/e2e/react-start/basic/src/routes/issue-6221.article.$id.tsx +++ /dev/null @@ -1,42 +0,0 @@ -import { Link, createFileRoute } from '@tanstack/react-router' -import { createClientOnlyFn } from '@tanstack/react-start' - -const isAuthed = createClientOnlyFn( - () => localStorage.getItem('issue-6221-auth') === 'good', -) - -const fetchArticle = async (id: string) => { - await new Promise((resolve) => setTimeout(resolve, 1000)) - return isAuthed() - ? { - title: `Article Title for ${id}`, - content: `Article content for ${id}`, - } - : null -} - -export const Route = createFileRoute('/issue-6221/article/$id')({ - ssr: false, - loader: ({ params }) => fetchArticle(params.id), - head: ({ loaderData }) => ({ - meta: [{ title: loaderData?.title ?? 'title n/a' }], - }), - component: Article, -}) - -function Article() { - const article = Route.useLoaderData() - - return ( -
- - Dashboard - - {article ? ( -
{article.content}
- ) : ( -
Article Not Accessible.
- )} -
- ) -} diff --git a/e2e/react-start/basic/src/routes/issue-6221.dashboard.tsx b/e2e/react-start/basic/src/routes/issue-6221.dashboard.tsx deleted file mode 100644 index 8c93da669c..0000000000 --- a/e2e/react-start/basic/src/routes/issue-6221.dashboard.tsx +++ /dev/null @@ -1,6 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/issue-6221/dashboard')({ - head: () => ({ meta: [{ title: 'Dashboard' }] }), - component: () =>
Dashboard
, -}) diff --git a/e2e/react-start/basic/src/routes/plain-ts-type-assertion.tsx b/e2e/react-start/basic/src/routes/plain-ts-type-assertion.tsx deleted file mode 100644 index 7538f2f14e..0000000000 --- a/e2e/react-start/basic/src/routes/plain-ts-type-assertion.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { cast } from '~/utils/cast' - -export const Route = createFileRoute('/plain-ts-type-assertion')({ - component: PlainTsTypeAssertion, -}) - -const regressionValue = cast('plain .ts cast parsed') - -function PlainTsTypeAssertion() { - return ( -
-

Plain TS Type Assertion

-

{regressionValue}

-
- ) -} diff --git a/e2e/react-start/basic/src/routes/posts.tsx b/e2e/react-start/basic/src/routes/posts.tsx index 22fb7e60a8..0f69c18341 100644 --- a/e2e/react-start/basic/src/routes/posts.tsx +++ b/e2e/react-start/basic/src/routes/posts.tsx @@ -1,4 +1,3 @@ -import { useState } from 'react' import { Link, Outlet, createFileRoute } from '@tanstack/react-router' import { fetchPosts } from '~/utils/posts' @@ -17,16 +16,9 @@ export const Route = createFileRoute('/posts')({ function PostsComponent() { const posts = Route.useLoaderData() - const [hydrationCount, setHydrationCount] = useState(0) return (
-
    {[...posts, { id: 'i-do-not-exist', title: 'Non-existent Post' }].map( (post) => { diff --git a/e2e/react-start/basic/src/routes/primitive-beforeload-error.tsx b/e2e/react-start/basic/src/routes/primitive-beforeload-error.tsx deleted file mode 100644 index e76ec5c73e..0000000000 --- a/e2e/react-start/basic/src/routes/primitive-beforeload-error.tsx +++ /dev/null @@ -1,21 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/primitive-beforeload-error')({ - beforeLoad: () => { - throw 'primitive beforeLoad error' - }, - component: () => { - return ( -
    - This should not render. -
    - ) - }, - errorComponent: ({ error }) => { - return ( -
    - {String(error)} -
    - ) - }, -}) diff --git a/e2e/react-start/basic/src/routes/raw-stream/client-call.tsx b/e2e/react-start/basic/src/routes/raw-stream/client-call.tsx index faf98c7a37..8179d56808 100644 --- a/e2e/react-start/basic/src/routes/raw-stream/client-call.tsx +++ b/e2e/react-start/basic/src/routes/raw-stream/client-call.tsx @@ -1,32 +1,6 @@ import { createFileRoute } from '@tanstack/react-router' import * as React from 'react' import { - singleRawStreamFn, - multipleRawStreamsFn, - jsonEndsFirstFn, - rawEndsFirstFn, - largeBinaryFn, - mixedStreamingFn, - textHintPureTextFn, - textHintPureBinaryFn, - textHintMixedFn, - binaryHintTextFn, - binaryHintBinaryFn, - interleavedStreamsFn, - burstPauseBurstFn, - threeStreamsFn, - emptyStreamFn, - errorStreamFn, - lateRawStreamFn, - multipleLateStreamsFn, - mixedImmediateLateFn, - createStreamConsumer, - consumeBinaryStream, - collectBytes, - compareBytes, - TEST7_EXPECTED, - TEST8_EXPECTED, - TEST9_EXPECTED, TEST10_EXPECTED, TEST11_EXPECTED, TEST12_STREAM_A_EXPECTED, @@ -35,10 +9,29 @@ import { TEST14_STREAM_A_EXPECTED, TEST14_STREAM_B_EXPECTED, TEST14_STREAM_C_EXPECTED, - LATE_STREAM_EXPECTED, - LATE_STREAM_A_EXPECTED, - LATE_STREAM_B_EXPECTED, - IMMEDIATE_STREAM_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' export const Route = createFileRoute('/raw-stream/client-call')({ @@ -556,109 +549,6 @@ function ClientCallTests() { {JSON.stringify(results.test16)}
- - {/* Late RawStream Tests Section */} -

Late RawStream Tests (RPC)

-

- These tests verify RawStreams wrapped in Promises (discovered after - initial serialization phase). -

- - {/* Test 17: Single Late RawStream */} -
-

Test 17: Single Late RawStream

- -
{JSON.stringify(results.test17)}
-
- - {/* Test 18: Multiple Late RawStreams */} -
-

Test 18: Multiple Late RawStreams

- -
{JSON.stringify(results.test18)}
-
- - {/* Test 19: Mixed Immediate and Late RawStreams */} -
-

- Test 19: Mixed Immediate and Late RawStreams -

- -
{JSON.stringify(results.test19)}
-
) } diff --git a/e2e/react-start/basic/src/routes/specialChars/search.tsx b/e2e/react-start/basic/src/routes/specialChars/search.tsx index 5840d425ab..152f39f527 100644 --- a/e2e/react-start/basic/src/routes/specialChars/search.tsx +++ b/e2e/react-start/basic/src/routes/specialChars/search.tsx @@ -1,36 +1,19 @@ import { createFileRoute } from '@tanstack/react-router' import z from 'zod' -const isBrowser = typeof window !== 'undefined' - export const Route = createFileRoute('/specialChars/search')({ validateSearch: z.object({ searchParam: z.string(), }), - beforeLoad: () => ({ - beforeLoadOn: isBrowser ? 'client' : 'server', - }), - loader: async () => { - console.log(`[loader] Running on ${isBrowser ? 'client' : 'server'}`) - return { - loadedOn: isBrowser ? 'client' : 'server', - } - }, component: RouteComponent, }) function RouteComponent() { const search = Route.useSearch() - const { beforeLoadOn } = Route.useRouteContext() - const { loadedOn } = Route.useLoaderData() return (
Hello "/specialChars/search"! -
- Before load on: {beforeLoadOn} -
-
Loaded on: {loadedOn}
{search.searchParam}
) diff --git a/e2e/react-start/basic/src/utils/auth-docs.ts b/e2e/react-start/basic/src/utils/auth-docs.ts deleted file mode 100644 index 22b36ee808..0000000000 --- a/e2e/react-start/basic/src/utils/auth-docs.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { createServerFn } from '@tanstack/react-start' -import { redirect } from '@tanstack/react-router' -import { getCookie, setCookie } from '@tanstack/react-start/server' -import { getIronSession } from 'iron-session' - -function getSession() { - return getIronSession<{ email: string }>( - { read: getCookie, write: setCookie }, - { - cookieName: 'auth-docs-test', - password: 'authentication-docs-browser-test-secret-only-2026', - ttl: 60 * 60, - cookieOptions: { - httpOnly: true, - secure: false, - sameSite: 'lax', - path: '/', - }, - }, - ) -} - -export const getCurrentUserFn = createServerFn({ method: 'GET' }).handler( - async () => { - const session = await getSession() - return session.email ? { email: session.email } : null - }, -) - -export const loginFn = createServerFn({ method: 'POST' }) - .validator((data: { email: string; password: string }) => data) - .handler(async ({ data }) => { - // Fixed credentials belong only to this browser-test fixture. - if ( - data.email !== 'reader@example.com' || - data.password !== 'test-password' - ) { - return { error: 'Invalid credentials' } - } - const session = await getSession() - session.email = data.email - await session.save() - throw redirect({ to: '/auth-docs/private' }) - }) - -export const logoutFn = createServerFn({ method: 'POST' }).handler(async () => { - const session = await getSession() - session.destroy() - throw redirect({ to: '/auth-docs' }) -}) - -export const getPrivateDataFn = createServerFn({ method: 'GET' }).handler( - async () => { - const session = await getSession() - if (!session.email) { - throw new Error('Unauthorized') - } - return 'Private account data' - }, -) diff --git a/e2e/react-start/basic/src/utils/cast.ts b/e2e/react-start/basic/src/utils/cast.ts deleted file mode 100644 index 65c76b343a..0000000000 --- a/e2e/react-start/basic/src/utils/cast.ts +++ /dev/null @@ -1,3 +0,0 @@ -export function cast(value: unknown): T { - return value -} diff --git a/e2e/react-start/basic/src/utils/execution-functions.ts b/e2e/react-start/basic/src/utils/execution-functions.ts deleted file mode 100644 index 97e66573d8..0000000000 --- a/e2e/react-start/basic/src/utils/execution-functions.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { createServerFn, createServerOnlyFn } from '@tanstack/react-start' - -export const readOnlyOnServer = createServerOnlyFn(() => 'Read on the server') - -export const readThroughRpc = createServerFn().handler(() => readOnlyOnServer()) diff --git a/e2e/react-start/basic/src/utils/posts.tsx b/e2e/react-start/basic/src/utils/posts.tsx index 9fdff27673..b2d9f3edec 100644 --- a/e2e/react-start/basic/src/utils/posts.tsx +++ b/e2e/react-start/basic/src/utils/posts.tsx @@ -8,12 +8,18 @@ export type PostType = { body: string } +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} + export const fetchPost = createServerFn({ method: 'GET' }) - .validator((postId: string) => postId) + .inputValidator((postId: string) => postId) .handler(async ({ data: postId }) => { console.info(`Fetching post with id ${postId}...`) const post = await axios - .get(`https://jsonplaceholder.typicode.com/posts/${postId}`) + .get(`${queryURL}/posts/${postId}`) .then((r) => r.data) .catch((err) => { console.error(err) @@ -30,7 +36,7 @@ export const fetchPosts = createServerFn({ method: 'GET' }).handler( async () => { console.info('Fetching posts...') return axios - .get>('https://jsonplaceholder.typicode.com/posts') + .get>(`${queryURL}/posts`) .then((r) => r.data.slice(0, 10)) }, ) diff --git a/e2e/react-start/basic/src/utils/users.tsx b/e2e/react-start/basic/src/utils/users.tsx index 7ba645b383..46be4b1580 100644 --- a/e2e/react-start/basic/src/utils/users.tsx +++ b/e2e/react-start/basic/src/utils/users.tsx @@ -3,3 +3,7 @@ export type User = { name: string email: string } + +const PORT = process.env.VITE_SERVER_PORT || 3000 + +export const DEPLOY_URL = `http://localhost:${PORT}` diff --git a/e2e/react-start/basic/start-mode-config.ts b/e2e/react-start/basic/start-mode-config.ts deleted file mode 100644 index 39ad676625..0000000000 --- a/e2e/react-start/basic/start-mode-config.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { isPrerender } from './tests/utils/isPrerender' -import { isSpaMode } from './tests/utils/isSpaMode' - -const rsbuildClientOutput: 'module' | 'iife' | undefined = (() => { - const output = process.env.TSS_RSB_CLIENT_OUTPUT - - if (output === undefined) return undefined - if (output === 'module') return 'module' - if (output === 'iife') return 'iife' - - throw new Error( - `Invalid TSS_RSB_CLIENT_OUTPUT: ${output}. Expected "module" or "iife".`, - ) -})() - -export function getStartModeConfig() { - return { - spa: isSpaMode - ? { - enabled: true, - prerender: { - outputPath: 'index.html', - }, - } - : undefined, - prerender: isPrerender - ? { - enabled: true, - filter: (page: { path: string }) => - ![ - '/this-route-does-not-exist', - '/redirect', - '/i-do-not-exist', - '/not-found', - '/primitive-beforeload-error', - '/specialChars/search', - '/specialChars/hash', - '/specialChars/malformed', - '/users', - ].some((p) => page.path.includes(p)), - maxRedirects: 100, - } - : undefined, - rsbuild: rsbuildClientOutput - ? { - client: { - output: rsbuildClientOutput, - }, - } - : undefined, - } -} diff --git a/e2e/react-start/basic/tests/auth-docs.spec.ts b/e2e/react-start/basic/tests/auth-docs.spec.ts deleted file mode 100644 index 47a57c9da2..0000000000 --- a/e2e/react-start/basic/tests/auth-docs.spec.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { expect, test } from '@playwright/test' -import { isSpaMode } from './utils/isSpaMode' - -test('authentication docs pattern handles login, logout, route context, and server authorization', async ({ - page, -}) => { - await page.goto('/auth-docs/private') - await expect(page).toHaveURL(/\/auth-docs$/) - await expect(page.getByTestId('auth-docs-user')).toHaveText('Signed out') - - await page - .getByRole('button', { name: 'Request private data directly' }) - .click() - await expect(page.getByTestId('auth-docs-private-result')).toHaveText( - 'Access denied', - ) - - await page.getByLabel('Email', { exact: true }).fill('reader@example.com') - await page.getByLabel('Password', { exact: true }).fill('wrong-password') - await page.getByRole('button', { name: 'Login', exact: true }).click() - await expect(page.getByRole('alert')).toHaveText('Invalid credentials') - await expect(page.getByTestId('auth-docs-user')).toHaveText('Signed out') - - await page.getByLabel('Password', { exact: true }).fill('test-password') - await page.getByRole('button', { name: 'Login', exact: true }).click() - await expect(page).toHaveURL(/\/auth-docs\/private$/) - await expect(page.getByTestId('auth-docs-user')).toHaveText( - 'reader@example.com', - ) - await expect(page.getByTestId('auth-docs-private-page')).toHaveText( - 'Private account data', - ) - - const response = await page.reload() - expect(response?.status()).toBe(200) - if (isSpaMode) { - // The shared SPA shell must not contain authenticated account data. - expect(await response?.text()).not.toContain('reader@example.com') - expect(await response?.text()).not.toContain('Private account data') - } else { - expect(response?.headers()['cache-control']).toBe('private, no-store') - } - await expect(page.getByTestId('auth-docs-user')).toHaveText( - 'reader@example.com', - ) - await page.getByRole('button', { name: 'Logout', exact: true }).click() - await expect(page).toHaveURL(/\/auth-docs$/) - await expect(page.getByTestId('auth-docs-user')).toHaveText('Signed out') - await page - .getByRole('button', { name: 'Request private data directly' }) - .click() - await expect(page.getByTestId('auth-docs-private-result')).toHaveText( - 'Access denied', - ) - await page.goto('/auth-docs/private') - await expect(page).toHaveURL(/\/auth-docs$/) -}) - -test('the authentication form cannot submit credentials before hydration', async ({ - browser, - baseURL, -}) => { - const context = await browser.newContext({ - javaScriptEnabled: false, - baseURL, - }) - const page = await context.newPage() - try { - await page.goto('/auth-docs') - if (isSpaMode) { - // Without JavaScript, the SPA shell cannot render credential controls. - await expect(page.locator('form')).toHaveCount(0) - await expect(page.getByLabel('Email', { exact: true })).toHaveCount(0) - await expect(page.getByLabel('Password', { exact: true })).toHaveCount(0) - await expect( - page.getByRole('button', { name: 'Login', exact: true }), - ).toHaveCount(0) - } else { - await expect(page.locator('form')).toHaveAttribute('method', 'post') - await expect(page.getByLabel('Email', { exact: true })).toBeDisabled() - await expect(page.getByLabel('Password', { exact: true })).toBeDisabled() - await expect( - page.getByRole('button', { name: 'Login', exact: true }), - ).toBeDisabled() - } - } finally { - await context.close() - } -}) diff --git a/e2e/react-start/basic/tests/client-only.spec.ts b/e2e/react-start/basic/tests/client-only.spec.ts index 299744f636..a3b6f99442 100644 --- a/e2e/react-start/basic/tests/client-only.spec.ts +++ b/e2e/react-start/basic/tests/client-only.spec.ts @@ -1,6 +1,5 @@ import { expect } from '@playwright/test' import { test } from '@tanstack/router-e2e-utils' -import { isSpaMode } from './utils/isSpaMode' /** * These tests verify the compiler optimization. @@ -16,15 +15,7 @@ import { isSpaMode } from './utils/isSpaMode' test('ClientOnly renders fallback on server, then client content after hydration', async ({ page, - request, }) => { - const response = await request.get('/client-only') - expect(response.status()).toBe(200) - const html = await response.text() - expect(html).not.toContain('data-testid="window-size"') - if (!isSpaMode) { - expect(html).toContain('Loading window size...') - } // Navigate directly to the client-only route // If the compiler optimization isn't working, this would crash the server // because WindowSize.tsx accesses `window` at module scope diff --git a/e2e/react-start/basic/tests/client-output.spec.ts b/e2e/react-start/basic/tests/client-output.spec.ts deleted file mode 100644 index 951d6668bc..0000000000 --- a/e2e/react-start/basic/tests/client-output.spec.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' - -test.skip( - process.env.TSS_RSB_CLIENT_OUTPUT !== 'iife', - 'IIFE client output assertions only run in rsbuild/ssr/iife mode', -) - -test('SSR HTML emits IIFE client scripts and classic script preloads', async ({ - page, -}) => { - const response = await page.goto('/posts') - const html = await response!.text() - - expect(html).not.toContain('rel="modulepreload"') - expect(html).toMatch(/]+rel="preload"[^>]+as="script"/) - - const clientEntry = html.match( - /]+src="([^"]*\/assets\/js\/index[^"]*)"[^>]*>/, - ) - expect(clientEntry).toBeTruthy() - expect(clientEntry![0]).toContain('async') - expect(clientEntry![0]).not.toContain('type="module"') - - await expect( - page.getByRole('link', { name: 'sunt aut facere repe' }), - ).toBeVisible() - - await page.getByRole('link', { name: 'sunt aut facere repe' }).click() - - await expect(page.getByRole('heading')).toContainText('sunt aut facere') -}) diff --git a/e2e/react-start/basic/tests/environment-functions.spec.ts b/e2e/react-start/basic/tests/environment-functions.spec.ts deleted file mode 100644 index 410b1d999e..0000000000 --- a/e2e/react-start/basic/tests/environment-functions.spec.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { expect, test } from '@playwright/test' -import { isSpaMode } from './utils/isSpaMode' - -const guardError = - 'createServerOnlyFn() functions can only be called on the server!' - -test('a server-only loader works on the server but rejects client navigation', async ({ - page, - request, -}) => { - const direct = await request.get('/execution-local') - expect(direct.status()).toBe(200) - if (!isSpaMode) { - expect(await direct.text()).toContain('Read on the server') - } - await page.goto('/execution-rpc') - await expect(page.getByTestId('execution-result')).toHaveText( - 'Read on the server', - ) - await page - .getByRole('link', { name: 'Call the server-only helper directly' }) - .click() - await expect(page.getByRole('alert')).toHaveText(guardError) -}) - -test('a server function preserves the loader result on direct requests and navigation', async ({ - page, - request, -}) => { - const direct = await request.get('/execution-rpc') - expect(direct.status()).toBe(200) - if (!isSpaMode) { - expect(await direct.text()).toContain('Read on the server') - } - await page.goto('/') - await page - .getByRole('link', { name: 'Server function loader', exact: true }) - .click() - await expect(page.getByTestId('execution-result')).toHaveText( - 'Read on the server', - ) - await page.reload() - await expect(page.getByTestId('execution-result')).toHaveText( - 'Read on the server', - ) -}) diff --git a/e2e/react-start/basic/tests/error-component.spec.ts b/e2e/react-start/basic/tests/error-component.spec.ts deleted file mode 100644 index 3f2beb967c..0000000000 --- a/e2e/react-start/basic/tests/error-component.spec.ts +++ /dev/null @@ -1,25 +0,0 @@ -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 500', - 'primitive beforeLoad error', - ], -}) - -test('beforeLoad primitive throw renders error component on direct visit', async ({ - page, -}) => { - const response = await page.goto('/primitive-beforeload-error') - await page.waitForLoadState('networkidle') - - expect(response?.status()).toBe(isSpaMode ? 200 : 500) - await expect( - page.getByTestId('primitive-beforeload-error-component'), - ).toHaveText('primitive beforeLoad error') - await expect( - page.getByTestId('primitive-beforeload-route-component'), - ).not.toBeInViewport() -}) diff --git a/e2e/react-start/basic/tests/fixture-api.spec.ts b/e2e/react-start/basic/tests/fixture-api.spec.ts deleted file mode 100644 index 6c9b26dc4c..0000000000 --- a/e2e/react-start/basic/tests/fixture-api.spec.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { expect, test } from '@playwright/test' - -test('server API receives canned users without a fixture listener', async ({ - request, -}) => { - const response = await request.get('/api/users') - expect(response.ok()).toBe(true) - const users = await response.json() - expect(users).toHaveLength(10) - expect(users[0]).toMatchObject({ id: 1, name: 'Leanne Graham' }) -}) diff --git a/e2e/react-start/basic/tests/issue-6221-head.spec.ts b/e2e/react-start/basic/tests/issue-6221-head.spec.ts deleted file mode 100644 index 96274ce0f9..0000000000 --- a/e2e/react-start/basic/tests/issue-6221-head.spec.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' -import { isPreview } from './utils/isPreview' -import { isSpaMode } from './utils/isSpaMode' - -// Ported to React from the regression app in -// https://github.com/TanStack/router/pull/6222 -test.skip( - isSpaMode || isPreview, - 'head() coverage for an ssr:false route requires the SSR test mode', -) - -test('browser back uses fresh loaderData for both the body and head (#6221)', async ({ - page, -}) => { - await page.goto('/') - await page.evaluate(() => localStorage.setItem('issue-6221-auth', 'good')) - - await page.goto('/issue-6221/article/1') - - await expect(page.getByTestId('issue-6221-article')).toHaveText( - 'Article content for 1', - ) - await expect(page).toHaveTitle('Article Title for 1') - - await page.evaluate(() => localStorage.removeItem('issue-6221-auth')) - await page.reload() - await expect(page.getByText('Article Not Accessible.')).toBeVisible() - await expect(page).toHaveTitle('title n/a') - - await page.evaluate(() => localStorage.setItem('issue-6221-auth', 'good')) - await page.getByTestId('issue-6221-dashboard-link').click() - await expect(page.getByTestId('issue-6221-dashboard')).toBeVisible() - await expect(page).toHaveTitle('Dashboard') - - await page.goBack() - await expect(page.getByTestId('issue-6221-article')).toHaveText( - 'Article content for 1', - ) - await expect(page).toHaveTitle('Article Title for 1') -}) diff --git a/e2e/react-start/basic/tests/navigation.spec.ts b/e2e/react-start/basic/tests/navigation.spec.ts index ce69a9d92a..36ed021c44 100644 --- a/e2e/react-start/basic/tests/navigation.spec.ts +++ b/e2e/react-start/basic/tests/navigation.spec.ts @@ -17,15 +17,6 @@ test('Navigating to post', async ({ page }) => { await expect(page.getByRole('heading')).toContainText('sunt aut facere') }) -test('plain .ts modules with angle-bracket type assertions build and render', async ({ - page, -}) => { - await page.goto('/plain-ts-type-assertion') - await expect(page.getByTestId('plain-ts-parser-regression')).toContainText( - 'plain .ts cast parsed', - ) -}) - test('Navigating to user', async ({ page }) => { await page.goto('/') await page.waitForURL('/') @@ -39,19 +30,15 @@ test('Navigating nested layouts', async ({ page }) => { await page.waitForURL('/') await page.getByRole('link', { name: 'Layout', exact: true }).click() - await page.waitForURL('/layout-a') await expect(page.locator('body')).toContainText("I'm a layout") await expect(page.locator('body')).toContainText("I'm a nested layout") + + await page.getByRole('link', { name: 'Layout A' }).click() await expect(page.locator('body')).toContainText("I'm layout A!") await page.getByRole('link', { name: 'Layout B' }).click() - await page.waitForURL('/layout-b') await expect(page.locator('body')).toContainText("I'm layout B!") - - await page.getByRole('link', { name: 'Layout A' }).click() - await page.waitForURL('/layout-a') - await expect(page.locator('body')).toContainText("I'm layout A!") }) test('client side navigating to a route with scripts', async ({ page }) => { @@ -59,7 +46,7 @@ test('client side navigating to a route with scripts', async ({ page }) => { await page.waitForURL('/') await page.getByRole('link', { name: 'Scripts', exact: true }).click() await expect(page.getByTestId('scripts-test-heading')).toBeInViewport() - await page.waitForFunction(() => (window as any).SCRIPT_1 === true) + expect(await page.evaluate('window.SCRIPT_1')).toBe(true) expect(await page.evaluate('window.SCRIPT_2')).toBe(undefined) }) @@ -67,7 +54,7 @@ test('directly going to a route with scripts', async ({ page }) => { await page.goto('/scripts') await page.waitForURL('/scripts') await page.waitForLoadState('networkidle') - await page.waitForFunction(() => (window as any).SCRIPT_1 === true) + expect(await page.evaluate('window.SCRIPT_1')).toBe(true) expect(await page.evaluate('window.SCRIPT_2')).toBe(undefined) }) diff --git a/e2e/react-start/basic/tests/not-found.spec.ts b/e2e/react-start/basic/tests/not-found.spec.ts index 339f841b21..89f6b6d4e9 100644 --- a/e2e/react-start/basic/tests/not-found.spec.ts +++ b/e2e/react-start/basic/tests/not-found.spec.ts @@ -1,7 +1,7 @@ import { expect } from '@playwright/test' import combinateImport from 'combinate' import { test } from '@tanstack/router-e2e-utils' -import { isSpaMode } from './utils/isSpaMode' +import { isSpaMode } from '../tests/utils/isSpaMode' // somehow playwright does not correctly import default exports const combinate = (combinateImport as any).default as typeof combinateImport @@ -12,24 +12,6 @@ test.use({ ], }) test.describe('not-found', () => { - test('direct nested not-found hydrates its already-rendered parent route', async ({ - page, - }) => { - test.skip(isSpaMode, 'issue #5106 requires a server-rendered direct visit') - - const response = await page.goto('/posts/i-do-not-exist') - await page.waitForLoadState('networkidle') - - const serverHtml = await response?.text() - expect(serverHtml).toContain('posts-parent-hydration-counter') - expect(serverHtml).toContain('Post not found') - await expect(page.getByText('Post not found')).toBeInViewport() - const counter = page.getByTestId('posts-parent-hydration-counter') - await expect(counter).toHaveText('Parent hydration count: 0') - await counter.click() - await expect(counter).toHaveText('Parent hydration count: 1') - }) - test(`global not found`, async ({ page }) => { const response = await page.goto(`/this-page-does-not-exist/foo/bar`) diff --git a/e2e/react-start/basic/tests/open-redirect-prevention.spec.ts b/e2e/react-start/basic/tests/open-redirect-prevention.spec.ts index bc88c33605..e497109889 100644 --- a/e2e/react-start/basic/tests/open-redirect-prevention.spec.ts +++ b/e2e/react-start/basic/tests/open-redirect-prevention.spec.ts @@ -77,14 +77,22 @@ test.describe('Open redirect prevention', () => { page, baseURL, }) => { - // %0d is kept encoded, so /%0d/test-path/ stays as-is and won't become //test-path/ - await page.goto('/%0d/test-path/') + // When control characters are stripped from paths like /%0d/evil.com/ + // the result could be //evil.com/ which is a protocol-relative URL + // Our fix collapses these to /evil.com/ to prevent external redirects + // This is already tested above, but we verify the collapsed path works + const res = await page.goto('/%0d/test-path/') await page.waitForLoadState('networkidle') // Should stay on the same origin expect(page.url().startsWith(baseURL!)).toBe(true) const url = new URL(page.url()) expect(url.origin).toBe(new URL(baseURL!).origin) + // Path should be collapsed to /test-path (not //test-path/) + expect(url.pathname).toMatch(/^\/test-path\/?$/) + if (!isSpaMode) { + expect(res?.request().redirectedFrom()?.url()).not.toBe(undefined) + } }) }) diff --git a/e2e/react-start/basic/tests/prerendering.spec.ts b/e2e/react-start/basic/tests/prerendering.spec.ts index ddcf720a4c..8506ff9b06 100644 --- a/e2e/react-start/basic/tests/prerendering.spec.ts +++ b/e2e/react-start/basic/tests/prerendering.spec.ts @@ -4,17 +4,13 @@ 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) @@ -38,6 +34,7 @@ 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/react-start/basic/tests/raw-stream.spec.ts b/e2e/react-start/basic/tests/raw-stream.spec.ts index 3bc6ea88b8..5b0c6a0fff 100644 --- a/e2e/react-start/basic/tests/raw-stream.spec.ts +++ b/e2e/react-start/basic/tests/raw-stream.spec.ts @@ -642,73 +642,3 @@ test.describe('RawStream - Edge Cases (RPC)', () => { expect(result).toContain('Error stream test') }) }) - -test.describe('RawStream - Late RawStream Tests (RPC)', () => { - test('Single late RawStream - Promise resolves correctly', async ({ - page, - }) => { - await page.goto('/raw-stream/client-call') - await page.waitForURL('/raw-stream/client-call') - - await page.getByTestId('test17-btn').waitFor({ state: 'visible' }) - await page.waitForTimeout(HYDRATION_WAIT) - - await page.getByTestId('test17-btn').click() - - await expect(page.getByTestId('test17-result')).toContainText( - '"match":true', - { timeout: 15000 }, - ) - await expect(page.getByTestId('test17-result')).toContainText( - 'Late stream test', - ) - }) - - test('Multiple late RawStreams - different Promise delays', async ({ - page, - }) => { - await page.goto('/raw-stream/client-call') - await page.waitForURL('/raw-stream/client-call') - - await page.getByTestId('test18-btn').waitFor({ state: 'visible' }) - await page.waitForTimeout(HYDRATION_WAIT) - - await page.getByTestId('test18-btn').click() - - // Both streams should match - await expect(page.getByTestId('test18-result')).toContainText( - '"match":true', - { timeout: 15000 }, - ) - // Verify both streams match by checking result - const result = await page.getByTestId('test18-result').textContent() - const parsed = JSON.parse(result || '{}') - expect(parsed.streamA?.match).toBe(true) - expect(parsed.streamB?.match).toBe(true) - expect(parsed.message).toBe('Multiple late streams test') - }) - - test('Mixed immediate and late RawStreams - both work correctly', async ({ - page, - }) => { - await page.goto('/raw-stream/client-call') - await page.waitForURL('/raw-stream/client-call') - - await page.getByTestId('test19-btn').waitFor({ state: 'visible' }) - await page.waitForTimeout(HYDRATION_WAIT) - - await page.getByTestId('test19-btn').click() - - // Both immediate and late streams should match - await expect(page.getByTestId('test19-result')).toContainText( - '"match":true', - { timeout: 15000 }, - ) - // Verify both streams match by checking result - const result = await page.getByTestId('test19-result').textContent() - const parsed = JSON.parse(result || '{}') - expect(parsed.immediate?.match).toBe(true) - expect(parsed.late?.match).toBe(true) - expect(parsed.message).toBe('Mixed immediate and late test') - }) -}) diff --git a/e2e/react-start/basic/tests/redirect.spec.ts b/e2e/react-start/basic/tests/redirect.spec.ts index 010ecec155..bc36de9623 100644 --- a/e2e/react-start/basic/tests/redirect.spec.ts +++ b/e2e/react-start/basic/tests/redirect.spec.ts @@ -1,28 +1,23 @@ import queryString from 'node:querystring' import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' import combinateImport from 'combinate' -import type { Page } from '@playwright/test' +import { + getDummyServerPort, + getTestServerPort, + test, +} from '@tanstack/router-e2e-utils' +import { isSpaMode } from '../tests/utils/isSpaMode' +import { isPreview } from '../tests/utils/isPreview' +import packageJson from '../package.json' with { type: 'json' } // somehow playwright does not correctly import default exports const combinate = (combinateImport as any).default as typeof combinateImport -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort( + `${packageJson.name}${isSpaMode ? '_spa' : ''}${isPreview ? '_preview' : ''}`, +) -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() -} +const EXTERNAL_HOST_PORT = await getDummyServerPort(packageJson.name) test.describe('redirects', () => { test.describe('internal', () => { @@ -45,7 +40,7 @@ test.describe('redirects', () => { `via-${thrower}${reloadDocument ? '-reloadDocument' : ''}`, ) - await waitForRouterIdle(page) + await page.waitForLoadState('networkidle') let requestHappened = false const requestPromise = new Promise((resolve) => { @@ -73,7 +68,10 @@ test.describe('redirects', () => { await link.click() - await waitForPostsIndex(page) + const url = `http://localhost:${PORT}/posts` + await page.waitForURL(url) + expect(page.url()).toBe(url) + await expect(page.getByTestId('PostsIndexComponent')).toBeInViewport() expect(fullPageLoad).toBe(reloadDocument) }) }, @@ -89,8 +87,12 @@ test.describe('redirects', () => { page, }) => { await page.goto(`/redirect/internal/via-${thrower}`) + await page.waitForLoadState('networkidle') - await waitForPostsIndex(page) + const url = `http://localhost:${PORT}/posts` + + expect(page.url()).toBe(url) + await expect(page.getByTestId('PostsIndexComponent')).toBeInViewport() }) }) }) @@ -106,12 +108,12 @@ test.describe('redirects', () => { page, }) => { const q = queryString.stringify({ - externalHost: `${EXTERNAL_ORIGIN}/`, + externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, }) if (scenario === 'navigate') { await page.goto(`/redirect/external?${q}`) - await waitForRouterIdle(page) + await page.waitForLoadState('networkidle') const link = page.getByTestId(`via-${thrower}`) await link.focus() await link.click() @@ -119,7 +121,7 @@ test.describe('redirects', () => { await page.goto(`/redirect/external/via-${thrower}?${q}`) } - const url = `${EXTERNAL_ORIGIN}/` + const url = `http://localhost:${EXTERNAL_HOST_PORT}/` await page.waitForURL(url) expect(page.url()).toBe(url) @@ -142,13 +144,13 @@ test.describe('redirects', () => { }) => { let fullPageLoad = false const q = queryString.stringify({ - externalHost: `${EXTERNAL_ORIGIN}/`, + externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, reloadDocument, }) if (scenario === 'navigate') { await page.goto(`/redirect/${target}/serverFn?${q}`) - await waitForRouterIdle(page) + await page.waitForLoadState('networkidle') const link = page.getByTestId( `via-${thrower}${reloadDocument ? '-reloadDocument' : ''}`, @@ -159,20 +161,22 @@ test.describe('redirects', () => { }) await link.focus() - await waitForRouterIdle(page) + await page.waitForLoadState('networkidle') await link.click() } else { await page.goto(`/redirect/${target}/serverFn/via-${thrower}?${q}`) } - const url = target === 'internal' ? POSTS_URL : `${EXTERNAL_ORIGIN}/` + const url = + target === 'internal' + ? `http://localhost:${PORT}/posts` + : `http://localhost:${EXTERNAL_HOST_PORT}/` await page.waitForURL(url) expect(page.url()).toBe(url) if (target === 'internal' && scenario === 'navigate') { - await waitForRouterIdle(page) await expect( page.getByTestId('PostsIndexComponent'), ).toBeInViewport() @@ -194,13 +198,13 @@ test.describe('redirects', () => { page, }) => { const q = queryString.stringify({ - externalHost: `${EXTERNAL_ORIGIN}/`, + externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, reloadDocument, }) await page.goto(`/redirect/${target}/serverFn/via-useServerFn?${q}`) - await waitForRouterIdle(page) + await page.waitForLoadState('networkidle') const button = page.getByTestId('redirect-on-click') @@ -211,11 +215,13 @@ test.describe('redirects', () => { await button.click() - const url = target === 'internal' ? POSTS_URL : `${EXTERNAL_ORIGIN}/` + const url = + target === 'internal' + ? `http://localhost:${PORT}/posts` + : `http://localhost:${EXTERNAL_HOST_PORT}/` 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/react-start/basic/tests/search-params.spec.ts b/e2e/react-start/basic/tests/search-params.spec.ts index cdf5a21b4a..74c1aa54dc 100644 --- a/e2e/react-start/basic/tests/search-params.spec.ts +++ b/e2e/react-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 './utils/isSpaMode' +import { isSpaMode } from 'tests/utils/isSpaMode' import { isPrerender } from './utils/isPrerender' import type { Response } from '@playwright/test' diff --git a/e2e/react-start/basic/tests/setup/dev-server.setup.ts b/e2e/react-start/basic/tests/setup/dev-server.setup.ts deleted file mode 100644 index d16ff0bb54..0000000000 --- a/e2e/react-start/basic/tests/setup/dev-server.setup.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { preOptimizeDevServer, waitForServer } from '@tanstack/router-e2e-utils' - -export default async function setup() { - const port = Number(process.env.E2E_APP_PORT ?? 0) - const baseURL = `http://localhost:${port}` - - await waitForServer(baseURL) - await preOptimizeDevServer({ - baseURL, - warmup: async (page) => { - await page.getByRole('heading').getByText('Welcome Home').waitFor() - await page.goto(`${baseURL}/specialChars/search?searchParam=warmup`) - await page.getByTestId('special-search-loaded-info').waitFor() - await page.goto(`${baseURL}/posts`) - await page.getByRole('link', { name: 'sunt aut facere repe' }).waitFor() - await page.waitForLoadState('networkidle') - }, - }) -} diff --git a/e2e/react-start/basic/tests/setup/global.setup.ts b/e2e/react-start/basic/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-start/basic/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/react-start/basic/tests/setup/global.teardown.ts b/e2e/react-start/basic/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-start/basic/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-start/basic/tests/spa-shell.spec.ts b/e2e/react-start/basic/tests/spa-shell.spec.ts deleted file mode 100644 index f42195e762..0000000000 --- a/e2e/react-start/basic/tests/spa-shell.spec.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' -import { isSpaMode } from './utils/isSpaMode' - -// The prod SPA run and the dev SPA runs (`E2E_DEV_SERVER`) all run this file. -// The dev runs run nothing else. -test.skip(!isSpaMode, 'only SPA mode answers documents with the shell') - -// Its loader and beforeLoad report where they ran. -const searchRoute = '/specialChars/search?searchParam=shell' - -test('a document request gets the shell, not the rendered route', async ({ - request, -}) => { - const response = await request.get(searchRoute) - - expect(response.status()).toBe(200) - const html = await response.text() - // The root route's document renders... - expect(html).toContain('This Route Does Not Exist') - // ...but not the matched route, nor its loader's output. - expect(html).not.toContain('special-search-loaded-info') - expect(html).not.toContain('Loaded on: server') -}) - -test('the route loads in the browser', async ({ page }) => { - await page.goto(searchRoute) - - await expect(page.getByTestId('special-search-loaded-info')).toHaveText( - 'Loaded on: client', - ) - await expect(page.getByTestId('special-search-before-load-info')).toHaveText( - 'Before load on: client', - ) - await expect(page.getByTestId('special-search-param')).toHaveText('shell') -}) - -test('client navigation works from the shell', async ({ page }) => { - await page.goto('/') - await expect(page.getByRole('heading')).toContainText('Welcome Home') - await expect(page.getByTestId('router-status')).toHaveText('idle') - - // A full page load would drop this. - await page.evaluate(() => { - ;(window as any).__spaShellPage = true - }) - await page.getByRole('link', { name: 'Posts' }).click() - await page.waitForURL('/posts') - await expect( - page.getByRole('link', { name: 'sunt aut facere repe' }), - ).toBeVisible() - expect(await page.evaluate(() => (window as any).__spaShellPage)).toBe(true) -}) diff --git a/e2e/react-start/basic/tests/special-characters.spec.ts b/e2e/react-start/basic/tests/special-characters.spec.ts index 188d1f10a6..ce800a77ef 100644 --- a/e2e/react-start/basic/tests/special-characters.spec.ts +++ b/e2e/react-start/basic/tests/special-characters.spec.ts @@ -64,22 +64,6 @@ test.describe('Unicode route rendering', () => { expect(param).toBe('대|') }) - - test('should not cause redirect loop for curly braces in path params', async ({ - page, - baseURL, - }) => { - // %7B/%7D (curly braces) must not trigger infinite 307 redirects - const res = await page.goto('/specialChars/%7B%7Bapp_name%7D%7D') - await page.waitForLoadState('load') - - // Should not redirect — URL stays encoded - expect(page.url()).toBe(`${baseURL}/specialChars/%7B%7Bapp_name%7D%7D`) - expect(res!.status()).toBe(200) - - const param = await page.getByTestId('special-param').textContent() - expect(param).toBe('{{app_name}}') - }) }) test.describe('Special characters in search params', () => { @@ -93,28 +77,11 @@ test.describe('Unicode route rendering', () => { `${baseURL}/specialChars/search?searchParam=%EB%8C%80|`, ) - await page.waitForLoadState('networkidle') - const searchParam = await page .getByTestId('special-search-param') .textContent() expect(searchParam).toBe('대|') - - const loadedOn = await page - .getByTestId('special-search-loaded-info') - .textContent() - const beforeLoadOn = await page - .getByTestId('special-search-before-load-info') - .textContent() - - if (isSpaMode) { - expect(loadedOn).toBe('Loaded on: client') - expect(beforeLoadOn).toBe('Before load on: client') - } else { - expect(loadedOn).toBe('Loaded on: server') - expect(beforeLoadOn).toBe('Before load on: server') - } }) test('should render route correctly on router navigation', async ({ @@ -208,12 +175,6 @@ test.describe('Unicode route rendering', () => { }) 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', @@ -221,22 +182,24 @@ test.describe('Unicode route rendering', () => { ], }) - 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) + test('un-matched malformed paths should return not found on direct navigation', async ({ + page, + }) => { + const res = await page.goto('/specialChars/malformed/%E0%A4') - await page.waitForLoadState(`load`) + 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) - } - }) - } + // in spa mode this is caught and handled at server level + if (!isSpaMode) { + expect(res!.status()).toBe(404) + + await expect( + page.getByTestId('default-not-found-component'), + ).toBeInViewport() + } else { + expect(res!.status()).toBe(400) + } + }) test('malformed path params should return not found on router link', async ({ page, diff --git a/e2e/react-start/basic/tests/utils/getPackageName.ts b/e2e/react-start/basic/tests/utils/getPackageName.ts deleted file mode 100644 index 6bd2e0499e..0000000000 --- a/e2e/react-start/basic/tests/utils/getPackageName.ts +++ /dev/null @@ -1,16 +0,0 @@ -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/react-start/basic/tsconfig.json b/e2e/react-start/basic/tsconfig.json index e486543b96..b3a2d67dfa 100644 --- a/e2e/react-start/basic/tsconfig.json +++ b/e2e/react-start/basic/tsconfig.json @@ -8,13 +8,12 @@ "moduleResolution": "Bundler", "lib": ["DOM", "DOM.Iterable", "ES2022"], "isolatedModules": true, - "allowImportingTsExtensions": true, "resolveJsonModule": true, "skipLibCheck": true, "target": "ES2022", - "types": ["node"], "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/react-start/basic/vite.config.ts b/e2e/react-start/basic/vite.config.ts index 2a9478eea6..8ac18ef504 100644 --- a/e2e/react-start/basic/vite.config.ts +++ b/e2e/react-start/basic/vite.config.ts @@ -2,18 +2,43 @@ import { defineConfig } from 'vite' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import viteReact from '@vitejs/plugin-react' import tailwindcss from '@tailwindcss/vite' -import { getStartModeConfig } from './start-mode-config' +import { isSpaMode } from './tests/utils/isSpaMode' +import { isPrerender } from './tests/utils/isPrerender' -const outDir = process.env.E2E_DIST_DIR ?? 'dist' -const startModeConfig = getStartModeConfig() +const spaModeConfiguration = { + enabled: true, + prerender: { + outputPath: 'index.html', + }, +} + +const prerenderConfiguration = { + enabled: true, + filter: (page: { path: string }) => + ![ + '/this-route-does-not-exist', + '/redirect', + '/i-do-not-exist', + '/not-found', + '/specialChars/search', + '/specialChars/hash', + '/specialChars/malformed', + '/users', + ].some((p) => page.path.includes(p)), + maxRedirects: 100, +} export default defineConfig({ resolve: { tsconfigPaths: true }, - build: { - outDir, - }, server: { port: 3000, }, - plugins: [tailwindcss(), tanstackStart(startModeConfig), viteReact()], + plugins: [ + tailwindcss(), + tanstackStart({ + spa: isSpaMode ? spaModeConfiguration : undefined, + prerender: isPrerender ? prerenderConfiguration : undefined, + }), + viteReact(), + ], }) diff --git a/e2e/react-start/clerk-basic/package.json b/e2e/react-start/clerk-basic/package.json index 7838b4cee1..6b127cf195 100644 --- a/e2e/react-start/clerk-basic/package.json +++ b/e2e/react-start/clerk-basic/package.json @@ -8,7 +8,7 @@ "dev:e2e": "vite dev", "build": "exit 0; vite build", "start": "node .output/server/index.mjs", - "test:e2e": "exit 0; playwright test --project=chromium" + "test:e2e": "exit 0; rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@clerk/tanstack-react-start": "^0.19.0", @@ -17,20 +17,19 @@ "@tanstack/react-start": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "catalog:", - "tailwind-merge": "^3.6.0" + "redaxios": "^0.5.1", + "tailwind-merge": "^2.6.0", + "vite": "^8.0.0" }, "devDependencies": { - "@playwright/test": "^1.61.0", - "@tailwindcss/vite": "^4.2.2", + "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "typescript": "^5.7.2", + "@tailwindcss/vite": "^4.2.2" } } diff --git a/e2e/react-start/clerk-basic/playwright.config.ts b/e2e/react-start/clerk-basic/playwright.config.ts index 82678ac00b..18b8905468 100644 --- a/e2e/react-start/clerk-basic/playwright.config.ts +++ b/e2e/react-start/clerk-basic/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/clerk-basic/src/components/DefaultCatchBoundary.tsx b/e2e/react-start/clerk-basic/src/components/DefaultCatchBoundary.tsx index 405fb5f4a7..ef2daa1ea1 100644 --- a/e2e/react-start/clerk-basic/src/components/DefaultCatchBoundary.tsx +++ b/e2e/react-start/clerk-basic/src/components/DefaultCatchBoundary.tsx @@ -1,15 +1,17 @@ import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, 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 === '/', + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, }) console.error(error) diff --git a/e2e/react-start/clerk-basic/src/routeTree.gen.ts b/e2e/react-start/clerk-basic/src/routeTree.gen.ts index d8111b637a..a6767e0efd 100644 --- a/e2e/react-start/clerk-basic/src/routeTree.gen.ts +++ b/e2e/react-start/clerk-basic/src/routeTree.gen.ts @@ -9,22 +9,22 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' import { Route as AuthedRouteImport } from './routes/_authed' +import { Route as IndexRouteImport } from './routes/index' 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' import { Route as AuthedProfileSplatRouteImport } from './routes/_authed/profile.$' +import { Route as AuthedPostsPostIdRouteImport } from './routes/_authed/posts.$postId' +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 AuthedPostsPostIdRoute = AuthedPostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - 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) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -90,6 +90,13 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { + '/_authed': { + id: '/_authed' + path: '' + fullPath: '' + preLoaderRoute: typeof AuthedRouteImport + parentRoute: typeof rootRouteImport + } '/': { id: '/' path: '/' @@ -97,13 +104,6 @@ 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/posts/$postId': { - id: '/_authed/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof AuthedPostsPostIdRouteImport - parentRoute: typeof AuthedPostsRoute - } '/_authed/profile/$': { id: '/_authed/profile/$' path: '/profile/$' @@ -132,6 +125,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthedProfileSplatRouteImport parentRoute: typeof AuthedRoute } + '/_authed/posts/$postId': { + id: '/_authed/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof AuthedPostsPostIdRouteImport + parentRoute: typeof AuthedPostsRoute + } } } diff --git a/e2e/react-start/clerk-basic/src/routes/_authed.tsx b/e2e/react-start/clerk-basic/src/routes/_authed.tsx index 440d0e3f3c..226ae0829f 100644 --- a/e2e/react-start/clerk-basic/src/routes/_authed.tsx +++ b/e2e/react-start/clerk-basic/src/routes/_authed.tsx @@ -8,7 +8,7 @@ export const Route = createFileRoute('/_authed')({ } }, errorComponent: ({ error }) => { - if (error instanceof Error && error.message === 'Not authenticated') { + if (error.message === 'Not authenticated') { return (
diff --git a/e2e/react-start/clerk-basic/src/utils/posts.ts b/e2e/react-start/clerk-basic/src/utils/posts.ts index 532e883ac0..b30810a5a3 100644 --- a/e2e/react-start/clerk-basic/src/utils/posts.ts +++ b/e2e/react-start/clerk-basic/src/utils/posts.ts @@ -9,7 +9,7 @@ export type PostType = { } export const fetchPost = createServerFn({ method: 'GET' }) - .validator((postId: string) => postId) + .inputValidator((postId: string) => postId) .handler(async ({ data: postId }) => { console.info(`Fetching post with id ${postId}...`) const post = await axios diff --git a/e2e/react-start/clerk-basic/tsconfig.json b/e2e/react-start/clerk-basic/tsconfig.json index cef9369516..3a9fb7cd71 100644 --- a/e2e/react-start/clerk-basic/tsconfig.json +++ b/e2e/react-start/clerk-basic/tsconfig.json @@ -13,6 +13,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/react-start/csp/package.json b/e2e/react-start/csp/package.json index fd8987bcef..e96dbeb836 100644 --- a/e2e/react-start/csp/package.json +++ b/e2e/react-start/csp/package.json @@ -8,23 +8,22 @@ "dev:e2e": "vite dev", "build": "vite build && tsc --noEmit", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", "@tanstack/react-start": "workspace:^", "react": "^19.0.0", - "react-dom": "^19.0.0" + "react-dom": "^19.0.0", + "vite": "^8.0.0" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "srvx": "^1.0.0", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "srvx": "^0.11.9", + "typescript": "^5.7.2" } } diff --git a/e2e/react-start/csp/playwright.config.ts b/e2e/react-start/csp/playwright.config.ts index 87b32e1f50..5f9de5709e 100644 --- a/e2e/react-start/csp/playwright.config.ts +++ b/e2e/react-start/csp/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -20,8 +21,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/csp/src/vite-env.d.ts b/e2e/react-start/csp/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/react-start/csp/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/react-start/csp/tests/csp.spec.ts b/e2e/react-start/csp/tests/csp.spec.ts index ef6b2dadc6..5bdfd93e9b 100644 --- a/e2e/react-start/csp/tests/csp.spec.ts +++ b/e2e/react-start/csp/tests/csp.spec.ts @@ -1,21 +1,6 @@ -import { expect, type Page } from '@playwright/test' +import { expect } from '@playwright/test' import { test } from '@tanstack/router-e2e-utils' -async function getRawHtml(page: Page) { - let rawHtml = '' - - await page.route('/', async (route) => { - const response = await route.fetch() - rawHtml = await response.text() - await route.fulfill({ response, body: rawHtml }) - }) - - const response = await page.goto('/') - await page.unrouteAll({ behavior: 'ignoreErrors' }) - - return { rawHtml, response } -} - test('CSP header is set with nonce', async ({ page }) => { const response = await page.goto('/') const csp = response?.headers()['content-security-policy'] @@ -36,10 +21,9 @@ test('Inline styles have nonce attribute', async ({ page }) => { }) test('External script has nonce attribute', async ({ page }) => { - const { rawHtml } = await getRawHtml(page) - expect(rawHtml).toMatch( - /]*\bsrc="\/external\.js")(?=[^>]*\bnonce="[^"]+")[^>]*>/, - ) + await page.goto('/') + const externalScript = page.locator('script[src="/external.js"]') + await expect(externalScript).toHaveAttribute('nonce') }) test('External stylesheet has nonce attribute', async ({ page }) => { @@ -50,7 +34,15 @@ test('External stylesheet has nonce attribute', async ({ page }) => { test('Nonces match between header and elements', async ({ page }) => { // Intercept the HTML response to get raw content before browser strips nonces - const { rawHtml, response } = await getRawHtml(page) + let rawHtml = '' + await page.route('/', async (route) => { + const response = await route.fetch() + rawHtml = await response.text() + await route.fulfill({ response }) + }) + + const response = await page.goto('/') + await page.unrouteAll({ behavior: 'ignoreErrors' }) const csp = response?.headers()['content-security-policy'] || '' diff --git a/e2e/react-start/csp/tsconfig.json b/e2e/react-start/csp/tsconfig.json index cef9369516..3a9fb7cd71 100644 --- a/e2e/react-start/csp/tsconfig.json +++ b/e2e/react-start/csp/tsconfig.json @@ -13,6 +13,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/react-start/css-inline/package.json b/e2e/react-start/css-inline/package.json deleted file mode 100644 index 6c5dd031c6..0000000000 --- a/e2e/react-start/css-inline/package.json +++ /dev/null @@ -1,113 +0,0 @@ -{ - "name": "tanstack-react-start-e2e-css-inline", - "private": true, - "sideEffects": false, - "type": "module", - "scripts": { - "build": "pnpm build:vite && pnpm build:rsbuild", - "build:vite": "vite build && tsc --noEmit", - "build:rsbuild": "rsbuild build && tsc --noEmit", - "start": "node server.js", - "test:e2e:vite": "E2E_TOOLCHAIN=vite playwright test --project=chromium", - "test:e2e:vite:transform-assets": "E2E_TOOLCHAIN=vite CSS_INLINE_TRANSFORM_ASSETS=true playwright test --project=chromium", - "test:e2e:rsbuild": "E2E_TOOLCHAIN=rsbuild playwright test --project=chromium", - "test:e2e:rsbuild:transform-assets": "E2E_TOOLCHAIN=rsbuild CSS_INLINE_TRANSFORM_ASSETS=true playwright test --project=chromium", - "test:e2e": "pnpm run test:e2e:vite && pnpm run test:e2e:vite:transform-assets && pnpm run test:e2e:rsbuild && pnpm run test:e2e:rsbuild:transform-assets" - }, - "dependencies": { - "@tanstack/react-router": "workspace:^", - "@tanstack/react-start": "workspace:^", - "express": "^5.2.1", - "react": "^19.0.0", - "react-dom": "^19.0.0", - "srvx": "^1.0.0" - }, - "devDependencies": { - "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", - "@rsbuild/plugin-react": "^2.0.0", - "@tanstack/router-e2e-utils": "workspace:^", - "@types/node": "^22.10.2", - "@types/react": "^19.0.8", - "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" - }, - "nx": { - "targets": { - "test:e2e": { - "parallelism": false, - "outputs": [ - "...", - "{projectRoot}/dist-vite-ssr", - "{projectRoot}/dist-vite-ssr-transform-assets", - "{projectRoot}/dist-vite-transform-assets-ssr", - "{projectRoot}/dist-rsbuild-ssr", - "{projectRoot}/dist-rsbuild-ssr-transform-assets", - "{projectRoot}/dist-rsbuild-transform-assets-ssr" - ] - }, - "build": { - "outputs": [ - "...", - "{projectRoot}/dist-vite-ssr", - "{projectRoot}/dist-rsbuild-ssr" - ] - }, - "test:e2e--vite-ssr": { - "outputs": [ - "...", - "{projectRoot}/dist-vite-ssr" - ] - }, - "test:e2e--vite-ssr--transform-assets": { - "outputs": [ - "...", - "{projectRoot}/dist-vite-ssr-transform-assets" - ] - }, - "test:e2e--rsbuild-ssr": { - "outputs": [ - "...", - "{projectRoot}/dist-rsbuild-ssr" - ] - }, - "test:e2e--rsbuild-ssr--transform-assets": { - "outputs": [ - "...", - "{projectRoot}/dist-rsbuild-ssr-transform-assets" - ] - } - }, - "metadata": { - "playwrightModes": [ - { - "toolchain": "vite", - "mode": "ssr" - }, - { - "toolchain": "vite", - "mode": "ssr", - "name": "transform-assets", - "env": { - "CSS_INLINE_TRANSFORM_ASSETS": "true" - } - }, - { - "toolchain": "rsbuild", - "mode": "ssr" - }, - { - "toolchain": "rsbuild", - "mode": "ssr", - "name": "transform-assets", - "env": { - "CSS_INLINE_TRANSFORM_ASSETS": "true" - } - } - ] - } - } -} diff --git a/e2e/react-start/css-inline/playwright.config.ts b/e2e/react-start/css-inline/playwright.config.ts deleted file mode 100644 index 78e7b75252..0000000000 --- a/e2e/react-start/css-inline/playwright.config.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' - -const toolchain = process.env.E2E_TOOLCHAIN ?? 'vite' -const inlineCssTransformAssets = - process.env.CSS_INLINE_TRANSFORM_ASSETS || 'false' -if (!['true', 'false'].includes(inlineCssTransformAssets)) { - throw new Error( - `CSS_INLINE_TRANSFORM_ASSETS must be "true" or "false". Received: ${JSON.stringify(inlineCssTransformAssets)}`, - ) -} - -const isInlineCssTransformAssets = inlineCssTransformAssets === 'true' -const transformAssetsSuffix = isInlineCssTransformAssets - ? '-transform-assets' - : '' -const distDir = - process.env.E2E_DIST_DIR ?? `dist-${toolchain}${transformAssetsSuffix}-ssr` - -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:${toolchain} && pnpm start`, - wait: appServerReady, - reuseExistingServer: false, - stdout: 'pipe', - env: { - E2E_DIST_DIR: distDir, - PORT: String(PORT), - CSS_INLINE_TRANSFORM_ASSETS: inlineCssTransformAssets, - }, - }, - - projects: [ - { - name: 'chromium', - use: { ...devices['Desktop Chrome'] }, - }, - ], -}) diff --git a/e2e/react-start/css-inline/rsbuild.config.ts b/e2e/react-start/css-inline/rsbuild.config.ts deleted file mode 100644 index 8957fc9a06..0000000000 --- a/e2e/react-start/css-inline/rsbuild.config.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { defineConfig } from '@rsbuild/core' -import { pluginReact } from '@rsbuild/plugin-react' -import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild' - -const outDir = process.env.E2E_DIST_DIR ?? 'dist-rsbuild-ssr' -const transformInlineCssAssets = - process.env.CSS_INLINE_TRANSFORM_ASSETS === 'true' - -export default defineConfig({ - plugins: [ - pluginReact(), - tanstackStart({ - server: { - build: { - inlineCss: transformInlineCssAssets - ? { enabled: true, transformAssets: true } - : true, - }, - }, - }), - ], - output: { - distPath: { - root: outDir, - }, - }, -}) diff --git a/e2e/react-start/css-inline/server.js b/e2e/react-start/css-inline/server.js deleted file mode 100644 index 27b2357284..0000000000 --- a/e2e/react-start/css-inline/server.js +++ /dev/null @@ -1,46 +0,0 @@ -import fs from 'node:fs' -import path from 'node:path' -import express from 'express' -import { toNodeHandler } from 'srvx/node' - -const port = Number(process.env.PORT ?? 3000) -const distDir = process.env.E2E_DIST_DIR || 'dist-vite-ssr' -const distClientDir = path.resolve(distDir, 'client') - -function resolveDistServerEntryPath() { - const candidates = [ - path.resolve(distDir, 'server', 'server.js'), - path.resolve(distDir, 'server', 'index.js'), - path.resolve(distDir, 'server', 'index.mjs'), - ] - - return ( - candidates.find((candidate) => fs.existsSync(candidate)) ?? candidates[0] - ) -} - -async function createStartServer() { - const server = (await import(resolveDistServerEntryPath())).default - const nodeHandler = toNodeHandler(server.fetch) - const app = express() - - app.use(express.static(distClientDir, { redirect: false })) - app.use(async (req, res, next) => { - try { - await nodeHandler(req, res) - } catch (error) { - next(error) - } - }) - - return app -} - -createStartServer().then((app) => { - const httpServer = app.listen(port, (error) => { - if (error) { - throw error - } - console.info(`E2E app: http://localhost:${httpServer.address().port}`) - }) -}) diff --git a/e2e/react-start/css-inline/src/components/NestedPanel.tsx b/e2e/react-start/css-inline/src/components/NestedPanel.tsx deleted file mode 100644 index d564a47eea..0000000000 --- a/e2e/react-start/css-inline/src/components/NestedPanel.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import styles from '~/styles/nested-panel.module.css' - -export function NestedPanel({ label }: { label: string }) { - return ( -
- {label} -
- ) -} diff --git a/e2e/react-start/css-inline/src/components/Shell.tsx b/e2e/react-start/css-inline/src/components/Shell.tsx deleted file mode 100644 index 4fd9b00877..0000000000 --- a/e2e/react-start/css-inline/src/components/Shell.tsx +++ /dev/null @@ -1,26 +0,0 @@ -import { Link, Outlet } from '@tanstack/react-router' -import { useEffect } from 'react' -import styles from '~/styles/shell.module.css' - -export function Shell() { - useEffect(() => { - ;(window as any).__CSS_INLINE_E2E_HYDRATED__ = true - }, []) - - return ( -
- - -
- ) -} diff --git a/e2e/react-start/css-inline/src/routeTree.gen.ts b/e2e/react-start/css-inline/src/routeTree.gen.ts deleted file mode 100644 index 1b5e5886b1..0000000000 --- a/e2e/react-start/css-inline/src/routeTree.gen.ts +++ /dev/null @@ -1,169 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as AppRouteRouteImport } from './routes/app/route' -import { Route as AppDashboardRouteRouteImport } from './routes/app/dashboard/route' -import { Route as AppDashboardIndexRouteImport } from './routes/app/dashboard/index' -import { Route as AppDashboardDetailsRouteImport } from './routes/app/dashboard/details' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const AppRouteRoute = AppRouteRouteImport.update({ - id: '/app', - path: '/app', - getParentRoute: () => rootRouteImport, -} as any) -const AppDashboardRouteRoute = AppDashboardRouteRouteImport.update({ - id: '/dashboard', - path: '/dashboard', - getParentRoute: () => AppRouteRoute, -} as any) -const AppDashboardIndexRoute = AppDashboardIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => AppDashboardRouteRoute, -} as any) -const AppDashboardDetailsRoute = AppDashboardDetailsRouteImport.update({ - id: '/details', - path: '/details', - getParentRoute: () => AppDashboardRouteRoute, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/app': typeof AppRouteRouteWithChildren - '/app/dashboard': typeof AppDashboardRouteRouteWithChildren - '/app/dashboard/details': typeof AppDashboardDetailsRoute - '/app/dashboard/': typeof AppDashboardIndexRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/app': typeof AppRouteRouteWithChildren - '/app/dashboard/details': typeof AppDashboardDetailsRoute - '/app/dashboard': typeof AppDashboardIndexRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/app': typeof AppRouteRouteWithChildren - '/app/dashboard': typeof AppDashboardRouteRouteWithChildren - '/app/dashboard/details': typeof AppDashboardDetailsRoute - '/app/dashboard/': typeof AppDashboardIndexRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/app' - | '/app/dashboard' - | '/app/dashboard/details' - | '/app/dashboard/' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/app' | '/app/dashboard/details' | '/app/dashboard' - id: - | '__root__' - | '/' - | '/app' - | '/app/dashboard' - | '/app/dashboard/details' - | '/app/dashboard/' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - AppRouteRoute: typeof AppRouteRouteWithChildren -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/app': { - id: '/app' - path: '/app' - fullPath: '/app' - preLoaderRoute: typeof AppRouteRouteImport - parentRoute: typeof rootRouteImport - } - '/app/dashboard': { - id: '/app/dashboard' - path: '/dashboard' - fullPath: '/app/dashboard' - preLoaderRoute: typeof AppDashboardRouteRouteImport - parentRoute: typeof AppRouteRoute - } - '/app/dashboard/': { - id: '/app/dashboard/' - path: '/' - fullPath: '/app/dashboard/' - preLoaderRoute: typeof AppDashboardIndexRouteImport - parentRoute: typeof AppDashboardRouteRoute - } - '/app/dashboard/details': { - id: '/app/dashboard/details' - path: '/details' - fullPath: '/app/dashboard/details' - preLoaderRoute: typeof AppDashboardDetailsRouteImport - parentRoute: typeof AppDashboardRouteRoute - } - } -} - -interface AppDashboardRouteRouteChildren { - AppDashboardDetailsRoute: typeof AppDashboardDetailsRoute - AppDashboardIndexRoute: typeof AppDashboardIndexRoute -} - -const AppDashboardRouteRouteChildren: AppDashboardRouteRouteChildren = { - AppDashboardDetailsRoute: AppDashboardDetailsRoute, - AppDashboardIndexRoute: AppDashboardIndexRoute, -} - -const AppDashboardRouteRouteWithChildren = - AppDashboardRouteRoute._addFileChildren(AppDashboardRouteRouteChildren) - -interface AppRouteRouteChildren { - AppDashboardRouteRoute: typeof AppDashboardRouteRouteWithChildren -} - -const AppRouteRouteChildren: AppRouteRouteChildren = { - AppDashboardRouteRoute: AppDashboardRouteRouteWithChildren, -} - -const AppRouteRouteWithChildren = AppRouteRoute._addFileChildren( - AppRouteRouteChildren, -) - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - AppRouteRoute: AppRouteRouteWithChildren, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() - -import type { getRouter } from './router.tsx' -import type { createStart } from '@tanstack/react-start' -declare module '@tanstack/react-start' { - interface Register { - ssr: true - router: Awaited> - } -} diff --git a/e2e/react-start/css-inline/src/router.tsx b/e2e/react-start/css-inline/src/router.tsx deleted file mode 100644 index 68365b748e..0000000000 --- a/e2e/react-start/css-inline/src/router.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' - -export const getRouter = () => { - return createRouter({ - routeTree, - defaultPreload: 'intent', - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} diff --git a/e2e/react-start/css-inline/src/routes/__root.tsx b/e2e/react-start/css-inline/src/routes/__root.tsx deleted file mode 100644 index 52ebd8d5f6..0000000000 --- a/e2e/react-start/css-inline/src/routes/__root.tsx +++ /dev/null @@ -1,30 +0,0 @@ -/// -import { HeadContent, Scripts, createRootRoute } from '@tanstack/react-router' -import { Shell } from '~/components/Shell' -import type { ReactNode } from 'react' - -export const Route = createRootRoute({ - head: () => ({ - meta: [ - { charSet: 'utf-8' }, - { name: 'viewport', content: 'width=device-width, initial-scale=1' }, - { title: 'Inline CSS E2E' }, - ], - }), - component: Shell, - shellComponent: RootDocument, -}) - -function RootDocument({ children }: { children: ReactNode }) { - return ( - - - - - - {children} - - - - ) -} diff --git a/e2e/react-start/css-inline/src/routes/app/dashboard/details.tsx b/e2e/react-start/css-inline/src/routes/app/dashboard/details.tsx deleted file mode 100644 index 8a0890bca4..0000000000 --- a/e2e/react-start/css-inline/src/routes/app/dashboard/details.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { NestedPanel } from '~/components/NestedPanel' -import styles from '~/styles/dashboard-details.module.css' - -export const Route = createFileRoute('/app/dashboard/details')({ - component: DashboardDetails, -}) - -function DashboardDetails() { - return ( -
-

Details route

- -
- ) -} diff --git a/e2e/react-start/css-inline/src/routes/app/dashboard/index.tsx b/e2e/react-start/css-inline/src/routes/app/dashboard/index.tsx deleted file mode 100644 index 35205cc9cf..0000000000 --- a/e2e/react-start/css-inline/src/routes/app/dashboard/index.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { NestedPanel } from '~/components/NestedPanel' -import styles from '~/styles/dashboard-index.module.css' - -export const Route = createFileRoute('/app/dashboard/')({ - head: () => ({ - meta: [{ title: 'Inline CSS dashboard' }], - }), - component: DashboardIndex, -}) - -function DashboardIndex() { - return ( -
-

Inline dashboard

- -
- ) -} diff --git a/e2e/react-start/css-inline/src/routes/app/dashboard/route.tsx b/e2e/react-start/css-inline/src/routes/app/dashboard/route.tsx deleted file mode 100644 index 6d1fcd2fec..0000000000 --- a/e2e/react-start/css-inline/src/routes/app/dashboard/route.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' -import styles from '~/styles/dashboard-layout.module.css' - -export const Route = createFileRoute('/app/dashboard')({ - component: DashboardLayout, -}) - -function DashboardLayout() { - return ( -
-

Dashboard route layout CSS

- -
- ) -} diff --git a/e2e/react-start/css-inline/src/routes/app/route.tsx b/e2e/react-start/css-inline/src/routes/app/route.tsx deleted file mode 100644 index a9490663b6..0000000000 --- a/e2e/react-start/css-inline/src/routes/app/route.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' -import styles from '~/styles/app-layout.module.css' - -export const Route = createFileRoute('/app')({ - component: AppLayout, -}) - -function AppLayout() { - return ( -
-

Nested app shell

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

Inline CSS home

- Open dashboard -
- ) -} diff --git a/e2e/react-start/css-inline/src/server.ts b/e2e/react-start/css-inline/src/server.ts deleted file mode 100644 index 3fd3005e59..0000000000 --- a/e2e/react-start/css-inline/src/server.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { - createStartHandler, - defaultStreamHandler, -} from '@tanstack/react-start/server' -import { createServerEntry } from '@tanstack/react-start/server-entry' -import type { TransformAssetsFn } from '@tanstack/react-start/server' - -const transformInlineCssAssets = - process.env.CSS_INLINE_TRANSFORM_ASSETS === 'true' -const transformAssets: TransformAssetsFn = ({ kind, url }) => { - if (kind === 'css-url') { - return `${url}${url.includes('?') ? '&' : '?'}cdn=1` - } - - return url -} - -const handler = createStartHandler({ - handler: defaultStreamHandler, - // The request option below should win over this handler-level default. - inlineCss: false, - ...(transformInlineCssAssets - ? { - transformAssets, - } - : {}), -}) - -export default createServerEntry({ - fetch(request) { - return handler(request, { - inlineCss: request.headers.get('x-inline-css') !== 'false', - }) - }, -}) diff --git a/e2e/react-start/css-inline/src/styles/app-layout.module.css b/e2e/react-start/css-inline/src/styles/app-layout.module.css deleted file mode 100644 index b5f2678ed9..0000000000 --- a/e2e/react-start/css-inline/src/styles/app-layout.module.css +++ /dev/null @@ -1,11 +0,0 @@ -.layout { - border: 4px solid rgb(22, 163, 74); - border-radius: 18px; - background: rgb(220, 252, 231); - padding: 18px; -} - -.heading { - color: rgb(21, 128, 61); - margin: 0 0 16px; -} diff --git a/e2e/react-start/css-inline/src/styles/dashboard-details.module.css b/e2e/react-start/css-inline/src/styles/dashboard-details.module.css deleted file mode 100644 index 4162d3fae6..0000000000 --- a/e2e/react-start/css-inline/src/styles/dashboard-details.module.css +++ /dev/null @@ -1,7 +0,0 @@ -.details { - background: rgb(255, 237, 213); - border: 3px solid rgb(234, 88, 12); - border-radius: 14px; - color: rgb(154, 52, 18); - padding: 20px; -} diff --git a/e2e/react-start/css-inline/src/styles/dashboard-index.module.css b/e2e/react-start/css-inline/src/styles/dashboard-index.module.css deleted file mode 100644 index 36974ec4a6..0000000000 --- a/e2e/react-start/css-inline/src/styles/dashboard-index.module.css +++ /dev/null @@ -1,12 +0,0 @@ -.card { - background-color: rgb(254, 249, 195); - background-image: url('./inline-dot.svg'); - border: 3px solid rgb(202, 138, 4); - border-radius: 14px; - padding: 20px; -} - -.title { - color: rgb(133, 77, 14); - margin-top: 0; -} diff --git a/e2e/react-start/css-inline/src/styles/dashboard-layout.module.css b/e2e/react-start/css-inline/src/styles/dashboard-layout.module.css deleted file mode 100644 index a6165a77dc..0000000000 --- a/e2e/react-start/css-inline/src/styles/dashboard-layout.module.css +++ /dev/null @@ -1,13 +0,0 @@ -.dashboard { - border-left: 8px solid rgb(124, 58, 237); - background: rgb(245, 243, 255); - padding: 18px; -} - -.kicker { - color: rgb(109, 40, 217); - font-size: 14px; - font-weight: 700; - letter-spacing: 0.08em; - text-transform: uppercase; -} diff --git a/e2e/react-start/css-inline/src/styles/inline-dot.svg b/e2e/react-start/css-inline/src/styles/inline-dot.svg deleted file mode 100644 index 846de3ee38..0000000000 --- a/e2e/react-start/css-inline/src/styles/inline-dot.svg +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - This file is intentionally larger than Vite's default inline asset limit so - the CSS inline e2e fixture exercises emitted CSS URL rewriting instead of - data URL inlining. - 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 - 111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 - 222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222 - 333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333 - 444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444 - 555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555 - 666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666 - 777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777 - 888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888 - 999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999 - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb - cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc - dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd - eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee - ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff - gggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg - hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh - iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii - jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj - - diff --git a/e2e/react-start/css-inline/src/styles/nested-panel.module.css b/e2e/react-start/css-inline/src/styles/nested-panel.module.css deleted file mode 100644 index 93c929307b..0000000000 --- a/e2e/react-start/css-inline/src/styles/nested-panel.module.css +++ /dev/null @@ -1,11 +0,0 @@ -.panel { - background: rgb(219, 234, 254); - border: 2px dashed rgb(37, 99, 235); - border-radius: 10px; - margin-top: 16px; - padding: 12px; -} - -.label { - color: rgb(30, 64, 175); -} diff --git a/e2e/react-start/css-inline/src/styles/shell.module.css b/e2e/react-start/css-inline/src/styles/shell.module.css deleted file mode 100644 index 9b01ebe2ab..0000000000 --- a/e2e/react-start/css-inline/src/styles/shell.module.css +++ /dev/null @@ -1,18 +0,0 @@ -.shell { - min-height: 100vh; - color: rgb(15, 23, 42); - background: rgb(240, 249, 255); - font-family: Arial, sans-serif; - padding: 24px; -} - -.nav { - display: flex; - gap: 16px; - margin-bottom: 24px; -} - -.nav a { - color: rgb(3, 105, 161); - font-weight: 700; -} diff --git a/e2e/react-start/css-inline/tests/css-inline.spec.ts b/e2e/react-start/css-inline/tests/css-inline.spec.ts deleted file mode 100644 index 89d7d3992f..0000000000 --- a/e2e/react-start/css-inline/tests/css-inline.spec.ts +++ /dev/null @@ -1,253 +0,0 @@ -import { expect } from '@playwright/test' -import { collectBrowserErrors, test } from '@tanstack/router-e2e-utils' - -const buildUrl = (baseURL: string, pathname: string) => - baseURL.replace(/\/$/, '') + pathname - -async function getStyle(page: any, testId: string, property: string) { - return page.getByTestId(testId).evaluate((element: Element, prop: string) => { - return getComputedStyle(element).getPropertyValue(prop) - }, property) -} - -async function getInlineCssTexts(page: any) { - return page - .locator('style') - .evaluateAll((elements: Array) => - elements - .map((element) => element.textContent ?? '') - .filter((text) => text.includes('background')), - ) -} - -async function waitForHydration(page: any) { - await page.waitForFunction(() => { - return (window as any).__CSS_INLINE_E2E_HYDRATED__ === true - }) -} - -test('SSR inlines active nested route CSS without manifest stylesheet links', async ({ - page, - request, - baseURL, -}) => { - const errors: Array = [] - page.on('console', (message) => { - if (message.type() === 'error') { - errors.push(message.text()) - } - }) - - const url = buildUrl(baseURL!, '/app/dashboard') - const response = await request.get(url) - const html = await response.text() - - expect(response.ok()).toBe(true) - expect(html).toContain('data-testid="dashboard-card"') - expect(html).not.toContain('data-tanstack-router-inline-css') - expect(html).not.toContain('data-allow-mismatch') - expect(html).not.toMatch(/]+rel="stylesheet"/) - expect(html).not.toContain('rel:"stylesheet"') - const styleMatches = Array.from( - html.matchAll(/]*>([\s\S]*?)<\/style>/g), - ) - expect(styleMatches).toHaveLength(1) - const inlineCss = styleMatches[0]?.[1] - expect(inlineCss?.length).toBeGreaterThan(100) - expect(inlineCss).not.toContain('\n') - if (process.env.CSS_INLINE_TRANSFORM_ASSETS === 'true') { - expect(inlineCss).toContain('cdn=1') - } else { - expect(inlineCss).not.toContain('cdn=1') - } - - await page.goto(url) - - await expect(page.getByTestId('dashboard-card')).toBeVisible() - await expect(page.getByTestId('nested-panel')).toBeVisible() - - await expect - .poll(() => getStyle(page, 'shell', 'background-color')) - .toBe('rgb(240, 249, 255)') - await expect - .poll(() => getStyle(page, 'app-layout', 'background-color')) - .toBe('rgb(220, 252, 231)') - await expect - .poll(() => getStyle(page, 'dashboard-layout', 'border-left-color')) - .toBe('rgb(124, 58, 237)') - await expect - .poll(() => getStyle(page, 'dashboard-card', 'background-color')) - .toBe('rgb(254, 249, 195)') - await expect - .poll(() => getStyle(page, 'nested-panel', 'background-color')) - .toBe('rgb(219, 234, 254)') - - const backgroundImage = await getStyle( - page, - 'dashboard-card', - 'background-image', - ) - expect(backgroundImage).not.toBe('none') - - const inlineStyleText = (await getInlineCssTexts(page))[0] - expect(inlineStyleText?.length).toBeGreaterThan(100) - - expect(errors.filter((error) => /hydration|Hydration/.test(error))).toEqual( - [], - ) -}) - -test('runtime request options can disable inline CSS', async ({ - page, - request, - baseURL, -}) => { - const url = buildUrl(baseURL!, '/app/dashboard') - const response = await request.get(url, { - headers: { - 'x-inline-css': 'false', - }, - }) - const html = await response.text() - - expect(response.ok()).toBe(true) - expect(html).toMatch(/]+rel="stylesheet"/) - expect(html).not.toMatch(/]*>[\s\S]*background[\s\S]*<\/style>/) - - await page.setExtraHTTPHeaders({ - 'x-inline-css': 'false', - }) - await page.goto(url) - - await expect(page.getByTestId('dashboard-card')).toBeVisible() - await expect.poll(() => getInlineCssTexts(page)).toHaveLength(0) - await expect - .poll(() => getStyle(page, 'dashboard-card', 'background-color')) - .toBe('rgb(254, 249, 195)') -}) - -test('client navigation keeps nested CSS module styles applied', async ({ - page, - baseURL, -}) => { - await page.goto(buildUrl(baseURL!, '/')) - await waitForHydration(page) - await page.getByTestId('nav-details').click() - await page.waitForURL('**/app/dashboard/details') - - await expect(page.getByTestId('details-card')).toBeVisible() - await expect - .poll(() => getStyle(page, 'details-card', 'background-color')) - .toBe('rgb(255, 237, 213)') - await expect - .poll(() => getStyle(page, 'nested-panel', 'border-top-color')) - .toBe('rgb(37, 99, 235)') -}) - -test('client navigation preserves the SSR inline shell stylesheet', async ({ - page, - baseURL, -}) => { - await page.goto(buildUrl(baseURL!, '/')) - await waitForHydration(page) - - const inlineStyle = page.locator('style[data-tsr-inline-css]') - await expect(inlineStyle).toHaveCount(1) - const original = await inlineStyle.evaluateHandle( - (style: HTMLStyleElement) => { - const mutations: Array = [] - const observer = new MutationObserver((records) => { - mutations.push(...records) - }) - observer.observe(style, { - childList: true, - characterData: true, - subtree: true, - }) - return { style, sheet: style.sheet, observer, mutations } - }, - ) - - await expect.poll(() => getInlineCssTexts(page)).toHaveLength(1) - await expect - .poll(() => getInlineCssTexts(page)) - .toEqual([expect.stringContaining('background')]) - await expect - .poll(() => getStyle(page, 'shell', 'background-color')) - .toBe('rgb(240, 249, 255)') - - await page.getByTestId('nav-dashboard').click() - await page.waitForURL('**/app/dashboard') - await expect(page).toHaveTitle('Inline CSS dashboard') - await expect(page.getByTestId('dashboard-card')).toBeVisible() - - await page.getByTestId('nav-home').click() - await expect(page).toHaveTitle('Inline CSS E2E') - await expect(page.getByTestId('home')).toBeVisible() - - // #8250: unchanged CSS text can hide a redundant innerHTML write that - // replaces the stylesheet or fails under Trusted Types. Observe native DOM - // mutations and CSSOM identity without patching the innerHTML setter. - expect( - await original.evaluate(({ style, sheet, observer, mutations }) => { - const mutationCount = mutations.length + observer.takeRecords().length - observer.disconnect() - return { - connected: style.isConnected, - sameSheet: style.sheet === sheet, - mutationCount, - } - }), - ).toEqual({ connected: true, sameSheet: true, mutationCount: 0 }) - await original.dispose() - - await expect.poll(() => getInlineCssTexts(page)).toHaveLength(1) - await expect - .poll(() => getInlineCssTexts(page)) - .toEqual([expect.stringContaining('background')]) - await expect - .poll(() => getStyle(page, 'shell', 'background-color')) - .toBe('rgb(240, 249, 255)') -}) - -test('client navigation preserves inline CSS with Trusted Types enforced', async ({ - page, -}) => { - const browserErrors = collectBrowserErrors(page) - const csp = "require-trusted-types-for 'script'; trusted-types 'none'" - await page.route('/', async (route) => { - const response = await route.fetch() - await route.fulfill({ - response, - headers: { ...response.headers(), 'content-security-policy': csp }, - }) - }) - - const response = await page.goto('/') - expect(response?.headers()['content-security-policy']).toBe(csp) - expect(await page.evaluate(() => 'trustedTypes' in window)).toBe(true) - await waitForHydration(page) - - const violations = await page.evaluateHandle(() => { - const directives: Array = [] - document.addEventListener('securitypolicyviolation', (event) => { - directives.push(event.effectiveDirective) - }) - return directives - }) - - await page.getByTestId('nav-dashboard').click() - await expect(page).toHaveTitle('Inline CSS dashboard') - await expect(page.getByTestId('dashboard-card')).toBeVisible() - await expect - .poll(() => getStyle(page, 'shell', 'background-color')) - .toBe('rgb(240, 249, 255)') - - await page.getByTestId('nav-home').click() - await expect(page).toHaveTitle('Inline CSS E2E') - await expect(page.getByTestId('home')).toBeVisible() - - expect(await violations.jsonValue()).toEqual([]) - expect(browserErrors).toEqual([]) - await violations.dispose() -}) diff --git a/e2e/react-start/css-inline/tsconfig.json b/e2e/react-start/css-inline/tsconfig.json deleted file mode 100644 index cc479423a1..0000000000 --- a/e2e/react-start/css-inline/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "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/e2e/react-start/css-inline/vite.config.ts b/e2e/react-start/css-inline/vite.config.ts deleted file mode 100644 index ccb64b4346..0000000000 --- a/e2e/react-start/css-inline/vite.config.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { defineConfig } from 'vite' -import { tanstackStart } from '@tanstack/react-start/plugin/vite' -import viteReact from '@vitejs/plugin-react' - -const outDir = process.env.E2E_DIST_DIR ?? 'dist-vite-ssr' -const transformInlineCssAssets = - process.env.CSS_INLINE_TRANSFORM_ASSETS === 'true' - -export default defineConfig({ - resolve: { tsconfigPaths: true }, - build: { - outDir, - }, - server: { - port: 3000, - }, - plugins: [ - tanstackStart({ - server: { - build: { - inlineCss: transformInlineCssAssets - ? { enabled: true, transformAssets: true } - : true, - }, - }, - }), - viteReact(), - ], -}) diff --git a/e2e/react-start/css-modules/.gitignore b/e2e/react-start/css-modules/.gitignore index a1fbca128d..229709a89d 100644 --- a/e2e/react-start/css-modules/.gitignore +++ b/e2e/react-start/css-modules/.gitignore @@ -3,4 +3,3 @@ dist test-results playwright-report port*.txt -.cloudflare diff --git a/e2e/react-start/css-modules/cloudflare.config.ts b/e2e/react-start/css-modules/cloudflare.config.ts deleted file mode 100644 index e2bd5e13f1..0000000000 --- a/e2e/react-start/css-modules/cloudflare.config.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { defineConfig } from 'cf/config' - -// Used by rsbuild-plugin-cloudflare (E2E_RSBUILD_CLOUDFLARE=true). -// The Vite Cloudflare variant still reads wrangler.jsonc. -export default defineConfig({ - worker: { - name: 'tanstack-start-css-modules', - entrypoint: '@tanstack/react-start/server-entry', - compatibilityDate: '2026-11-01', - }, -}) diff --git a/e2e/react-start/css-modules/package.json b/e2e/react-start/css-modules/package.json index 25c11d7321..00cd504b43 100644 --- a/e2e/react-start/css-modules/package.json +++ b/e2e/react-start/css-modules/package.json @@ -12,8 +12,6 @@ "dev:e2e:basepath": "VITE_BASE_PATH=/my-app vite dev --port $PORT", "dev:cloudflare": "echo 'Cloudflare dev mode has React duplication issues - use build+preview instead' && exit 1", "dev:e2e:cloudflare": "echo 'Cloudflare dev mode has React duplication issues - use build+preview instead' && exit 1", - "dev:e2e:rsbuild": "rsbuild dev --port $PORT", - "dev:e2e:rsbuild-cloudflare": "E2E_RSBUILD_CLOUDFLARE=true rsbuild dev --port $PORT", "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", @@ -21,16 +19,11 @@ "test:e2e:dev:nitro": "MODE=dev VITE_CONFIG=nitro playwright test --project=chromium", "test:e2e:dev:basepath": "MODE=dev VITE_CONFIG=basepath playwright test --project=chromium", "_test:e2e:dev:cloudflare": "MODE=dev VITE_CONFIG=cloudflare playwright test --project=chromium", - "test:e2e:dev:rsbuild": "MODE=dev VITE_CONFIG=rsbuild playwright test --project=chromium", - "test:e2e:dev:rsbuild-cloudflare": "MODE=dev VITE_CONFIG=rsbuild-cloudflare playwright test --project=chromium", - "test:e2e:prod:default": "MODE=prod playwright test --project=chromium", - "test:e2e:prod": "pnpm run test:e2e:prod:default && pnpm run test:e2e:prod:css-code-split-false", - "test:e2e:prod:css-code-split-false": "MODE=prod VITE_CSS_CODE_SPLIT=false playwright test tests/css.prod.spec.ts --project=chromium", - "test:e2e": "pnpm run test:e2e:dev && pnpm run test:e2e:prod", - "test:e2e:nitro": "pnpm run test:e2e:dev:nitro", - "test:e2e:basepath": "pnpm run test:e2e:dev:basepath", - "_test:e2e:cloudflare": "echo 'Cloudflare dev mode disabled - React duplication issues' && exit 0", - "build:rsbuild": "rsbuild build && tsc --noEmit" + "test:e2e:prod": "MODE=prod playwright test --project=chromium", + "test:e2e": "rm -rf port*.txt; pnpm run test:e2e:dev && pnpm run test:e2e:prod", + "test:e2e:nitro": "rm -rf port*.txt; pnpm run test:e2e:dev:nitro", + "test:e2e:basepath": "rm -rf port*.txt; pnpm run test:e2e:dev:basepath", + "_test:e2e:cloudflare": "echo 'Cloudflare dev mode disabled - React duplication issues' && exit 0" }, "dependencies": { "@tanstack/react-router": "workspace:*", @@ -40,37 +33,17 @@ }, "devDependencies": { "@cloudflare/vite-plugin": "^1.29.0", - "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", - "@rsbuild/plugin-react": "^2.0.0", - "@rsbuild/plugin-sass": "^2.0.1", + "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:*", "@types/node": "^22.10.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@typescript/native": "npm:typescript@^7.0.2", "@vitejs/plugin-react": "^6.0.1", - "cf": "1.0.0-beta.28", - "nitro": "^3.0.260903-beta", - "rsbuild-plugin-cloudflare": "^0.0.4", + "nitro": "^3.0.260311-beta", "sass": "^1.97.2", - "srvx": "^1.0.0", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", + "srvx": "^0.11.9", + "typescript": "^5.7.2", + "vite": "^8.0.0", "wrangler": "^4.74.0" - }, - "nx": { - "metadata": { - "playwrightModes": [ - { - "toolchain": "vite", - "mode": "ssr" - }, - { - "toolchain": "rsbuild", - "mode": "ssr" - } - ] - } } } diff --git a/e2e/react-start/css-modules/playwright.config.ts b/e2e/react-start/css-modules/playwright.config.ts index 7e7ad3d9b3..644798ca99 100644 --- a/e2e/react-start/css-modules/playwright.config.ts +++ b/e2e/react-start/css-modules/playwright.config.ts @@ -1,41 +1,37 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } const mode = process.env.MODE ?? 'prod' const isDev = mode === 'dev' -const distDir = process.env.E2E_DIST_DIR const viteConfig = process.env.VITE_CONFIG // 'nitro' | 'basepath' | 'cloudflare' | undefined -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort( + viteConfig ? `${packageJson.name}-${viteConfig}` : packageJson.name, +) // When using basepath config, the app is served at /my-app const basePath = viteConfig === 'basepath' ? '/my-app' : '' const baseURL = `http://localhost:${PORT}${basePath}` // Select the appropriate dev command based on VITE_CONFIG -const devCommand = viteConfig - ? `pnpm dev:e2e:${viteConfig}` - : 'pnpm dev:e2e --port 0' +const devCommand = viteConfig ? `pnpm dev:e2e:${viteConfig}` : 'pnpm dev:e2e' export default defineConfig({ testDir: './tests', - testMatch: isDev ? '**/*.dev.spec.ts' : '**/*.prod.spec.ts', workers: 1, reporter: [['line']], globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', use: { baseURL, }, webServer: { - command: isDev - ? devCommand - : distDir - ? `pnpm exec srvx --prod --dir=. -s ${distDir}/client --entry ${distDir}/server/server.js` - : `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + command: isDev ? devCommand : `pnpm build && PORT=${PORT} pnpm start`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { VITE_NODE_ENV: 'test', diff --git a/e2e/react-start/css-modules/rsbuild.config.ts b/e2e/react-start/css-modules/rsbuild.config.ts deleted file mode 100644 index 499ed67ebc..0000000000 --- a/e2e/react-start/css-modules/rsbuild.config.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { defineConfig } from '@rsbuild/core' -import { pluginReact } from '@rsbuild/plugin-react' -import { pluginSass } from '@rsbuild/plugin-sass' -import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild' -import { cloudflare } from 'rsbuild-plugin-cloudflare' - -// E2E_RSBUILD_CLOUDFLARE: Set to 'true' to run the SSR environment in workerd -const useCloudflare = process.env.E2E_RSBUILD_CLOUDFLARE === 'true' - -export default defineConfig({ - plugins: [ - pluginReact(), - pluginSass(), - ...(useCloudflare - ? [ - cloudflare({ - rsbuildEnvironment: { name: 'ssr' }, - inspectorPort: false, - }), - ] - : []), - tanstackStart(), - ], - output: { - distPath: { - root: process.env.E2E_DIST_DIR ?? 'dist-rsbuild-ssr', - }, - }, - tools: { - rspack(config, { environment }) { - if (environment.name === 'ssr') { - config.output ??= {} - config.output.filename = 'server.js' - } - if (environment.name !== 'client') { - return - } - config.optimization ??= {} - // Extract the shared component and its helper into their own chunks so - // a route depends on a shared chunk that depends on another shared chunk. - config.optimization.splitChunks = { - cacheGroups: { - sharedHeader: { - test: /[\\/]src[\\/]components[\\/]/, - chunks: 'async', - minChunks: 2, - minSize: 0, - enforce: true, - name: 'shared-header', - }, - sharedFormat: { - test: /[\\/]src[\\/]utils[\\/]/, - chunks: 'async', - minChunks: 2, - minSize: 0, - enforce: true, - name: 'shared-format', - }, - }, - } - }, - }, -}) diff --git a/e2e/react-start/css-modules/src/components/Header.module.css b/e2e/react-start/css-modules/src/components/Header.module.css deleted file mode 100644 index e6878a5410..0000000000 --- a/e2e/react-start/css-modules/src/components/Header.module.css +++ /dev/null @@ -1,14 +0,0 @@ -.header { - --repro-shared-header: 1; - display: grid; - grid-template-columns: minmax(0, 1fr) auto; - align-items: center; - height: 64px; - padding-inline: 16px; - background: #e4f2e9; -} - -.header h1 { - margin: 0; - font-size: 24px; -} diff --git a/e2e/react-start/css-modules/src/components/Header.tsx b/e2e/react-start/css-modules/src/components/Header.tsx deleted file mode 100644 index f16b12e8ff..0000000000 --- a/e2e/react-start/css-modules/src/components/Header.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import { formatTitle } from '../utils/formatTitle' -import styles from './Header.module.css' - -export function Header({ title }: { title: string }) { - return ( -
-

{formatTitle(title)}

- -
- ) -} diff --git a/e2e/react-start/css-modules/src/components/shared-widget-lazy.tsx b/e2e/react-start/css-modules/src/components/shared-widget-lazy.tsx new file mode 100644 index 0000000000..6d9ddce6f5 --- /dev/null +++ b/e2e/react-start/css-modules/src/components/shared-widget-lazy.tsx @@ -0,0 +1,5 @@ +import { SharedWidget } from './shared-widget' + +export default function SharedWidgetLazy() { + return +} diff --git a/e2e/react-start/css-modules/src/components/shared-widget.tsx b/e2e/react-start/css-modules/src/components/shared-widget.tsx new file mode 100644 index 0000000000..51a3be072c --- /dev/null +++ b/e2e/react-start/css-modules/src/components/shared-widget.tsx @@ -0,0 +1,15 @@ +/// +import styles from '~/styles/shared-widget.module.css' + +export function SharedWidget() { + return ( +
+
+ Shared widget styles +
+
+ This widget uses a CSS module shared by a static route and a lazy route. +
+
+ ) +} diff --git a/e2e/react-start/css-modules/src/routeTree.gen.ts b/e2e/react-start/css-modules/src/routeTree.gen.ts index 2789a3490a..ab5f0b6554 100644 --- a/e2e/react-start/css-modules/src/routeTree.gen.ts +++ b/e2e/react-start/css-modules/src/routeTree.gen.ts @@ -9,37 +9,16 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as AlphaRouteImport } from './routes/alpha' -import { Route as BetaRouteImport } from './routes/beta' -import { Route as GammaRouteImport } from './routes/gamma' -import { Route as ModulesRouteImport } from './routes/modules' -import { Route as QuotesRouteImport } from './routes/quotes' import { Route as SassMixinRouteImport } from './routes/sass-mixin' +import { Route as QuotesRouteImport } from './routes/quotes' +import { Route as ModulesRouteImport } from './routes/modules' +import { Route as LazyCssStaticRouteImport } from './routes/lazy-css-static' +import { Route as LazyCssLazyRouteImport } from './routes/lazy-css-lazy' +import { Route as IndexRouteImport } from './routes/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const AlphaRoute = AlphaRouteImport.update({ - id: '/alpha', - path: '/alpha', - getParentRoute: () => rootRouteImport, -} as any) -const BetaRoute = BetaRouteImport.update({ - id: '/beta', - path: '/beta', - getParentRoute: () => rootRouteImport, -} as any) -const GammaRoute = GammaRouteImport.update({ - id: '/gamma', - path: '/gamma', - getParentRoute: () => rootRouteImport, -} as any) -const ModulesRoute = ModulesRouteImport.update({ - id: '/modules', - path: '/modules', +const SassMixinRoute = SassMixinRouteImport.update({ + id: '/sass-mixin', + path: '/sass-mixin', getParentRoute: () => rootRouteImport, } as any) const QuotesRoute = QuotesRouteImport.update({ @@ -47,26 +26,39 @@ const QuotesRoute = QuotesRouteImport.update({ path: '/quotes', getParentRoute: () => rootRouteImport, } as any) -const SassMixinRoute = SassMixinRouteImport.update({ - id: '/sass-mixin', - path: '/sass-mixin', +const ModulesRoute = ModulesRouteImport.update({ + id: '/modules', + path: '/modules', + getParentRoute: () => rootRouteImport, +} as any) +const LazyCssStaticRoute = LazyCssStaticRouteImport.update({ + id: '/lazy-css-static', + path: '/lazy-css-static', + getParentRoute: () => rootRouteImport, +} as any) +const LazyCssLazyRoute = LazyCssLazyRouteImport.update({ + id: '/lazy-css-lazy', + path: '/lazy-css-lazy', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute - '/alpha': typeof AlphaRoute - '/beta': typeof BetaRoute - '/gamma': typeof GammaRoute + '/lazy-css-lazy': typeof LazyCssLazyRoute + '/lazy-css-static': typeof LazyCssStaticRoute '/modules': typeof ModulesRoute '/quotes': typeof QuotesRoute '/sass-mixin': typeof SassMixinRoute } export interface FileRoutesByTo { '/': typeof IndexRoute - '/alpha': typeof AlphaRoute - '/beta': typeof BetaRoute - '/gamma': typeof GammaRoute + '/lazy-css-lazy': typeof LazyCssLazyRoute + '/lazy-css-static': typeof LazyCssStaticRoute '/modules': typeof ModulesRoute '/quotes': typeof QuotesRoute '/sass-mixin': typeof SassMixinRoute @@ -74,9 +66,8 @@ export interface FileRoutesByTo { export interface FileRoutesById { __root__: typeof rootRouteImport '/': typeof IndexRoute - '/alpha': typeof AlphaRoute - '/beta': typeof BetaRoute - '/gamma': typeof GammaRoute + '/lazy-css-lazy': typeof LazyCssLazyRoute + '/lazy-css-static': typeof LazyCssStaticRoute '/modules': typeof ModulesRoute '/quotes': typeof QuotesRoute '/sass-mixin': typeof SassMixinRoute @@ -84,16 +75,25 @@ export interface FileRoutesById { export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath fullPaths: - '/' | '/alpha' | '/beta' | '/gamma' | '/modules' | '/quotes' | '/sass-mixin' + | '/' + | '/lazy-css-lazy' + | '/lazy-css-static' + | '/modules' + | '/quotes' + | '/sass-mixin' fileRoutesByTo: FileRoutesByTo to: - '/' | '/alpha' | '/beta' | '/gamma' | '/modules' | '/quotes' | '/sass-mixin' + | '/' + | '/lazy-css-lazy' + | '/lazy-css-static' + | '/modules' + | '/quotes' + | '/sass-mixin' id: | '__root__' | '/' - | '/alpha' - | '/beta' - | '/gamma' + | '/lazy-css-lazy' + | '/lazy-css-static' | '/modules' | '/quotes' | '/sass-mixin' @@ -101,9 +101,8 @@ export interface FileRouteTypes { } export interface RootRouteChildren { IndexRoute: typeof IndexRoute - AlphaRoute: typeof AlphaRoute - BetaRoute: typeof BetaRoute - GammaRoute: typeof GammaRoute + LazyCssLazyRoute: typeof LazyCssLazyRoute + LazyCssStaticRoute: typeof LazyCssStaticRoute ModulesRoute: typeof ModulesRoute QuotesRoute: typeof QuotesRoute SassMixinRoute: typeof SassMixinRoute @@ -111,39 +110,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/alpha': { - id: '/alpha' - path: '/alpha' - fullPath: '/alpha' - preLoaderRoute: typeof AlphaRouteImport - parentRoute: typeof rootRouteImport - } - '/beta': { - id: '/beta' - path: '/beta' - fullPath: '/beta' - preLoaderRoute: typeof BetaRouteImport - parentRoute: typeof rootRouteImport - } - '/gamma': { - id: '/gamma' - path: '/gamma' - fullPath: '/gamma' - preLoaderRoute: typeof GammaRouteImport - parentRoute: typeof rootRouteImport - } - '/modules': { - id: '/modules' - path: '/modules' - fullPath: '/modules' - preLoaderRoute: typeof ModulesRouteImport + '/sass-mixin': { + id: '/sass-mixin' + path: '/sass-mixin' + fullPath: '/sass-mixin' + preLoaderRoute: typeof SassMixinRouteImport parentRoute: typeof rootRouteImport } '/quotes': { @@ -153,11 +124,32 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof QuotesRouteImport parentRoute: typeof rootRouteImport } - '/sass-mixin': { - id: '/sass-mixin' - path: '/sass-mixin' - fullPath: '/sass-mixin' - preLoaderRoute: typeof SassMixinRouteImport + '/modules': { + id: '/modules' + path: '/modules' + fullPath: '/modules' + preLoaderRoute: typeof ModulesRouteImport + parentRoute: typeof rootRouteImport + } + '/lazy-css-static': { + id: '/lazy-css-static' + path: '/lazy-css-static' + fullPath: '/lazy-css-static' + preLoaderRoute: typeof LazyCssStaticRouteImport + parentRoute: typeof rootRouteImport + } + '/lazy-css-lazy': { + id: '/lazy-css-lazy' + path: '/lazy-css-lazy' + fullPath: '/lazy-css-lazy' + preLoaderRoute: typeof LazyCssLazyRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } } @@ -165,9 +157,8 @@ declare module '@tanstack/react-router' { const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, - AlphaRoute: AlphaRoute, - BetaRoute: BetaRoute, - GammaRoute: GammaRoute, + LazyCssLazyRoute: LazyCssLazyRoute, + LazyCssStaticRoute: LazyCssStaticRoute, ModulesRoute: ModulesRoute, QuotesRoute: QuotesRoute, SassMixinRoute: SassMixinRoute, diff --git a/e2e/react-start/css-modules/src/routes/__root.tsx b/e2e/react-start/css-modules/src/routes/__root.tsx index d7840bc0c1..a383beacec 100644 --- a/e2e/react-start/css-modules/src/routes/__root.tsx +++ b/e2e/react-start/css-modules/src/routes/__root.tsx @@ -62,6 +62,20 @@ function RootComponent() { > Quoted CSS + + Lazy CSS Static + + + Lazy CSS Lazy +
diff --git a/e2e/react-start/css-modules/src/routes/alpha.tsx b/e2e/react-start/css-modules/src/routes/alpha.tsx deleted file mode 100644 index e894cd758f..0000000000 --- a/e2e/react-start/css-modules/src/routes/alpha.tsx +++ /dev/null @@ -1,13 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { Header } from '../components/Header' -import styles from '../styles/alpha.module.css' - -export const Route = createFileRoute('/alpha')({ component: Alpha }) - -function Alpha() { - return ( -
-
-
- ) -} diff --git a/e2e/react-start/css-modules/src/routes/beta.tsx b/e2e/react-start/css-modules/src/routes/beta.tsx deleted file mode 100644 index 4f139ac41a..0000000000 --- a/e2e/react-start/css-modules/src/routes/beta.tsx +++ /dev/null @@ -1,13 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { Header } from '../components/Header' -import styles from '../styles/beta.module.css' - -export const Route = createFileRoute('/beta')({ component: Beta }) - -function Beta() { - return ( -
-
-
- ) -} diff --git a/e2e/react-start/css-modules/src/routes/gamma.tsx b/e2e/react-start/css-modules/src/routes/gamma.tsx deleted file mode 100644 index a8e036b85f..0000000000 --- a/e2e/react-start/css-modules/src/routes/gamma.tsx +++ /dev/null @@ -1,8 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { formatTitle } from '../utils/formatTitle' - -export const Route = createFileRoute('/gamma')({ component: Gamma }) - -function Gamma() { - return
{formatTitle('Gamma')}
-} diff --git a/e2e/react-start/css-modules/src/routes/lazy-css-lazy.tsx b/e2e/react-start/css-modules/src/routes/lazy-css-lazy.tsx new file mode 100644 index 0000000000..4d147a9651 --- /dev/null +++ b/e2e/react-start/css-modules/src/routes/lazy-css-lazy.tsx @@ -0,0 +1,28 @@ +import * as React from 'react' +import { createFileRoute } from '@tanstack/react-router' + +const LazySharedWidget = React.lazy( + () => import('~/components/shared-widget-lazy'), +) + +export const Route = createFileRoute('/lazy-css-lazy')({ + component: LazyCssLazyRoute, +}) + +function LazyCssLazyRoute() { + return ( +
+

Lazy CSS Repro - Lazy Route

+

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

+ + Loading...
} + > + + +
+ ) +} diff --git a/e2e/react-start/css-modules/src/routes/lazy-css-static.tsx b/e2e/react-start/css-modules/src/routes/lazy-css-static.tsx new file mode 100644 index 0000000000..c9e3f33a0e --- /dev/null +++ b/e2e/react-start/css-modules/src/routes/lazy-css-static.tsx @@ -0,0 +1,24 @@ +import { ClientOnly, createFileRoute } from '@tanstack/react-router' +import { SharedWidget } from '~/components/shared-widget' + +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/react-start/css-modules/src/styles/alpha.module.css b/e2e/react-start/css-modules/src/styles/alpha.module.css deleted file mode 100644 index 12a606a8d3..0000000000 --- a/e2e/react-start/css-modules/src/styles/alpha.module.css +++ /dev/null @@ -1,4 +0,0 @@ -.page { - --repro-alpha: 1; - border: 4px solid #226844; -} diff --git a/e2e/react-start/css-modules/src/styles/beta.module.css b/e2e/react-start/css-modules/src/styles/beta.module.css deleted file mode 100644 index 719686a76b..0000000000 --- a/e2e/react-start/css-modules/src/styles/beta.module.css +++ /dev/null @@ -1,4 +0,0 @@ -.page { - --repro-beta: 1; - border: 4px solid #ac344c; -} diff --git a/e2e/react-start/css-modules/src/styles/shared-widget.module.css b/e2e/react-start/css-modules/src/styles/shared-widget.module.css new file mode 100644 index 0000000000..66f3d679d8 --- /dev/null +++ b/e2e/react-start/css-modules/src/styles/shared-widget.module.css @@ -0,0 +1,19 @@ +.widget { + background: rgb(255, 247, 237); + border: 2px solid rgb(249, 115, 22); + border-radius: 14px; + padding: 20px; +} + +.title { + color: rgb(154, 52, 18); + font-size: 20px; + font-weight: 700; + margin-bottom: 8px; +} + +.content { + color: rgb(194, 65, 12); + font-size: 14px; + line-height: 1.5; +} diff --git a/e2e/react-start/css-modules/src/utils/formatTitle.ts b/e2e/react-start/css-modules/src/utils/formatTitle.ts deleted file mode 100644 index d0325ac63e..0000000000 --- a/e2e/react-start/css-modules/src/utils/formatTitle.ts +++ /dev/null @@ -1,3 +0,0 @@ -export function formatTitle(title: string) { - return `${title} (repro-format-title)` -} diff --git a/e2e/react-start/css-modules/tests/css.prod.spec.ts b/e2e/react-start/css-modules/tests/css.prod.spec.ts index 3e5c5214e9..66aeff5700 100644 --- a/e2e/react-start/css-modules/tests/css.prod.spec.ts +++ b/e2e/react-start/css-modules/tests/css.prod.spec.ts @@ -1,80 +1,140 @@ import { expect } from '@playwright/test' import { test } from '@tanstack/router-e2e-utils' -test.skip(process.env.MODE !== 'prod', 'Prod-only coverage') -test.skip( - process.env.VITE_CSS_CODE_SPLIT !== 'false', - 'Requires cssCodeSplit=false mode', -) +test.skip(process.env.MODE === 'dev', 'Prod-only repro') -test.describe('CSS modules with cssCodeSplit disabled', () => { - test.describe('with JavaScript disabled', () => { - test.use({ javaScriptEnabled: false }) +test.describe('CSS styles in SSR (prod only)', () => { + const buildUrl = (baseURL: string, path: string) => { + return baseURL.replace(/\/$/, '') + path + } - test('CSS modules are applied on initial page load', async ({ page }) => { - await page.goto('/modules') - - const card = page.getByTestId('module-card') - await expect(card).toBeVisible() - - const className = await card.getAttribute('class') - expect(className).toBeTruthy() - expect(className).not.toBe('card') - expect(className!.length).toBeGreaterThan(5) - - 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('CSS modules styles persist after hydration', async ({ page }) => { - await page.goto('/modules') - - const card = page.getByTestId('module-card') - await expect(card).toBeVisible() - - 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 ({ + test('CSS modules stay applied when navigating from static to lazy route', async ({ page, + baseURL, }) => { - await page.goto('/') + await page.goto(buildUrl(baseURL!, '/lazy-css-static')) - const globalElement = page.getByTestId('global-styled') - await expect(globalElement).toBeVisible() + const widget = page.getByTestId('shared-widget') + await expect(widget).toBeVisible() - let backgroundColor = await globalElement.evaluate( + const backgroundColor = await widget.evaluate( (el) => getComputedStyle(el).backgroundColor, ) - expect(backgroundColor).toBe('rgb(59, 130, 246)') + expect(backgroundColor).toBe('rgb(255, 247, 237)') - await page.getByTestId('nav-modules').click() - await page.waitForURL('**/modules') + const borderTopColor = await widget.evaluate( + (el) => getComputedStyle(el).borderTopColor, + ) + expect(borderTopColor).toBe('rgb(249, 115, 22)') - const card = page.getByTestId('module-card') - await expect(card).toBeVisible() + await expect(page.getByTestId('lazy-css-static-hydrated')).toBeVisible() - await expect(async () => { - const backgroundColor = await card.evaluate( - (el) => getComputedStyle(el).backgroundColor, + await page.getByTestId('nav-lazy-css-lazy').click() + await page.waitForURL('**/lazy-css-lazy') + await expect(page.getByTestId('lazy-css-lazy-heading')).toBeVisible() + + const lazyWidget = page.getByTestId('shared-widget') + await expect(lazyWidget).toBeVisible() + + await expect + .poll( + () => lazyWidget.evaluate((el) => getComputedStyle(el).backgroundColor), + { timeout: 5_000 }, ) - expect(backgroundColor).toBe('rgb(240, 253, 244)') - }).toPass({ timeout: 5000 }) + .toBe('rgb(255, 247, 237)') + }) + + test('CSS modules stay 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() + + // Wait for lazy widget to load + const lazyWidget = page.getByTestId('shared-widget') + await expect(lazyWidget).toBeVisible() + + await expect + .poll( + () => lazyWidget.evaluate((el) => getComputedStyle(el).backgroundColor), + { timeout: 5_000 }, + ) + .toBe('rgb(255, 247, 237)') + + // Navigate to static route + await page.getByTestId('nav-lazy-css-static').click() + await page.waitForURL('**/lazy-css-static') + + const staticWidget = page.getByTestId('shared-widget') + await expect(staticWidget).toBeVisible() + + await expect + .poll( + () => + staticWidget.evaluate((el) => getComputedStyle(el).backgroundColor), + { timeout: 5_000 }, + ) + .toBe('rgb(255, 247, 237)') + + const borderTopColor = await staticWidget.evaluate( + (el) => getComputedStyle(el).borderTopColor, + ) + expect(borderTopColor).toBe('rgb(249, 115, 22)') + }) + + test('CSS modules applied on direct navigation to lazy route', async ({ + page, + baseURL, + }) => { + // Navigate directly to the lazy route (cold start, no prior static route) + await page.goto(buildUrl(baseURL!, '/lazy-css-lazy')) + await expect(page.getByTestId('lazy-css-lazy-heading')).toBeVisible() + + const widget = page.getByTestId('shared-widget') + await expect(widget).toBeVisible() + + await expect + .poll( + () => widget.evaluate((el) => getComputedStyle(el).backgroundColor), + { timeout: 5_000 }, + ) + .toBe('rgb(255, 247, 237)') + + const borderTopColor = await widget.evaluate( + (el) => getComputedStyle(el).borderTopColor, + ) + expect(borderTopColor).toBe('rgb(249, 115, 22)') + }) + + test('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() + + // Navigate to lazy + await page.getByTestId('nav-lazy-css-lazy').click() + await page.waitForURL('**/lazy-css-lazy') + await expect(page.getByTestId('shared-widget')).toBeVisible() + + // Navigate away to home + await page.getByTestId('nav-home').click() + await page.waitForURL(/\/([^/]*)(\/)?($|\?)/) + + // Navigate back to lazy + await page.getByTestId('nav-lazy-css-lazy').click() + await page.waitForURL('**/lazy-css-lazy') + + const widget = page.getByTestId('shared-widget') + await expect(widget).toBeVisible() + + await expect + .poll( + () => widget.evaluate((el) => getComputedStyle(el).backgroundColor), + { timeout: 5_000 }, + ) + .toBe('rgb(255, 247, 237)') }) }) diff --git a/e2e/react-start/css-modules/tests/setup/global.setup.ts b/e2e/react-start/css-modules/tests/setup/global.setup.ts index 7c0fce762a..e8879c0165 100644 --- a/e2e/react-start/css-modules/tests/setup/global.setup.ts +++ b/e2e/react-start/css-modules/tests/setup/global.setup.ts @@ -1,10 +1,20 @@ -import { preOptimizeDevServer, waitForServer } from '@tanstack/router-e2e-utils' +import { + e2eStartDummyServer, + getTestServerPort, + preOptimizeDevServer, + waitForServer, +} from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } export default async function setup() { + await e2eStartDummyServer(packageJson.name) + if (process.env.MODE !== 'dev') return const viteConfig = process.env.VITE_CONFIG // 'nitro' | 'basepath' | 'cloudflare' | undefined - const port = Number(process.env.E2E_APP_PORT ?? 0) + const port = await getTestServerPort( + viteConfig ? `${packageJson.name}-${viteConfig}` : packageJson.name, + ) const basePath = viteConfig === 'basepath' ? '/my-app' : '' const baseURL = `http://localhost:${port}${basePath}` diff --git a/e2e/react-start/css-modules/tests/setup/global.teardown.ts b/e2e/react-start/css-modules/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-start/css-modules/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-start/css-modules/tests/shared-css.prod.spec.ts b/e2e/react-start/css-modules/tests/shared-css.prod.spec.ts deleted file mode 100644 index 9a9595f819..0000000000 --- a/e2e/react-start/css-modules/tests/shared-css.prod.spec.ts +++ /dev/null @@ -1,94 +0,0 @@ -import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' -import type { Page } from '@playwright/test' - -test.skip( - process.env.VITE_CSS_CODE_SPLIT === 'false', - 'Route stylesheet isolation requires CSS code splitting', -) -test.use({ javaScriptEnabled: false }) - -async function getStylesheetContent(page: Page) { - const hrefs = await page - .locator('link[rel="stylesheet"]') - .evaluateAll((links: Array) => - links.map((link) => link.href), - ) - expect(hrefs.length).toBeGreaterThan(0) - const stylesheets = await Promise.all( - hrefs.map(async (href) => { - const response = await page.request.get(href) - expect(response.ok()).toBe(true) - return response.text() - }), - ) - return stylesheets.join('\n') -} - -for (const route of ['alpha', 'beta']) { - test(`${route} has complete and isolated CSS without JavaScript`, async ({ - page, - }) => { - await page.goto(`/${route}`) - - const header = page.getByTestId('shared-header') - await expect(header).toHaveCSS('display', 'grid') - await expect(header).toHaveCSS('height', '64px') - await expect(page.getByTestId('route-page')).toHaveCSS( - `--repro-${route}`, - '1', - ) - - const css = await getStylesheetContent(page) - expect(css).toContain('--repro-shared-header') - expect(css).toContain(`--repro-${route}`) - expect(css).not.toContain(`--repro-${route === 'alpha' ? 'beta' : 'alpha'}`) - }) -} - -function getScriptPreloadHrefs(html: string) { - return Array.from(html.matchAll(/]*>/g), (match) => match[0]) - .filter( - (tag) => - /\brel="modulepreload"/.test(tag) || - (/\brel="preload"/.test(tag) && /\bas="script"/.test(tag)), - ) - .map((tag) => tag.match(/\bhref="([^"]+)"/)?.[1]) - .filter((href): href is string => !!href) -} - -test('alpha preloads the shared header chunk and the chunk it depends on', async ({ - page, -}) => { - const response = await page.request.get('/alpha') - expect(response.ok()).toBe(true) - - const hrefs = getScriptPreloadHrefs(await response.text()) - expect(hrefs.length).toBeGreaterThan(0) - - const scripts = await Promise.all( - hrefs.map(async (href) => { - const script = await page.request.get(href) - expect(script.ok()).toBe(true) - return script.text() - }), - ) - - expect(scripts.some((code) => code.includes('shared-header'))).toBe(true) - expect(scripts.some((code) => code.includes('repro-format-title'))).toBe(true) -}) - -test('home does not load the shared header or route styles', async ({ - page, -}) => { - await page.goto('/') - await expect(page.getByTestId('global-styled')).toHaveCSS( - 'background-color', - 'rgb(59, 130, 246)', - ) - - const css = await getStylesheetContent(page) - expect(css).not.toContain('--repro-shared-header') - expect(css).not.toContain('--repro-alpha') - expect(css).not.toContain('--repro-beta') -}) diff --git a/e2e/react-start/css-modules/tsconfig.json b/e2e/react-start/css-modules/tsconfig.json index cef9369516..3a9fb7cd71 100644 --- a/e2e/react-start/css-modules/tsconfig.json +++ b/e2e/react-start/css-modules/tsconfig.json @@ -13,6 +13,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/react-start/css-modules/vite.config.ts b/e2e/react-start/css-modules/vite.config.ts index c9c27f7f9a..93c2d05136 100644 --- a/e2e/react-start/css-modules/vite.config.ts +++ b/e2e/react-start/css-modules/vite.config.ts @@ -5,10 +5,8 @@ import viteReact from '@vitejs/plugin-react' // Environment variables for different test configurations: // - VITE_BASE_PATH: Set to '/my-app' for basepath testing // - VITE_USE_NITRO: Set to 'true' to enable Nitro server -// - VITE_CSS_CODE_SPLIT: Set to 'false' to disable CSS code splitting in prod const basePath = process.env.VITE_BASE_PATH const useNitro = process.env.VITE_USE_NITRO === 'true' -const cssCodeSplit = process.env.VITE_CSS_CODE_SPLIT !== 'false' export default defineConfig(async () => { // Dynamically import nitro only when needed to avoid loading it when not used @@ -20,10 +18,6 @@ export default defineConfig(async () => { server: { port: 3000, }, - build: { - outDir: process.env.E2E_DIST_DIR ?? 'dist', - cssCodeSplit, - }, plugins: [ // Nitro is placed BEFORE tanstackStart to test that our CSS middleware // works regardless of plugin order (nitro has a catch-all middleware) diff --git a/e2e/react-start/custom-basepath/express-server.ts b/e2e/react-start/custom-basepath/express-server.ts index b9bf393466..87dcfb50da 100644 --- a/e2e/react-start/custom-basepath/express-server.ts +++ b/e2e/react-start/custom-basepath/express-server.ts @@ -1,6 +1,5 @@ import express from 'express' import { toNodeHandler } from 'srvx/node' -import type { AddressInfo } from 'node:net' import type { NodeHttp1Handler } from 'srvx' const DEVELOPMENT = process.env.NODE_ENV === 'development' @@ -41,11 +40,6 @@ if (DEVELOPMENT) { }) } -const httpServer = app.listen(PORT, (error) => { - if (error) { - throw error - } - console.log( - `E2E app: http://localhost:${(httpServer.address() as AddressInfo).port}`, - ) +app.listen(PORT, () => { + console.log(`Server is running on http://localhost:${PORT}`) }) diff --git a/e2e/react-start/custom-basepath/package.json b/e2e/react-start/custom-basepath/package.json index e93949eea2..b2295fba6d 100644 --- a/e2e/react-start/custom-basepath/package.json +++ b/e2e/react-start/custom-basepath/package.json @@ -8,32 +8,31 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "tsx express-server.ts", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", "@tanstack/react-router-devtools": "workspace:^", "@tanstack/react-start": "workspace:^", - "express": "^5.2.1", + "express": "^5.1.0", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "catalog:" + "redaxios": "^0.5.1" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", - "@types/express": "^5.0.6", + "@types/express": "^5.0.3", "@types/node": "^22.10.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "cross-env": "^10.0.0", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "tsx": "^4.20.3", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/e2e/react-start/custom-basepath/playwright.config.ts b/e2e/react-start/custom-basepath/playwright.config.ts index e113ce64ad..5095425f47 100644 --- a/e2e/react-start/custom-basepath/playwright.config.ts +++ b/e2e/react-start/custom-basepath/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}/custom/basepath` /** @@ -13,19 +18,19 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', - env: { - NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, - }, }, projects: [ diff --git a/e2e/react-start/custom-basepath/src/components/DefaultCatchBoundary.tsx b/e2e/react-start/custom-basepath/src/components/DefaultCatchBoundary.tsx index 405fb5f4a7..ef2daa1ea1 100644 --- a/e2e/react-start/custom-basepath/src/components/DefaultCatchBoundary.tsx +++ b/e2e/react-start/custom-basepath/src/components/DefaultCatchBoundary.tsx @@ -1,15 +1,17 @@ import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, 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 === '/', + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, }) console.error(error) diff --git a/e2e/react-start/custom-basepath/src/routeTree.gen.ts b/e2e/react-start/custom-basepath/src/routeTree.gen.ts index 18cc9b5163..9aacbfbdf0 100644 --- a/e2e/react-start/custom-basepath/src/routeTree.gen.ts +++ b/e2e/react-start/custom-basepath/src/routeTree.gen.ts @@ -9,40 +9,25 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as LogoutRouteImport } from './routes/logout' -import { Route as NavigateTestRouteImport } from './routes/navigate-test' -import { Route as PostsRouteImport } from './routes/posts' import { Route as UsersRouteImport } from './routes/users' -import { Route as ApiUsersRouteImport } from './routes/api.users' -import { Route as 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 PostsRouteImport } from './routes/posts' +import { Route as NavigateTestRouteImport } from './routes/navigate-test' +import { Route as LogoutRouteImport } from './routes/logout' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as IndexRouteImport } from './routes/index' import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as RedirectIndexRouteImport } from './routes/redirect/index' +import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as ApiUsersIdRouteImport } from './routes/api/users.$id' +import { Route as RedirectThrowItRouteImport } from './routes/redirect/throw-it' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as ApiUsersRouteImport } from './routes/api.users' import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' +import { Route as ApiUsersIdRouteImport } from './routes/api/users.$id' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const DeferredRoute = DeferredRouteImport.update({ - id: '/deferred', - path: '/deferred', - getParentRoute: () => rootRouteImport, -} as any) -const LogoutRoute = LogoutRouteImport.update({ - id: '/logout', - path: '/logout', - getParentRoute: () => rootRouteImport, -} as any) -const NavigateTestRoute = NavigateTestRouteImport.update({ - id: '/navigate-test', - path: '/navigate-test', +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', getParentRoute: () => rootRouteImport, } as any) const PostsRoute = PostsRouteImport.update({ @@ -50,34 +35,24 @@ const PostsRoute = PostsRouteImport.update({ path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const NavigateTestRoute = NavigateTestRouteImport.update({ + id: '/navigate-test', + path: '/navigate-test', getParentRoute: () => rootRouteImport, } as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', +const LogoutRoute = LogoutRouteImport.update({ + id: '/logout', + path: '/logout', getParentRoute: () => rootRouteImport, } as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ +const DeferredRoute = DeferredRouteImport.update({ + id: '/deferred', + path: '/deferred', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', - getParentRoute: () => PostsRoute, -} as any) -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 UsersIndexRoute = UsersIndexRouteImport.update({ @@ -85,21 +60,46 @@ const UsersIndexRoute = UsersIndexRouteImport.update({ path: '/', getParentRoute: () => UsersRoute, } as any) +const RedirectIndexRoute = RedirectIndexRouteImport.update({ + id: '/redirect/', + path: '/redirect/', + getParentRoute: () => rootRouteImport, +} as any) +const PostsIndexRoute = PostsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PostsRoute, +} as any) const UsersUserIdRoute = UsersUserIdRouteImport.update({ id: '/$userId', path: '/$userId', getParentRoute: () => UsersRoute, } as any) -const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => ApiUsersRoute, +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, +} 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, } as any) +const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => ApiUsersRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -218,32 +218,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport - parentRoute: typeof rootRouteImport - } - '/logout': { - id: '/logout' - path: '/logout' - fullPath: '/logout' - preLoaderRoute: typeof LogoutRouteImport - parentRoute: typeof rootRouteImport - } - '/navigate-test': { - id: '/navigate-test' - path: '/navigate-test' - fullPath: '/navigate-test' - preLoaderRoute: typeof NavigateTestRouteImport + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport parentRoute: typeof rootRouteImport } '/posts': { @@ -253,46 +232,32 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport + '/navigate-test': { + id: '/navigate-test' + path: '/navigate-test' + fullPath: '/navigate-test' + preLoaderRoute: typeof NavigateTestRouteImport parentRoute: typeof rootRouteImport } - '/api/users': { - id: '/api/users' - path: '/api/users' - fullPath: '/api/users' - preLoaderRoute: typeof ApiUsersRouteImport + '/logout': { + id: '/logout' + path: '/logout' + fullPath: '/logout' + preLoaderRoute: typeof LogoutRouteImport parentRoute: typeof rootRouteImport } - '/posts/': { - id: '/posts/' + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' 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 - } - '/redirect/': { - id: '/redirect/' - path: '/redirect' - fullPath: '/redirect/' - preLoaderRoute: typeof RedirectIndexRouteImport - parentRoute: typeof rootRouteImport - } - '/redirect/throw-it': { - id: '/redirect/throw-it' - path: '/redirect/throw-it' - fullPath: '/redirect/throw-it' - preLoaderRoute: typeof RedirectThrowItRouteImport + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/users/': { @@ -302,6 +267,20 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof UsersIndexRouteImport parentRoute: typeof UsersRoute } + '/redirect/': { + id: '/redirect/' + path: '/redirect' + fullPath: '/redirect/' + preLoaderRoute: typeof RedirectIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRoute + } '/users/$userId': { id: '/users/$userId' path: '/$userId' @@ -309,12 +288,26 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof UsersUserIdRouteImport parentRoute: typeof UsersRoute } - '/api/users/$id': { - id: '/api/users/$id' - path: '/$id' - fullPath: '/api/users/$id' - preLoaderRoute: typeof ApiUsersIdRouteImport - parentRoute: typeof ApiUsersRoute + '/redirect/throw-it': { + id: '/redirect/throw-it' + path: '/redirect/throw-it' + fullPath: '/redirect/throw-it' + preLoaderRoute: typeof RedirectThrowItRouteImport + parentRoute: typeof rootRouteImport + } + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRoute + } + '/api/users': { + id: '/api/users' + path: '/api/users' + fullPath: '/api/users' + preLoaderRoute: typeof ApiUsersRouteImport + parentRoute: typeof rootRouteImport } '/posts_/$postId/deep': { id: '/posts_/$postId/deep' @@ -323,6 +316,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsPostIdDeepRouteImport parentRoute: typeof rootRouteImport } + '/api/users/$id': { + id: '/api/users/$id' + path: '/$id' + fullPath: '/api/users/$id' + preLoaderRoute: typeof ApiUsersIdRouteImport + parentRoute: typeof ApiUsersRoute + } } } diff --git a/e2e/react-start/custom-basepath/src/routes/api.users.ts b/e2e/react-start/custom-basepath/src/routes/api.users.ts index 6fc8cde830..9e055549ef 100644 --- a/e2e/react-start/custom-basepath/src/routes/api.users.ts +++ b/e2e/react-start/custom-basepath/src/routes/api.users.ts @@ -3,7 +3,11 @@ import axios from 'redaxios' import type { User } from '~/utils/users' -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const Route = createFileRoute('/api/users')({ server: { diff --git a/e2e/react-start/custom-basepath/src/routes/api/users.$id.ts b/e2e/react-start/custom-basepath/src/routes/api/users.$id.ts index 81c071afb5..57682660fd 100644 --- a/e2e/react-start/custom-basepath/src/routes/api/users.$id.ts +++ b/e2e/react-start/custom-basepath/src/routes/api/users.$id.ts @@ -2,7 +2,11 @@ import axios from 'redaxios' import type { User } from '~/utils/users' import { createFileRoute } from '@tanstack/react-router' -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const Route = createFileRoute('/api/users/$id')({ server: { diff --git a/e2e/react-start/custom-basepath/src/routes/deferred.tsx b/e2e/react-start/custom-basepath/src/routes/deferred.tsx index a6bd45f8c2..9c6e3064b8 100644 --- a/e2e/react-start/custom-basepath/src/routes/deferred.tsx +++ b/e2e/react-start/custom-basepath/src/routes/deferred.tsx @@ -3,13 +3,13 @@ import { createServerFn } from '@tanstack/react-start' import { Suspense, useState } from 'react' const personServerFn = createServerFn({ method: 'GET' }) - .validator((data: { name: string }) => data) + .inputValidator((data: { name: string }) => data) .handler(({ data }) => { return { name: data.name, randomNumber: Math.floor(Math.random() * 100) } }) const slowServerFn = createServerFn({ method: 'GET' }) - .validator((data: { name: string }) => data) + .inputValidator((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/react-start/custom-basepath/src/utils/posts.tsx b/e2e/react-start/custom-basepath/src/utils/posts.tsx index d9b98a8c9c..b2d9f3edec 100644 --- a/e2e/react-start/custom-basepath/src/utils/posts.tsx +++ b/e2e/react-start/custom-basepath/src/utils/posts.tsx @@ -8,10 +8,14 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPost = createServerFn({ method: 'GET' }) - .validator((postId: string) => postId) + .inputValidator((postId: string) => postId) .handler(async ({ data: postId }) => { console.info(`Fetching post with id ${postId}...`) const post = await axios diff --git a/e2e/react-start/custom-basepath/src/utils/users.tsx b/e2e/react-start/custom-basepath/src/utils/users.tsx index 7ba645b383..46be4b1580 100644 --- a/e2e/react-start/custom-basepath/src/utils/users.tsx +++ b/e2e/react-start/custom-basepath/src/utils/users.tsx @@ -3,3 +3,7 @@ export type User = { name: string email: string } + +const PORT = process.env.VITE_SERVER_PORT || 3000 + +export const DEPLOY_URL = `http://localhost:${PORT}` diff --git a/e2e/react-start/custom-basepath/tests/setup/global.setup.ts b/e2e/react-start/custom-basepath/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-start/custom-basepath/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/react-start/custom-basepath/tests/setup/global.teardown.ts b/e2e/react-start/custom-basepath/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-start/custom-basepath/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-start/custom-basepath/tsconfig.json b/e2e/react-start/custom-basepath/tsconfig.json index 3824b148e1..d35a4b17f4 100644 --- a/e2e/react-start/custom-basepath/tsconfig.json +++ b/e2e/react-start/custom-basepath/tsconfig.json @@ -13,6 +13,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/react-start/custom-server-rsbuild/.gitignore b/e2e/react-start/custom-server-rsbuild/.gitignore deleted file mode 100644 index a79d5cf129..0000000000 --- a/e2e/react-start/custom-server-rsbuild/.gitignore +++ /dev/null @@ -1,20 +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 -/test-results/ -/playwright-report/ -/blob-report/ -/playwright/.cache/ diff --git a/e2e/react-start/custom-server-rsbuild/express-server.ts b/e2e/react-start/custom-server-rsbuild/express-server.ts deleted file mode 100644 index 68537956b4..0000000000 --- a/e2e/react-start/custom-server-rsbuild/express-server.ts +++ /dev/null @@ -1,91 +0,0 @@ -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') - -type FetchServerEntry = { - default: { fetch: (req: Request) => Promise } -} - -const app = express() - -if (DEVELOPMENT) { - // Set up rsbuild in middleware mode: - // https://rsbuild.rs/config/server/middleware-mode - const { createRsbuild, loadConfig } = await import('@rsbuild/core') - const { content: userConfig } = await loadConfig({ cwd: process.cwd() }) - - const rsbuild = await createRsbuild({ - rsbuildConfig: { - ...userConfig, - server: { - ...(userConfig.server ?? {}), - middlewareMode: true, - }, - }, - }) - - const devServer = await rsbuild.createDevServer() - - const serverEntry = - await devServer.environments.ssr.loadBundle('index') - const handler = toNodeHandler(serverEntry.default.fetch) as NodeHttp1Handler - - // Intercept server-fn URLs BEFORE rsbuild's built-in middlewares so they - // don't get swallowed by htmlCompletion/assetsMiddleware — long base64 - // function IDs in the path can look like asset routes. - app.use(async (req, res, next) => { - if (!req.url.startsWith('/_serverFn')) return next() - try { - await handler(req, res) - } catch (error) { - next(error) - } - }) - - // Rsbuild asset middlewares (JS/CSS/HMR). - app.use(devServer.middlewares) - - // Catch-all SSR for page navigations. - app.use(async (req, res, next) => { - try { - await handler(req, res) - } catch (error) { - next(error) - } - }) - - const httpServer = app.listen(PORT, async (error) => { - if (error) { - throw error - } - await devServer.afterListen() - console.log( - `E2E app: http://localhost:${(httpServer.address() as AddressInfo).port}`, - ) - }) - devServer.connectWebSocket({ server: httpServer }) -} else { - const { default: handler } = - (await import('./dist/server/index.js')) as FetchServerEntry - const nodeHandler = toNodeHandler(handler.fetch) as NodeHttp1Handler - app.use(express.static('dist/client')) - app.use(async (req, res, next) => { - try { - await nodeHandler(req, res) - } catch (error) { - next(error) - } - }) - const httpServer = app.listen(PORT, (error) => { - if (error) { - throw error - } - console.log( - `E2E app: http://localhost:${(httpServer.address() as AddressInfo).port}`, - ) - }) -} diff --git a/e2e/react-start/custom-server-rsbuild/package.json b/e2e/react-start/custom-server-rsbuild/package.json deleted file mode 100644 index 1c5b3af393..0000000000 --- a/e2e/react-start/custom-server-rsbuild/package.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "name": "tanstack-react-start-e2e-custom-server-rsbuild", - "private": true, - "sideEffects": false, - "type": "module", - "scripts": { - "dev": "cross-env NODE_ENV=development tsx express-server.ts", - "dev:e2e": "cross-env NODE_ENV=development tsx express-server.ts", - "build": "rsbuild build && tsc --noEmit", - "start": "tsx express-server.ts", - "test:e2e:dev": "cross-env MODE=dev playwright test --project=chromium", - "test:e2e:prod": "cross-env MODE=prod playwright test --project=chromium", - "test:e2e": "pnpm run test:e2e:dev && pnpm run test:e2e:prod" - }, - "dependencies": { - "@tanstack/react-router": "workspace:^", - "@tanstack/react-start": "workspace:^", - "express": "^5.2.1", - "react": "^19.0.0", - "react-dom": "^19.0.0" - }, - "devDependencies": { - "@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:^", - "@types/express": "^5.0.6", - "@types/node": "^22.10.2", - "@types/react": "^19.0.8", - "@types/react-dom": "^19.0.3", - "cross-env": "^10.0.0", - "srvx": "^1.0.0", - "tailwindcss": "^4.2.2", - "tsx": "^4.20.3", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2" - } -} diff --git a/e2e/react-start/custom-server-rsbuild/playwright.config.ts b/e2e/react-start/custom-server-rsbuild/playwright.config.ts deleted file mode 100644 index f0542500fd..0000000000 --- a/e2e/react-start/custom-server-rsbuild/playwright.config.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { defineConfig, devices } from '@playwright/test' - -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']], - use: { baseURL }, - webServer: { - command: isDev ? 'pnpm dev:e2e' : 'pnpm build && pnpm start', - wait: { stdout: /E2E app: http:\/\/localhost:(?\d+)/ }, - reuseExistingServer: false, - stdout: 'pipe', - env: { - PORT: String(PORT), - }, - }, - projects: [ - { - name: 'chromium', - use: { ...devices['Desktop Chrome'] }, - }, - ], -}) diff --git a/e2e/react-start/custom-server-rsbuild/postcss.config.mjs b/e2e/react-start/custom-server-rsbuild/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/e2e/react-start/custom-server-rsbuild/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/e2e/react-start/custom-server-rsbuild/rsbuild.config.ts b/e2e/react-start/custom-server-rsbuild/rsbuild.config.ts deleted file mode 100644 index 5f9aa96e16..0000000000 --- a/e2e/react-start/custom-server-rsbuild/rsbuild.config.ts +++ /dev/null @@ -1,65 +0,0 @@ -import path from 'node:path' -import { defineConfig } from '@rsbuild/core' -import { pluginReact } from '@rsbuild/plugin-react' -import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild' - -// Stress-test fixture for `` and the start manifest under a -// non-default client chunk layout. The combination that matters for the -// repro is: -// -// - `client.output: 'iife'` — emit the client entry as a self-executing -// script. The manifest uses plain script tags and classic script preloads; -// setting IIFE here exercises that non-module asset path. -// -// - Client `runtimeChunk: 'single'` — extracts the webpack runtime into -// its own chunk. With IIFE plain scripts, the entry can't bootstrap -// until the runtime has executed, so `` has to emit a -// `', endIndex) - const scriptCloseIndex = html.indexOf('', endIndex) - const bodyCloseIndex = html.indexOf('', scriptCloseIndex) - const htmlCloseIndex = html.indexOf('', bodyCloseIndex) - - expect(endIndex).toBeGreaterThan(-1) - expect(scriptOpenIndex).toBeGreaterThan(previousScriptCloseIndex) - expect(scriptCloseIndex).toBeGreaterThan(endIndex) - expect(payloadIndex).toBeGreaterThan(-1) - expect(payloadIndex).toBeLessThan(endIndex) - expect(html.slice(endIndex, scriptCloseIndex)).toContain(LATE_RECORD_CLOSE) - expect(scriptCloseIndex).toBeLessThan(bodyCloseIndex) - expect(bodyCloseIndex).toBeLessThan(htmlCloseIndex) -} - -async function verifyHydration( - page: Page, - { timeout = 10_000 }: { timeout?: number } = {}, -) { - const button = page.getByTestId('hydration-check-btn') - const status = page.getByTestId('hydration-status') - - await expect(button).toBeVisible() - await expect(async () => { - await button.click() - await expect(status).toHaveText('hydrated', { timeout: 100 }) - }).toPass({ timeout }) - - await expect(page.locator(STREAM_PART_SELECTOR)).toHaveCount(0) - await expect( - page.locator('script').filter({ hasText: STREAM_BOUNDARY_MARKER }), - ).toHaveCount(0) -} - -export { test } - -export const testWithHydration = test.extend({ - page: async ({ page }, use) => { - await use(page) - await verifyHydration(page) - }, -}) - -export { expect } diff --git a/e2e/streaming-ssr-fixtures/index.ts b/e2e/streaming-ssr-fixtures/index.ts deleted file mode 100644 index a70ef94459..0000000000 --- a/e2e/streaming-ssr-fixtures/index.ts +++ /dev/null @@ -1,381 +0,0 @@ -export type SourceMarker = 'server' | 'client' - -export type ServerData = { - name: string - timestamp: number - source: 'server' -} - -export type DeferredMessage = { - message: string - source: SourceMarker -} - -export type QueryType = 'sync' | 'fast-async' | 'slow-async' - -export type QueryData = { - type: QueryType - id: number - value: string - source: SourceMarker -} - -export const deferredDataMessage = 'Deferred data loaded!' -export const deferredDataDelay = 1000 -export const deferredServerDelay = 800 -export const deferredImmediateName = 'Fast User' -export const deferredSlowName = 'Slow User' -export const deferredErrorMessage = 'Error in deferred object' - -export const fastSerialStaticData = 'This is static data' -export const fastSerialSmallValue = 'small-data' - -export const syncOnlyMessage = 'Hello from sync loader!' -export const syncOnlyItems = ['item-1', 'item-2', 'item-3'] as const - -export const slowRenderDeferredMessage = 'Deferred resolved!' -export const slowRenderDeferredDelay = 50 -export const slowRenderQuickName = 'Quick data' -export const slowRenderComponents = [ - 'Slow component 1', - 'Slow component 2', - 'Slow component 3', -] as const - -export const nestedLevelDelays = [200, 400, 600] as const -export const nestedPlainDelay = 300 -export const nestedPlainMessage = 'Plain deferred resolved!' - -export const streamPromiseValue = 'promise-resolved' -export const streamPromiseDelay = 150 -export const streamChunkDelay = 200 -export const streamChunks = Array.from({ length: 5 }, (_, i) => `chunk-${i}`) - -export const routerHtmlPayloadChars = 17 * 1024 * 1024 -export const routerHtmlPayloadChar = 'x' -export const routerHtmlPayloadDelay = 100 - -export const manyPromiseItems = [ - { - key: 'immediate1', - testId: 'immediate-1', - label: 'Immediate 1', - value: 'immediate-1', - delayMs: 0, - }, - { - key: 'immediate2', - testId: 'immediate-2', - label: 'Immediate 2', - value: 'immediate-2', - delayMs: 10, - }, - { - key: 'immediate3', - testId: 'immediate-3', - label: 'Immediate 3', - value: 'immediate-3', - delayMs: 20, - }, - { - key: 'fast1', - testId: 'fast-1', - label: 'Fast 1', - value: 'fast-1', - delayMs: 50, - }, - { - key: 'fast2', - testId: 'fast-2', - label: 'Fast 2', - value: 'fast-2', - delayMs: 75, - }, - { - key: 'fast3', - testId: 'fast-3', - label: 'Fast 3', - value: 'fast-3', - delayMs: 100, - }, - { - key: 'fast4', - testId: 'fast-4', - label: 'Fast 4', - value: 'fast-4', - delayMs: 125, - }, - { - key: 'medium1', - testId: 'medium-1', - label: 'Medium 1', - value: 'medium-1', - delayMs: 150, - }, - { - key: 'medium2', - testId: 'medium-2', - label: 'Medium 2', - value: 'medium-2', - delayMs: 200, - }, - { - key: 'medium3', - testId: 'medium-3', - label: 'Medium 3', - value: 'medium-3', - delayMs: 250, - }, - { - key: 'slow1', - testId: 'slow-1', - label: 'Slow 1', - value: 'slow-1', - delayMs: 300, - }, - { - key: 'slow2', - testId: 'slow-2', - label: 'Slow 2', - value: 'slow-2', - delayMs: 400, - }, - { - key: 'slow3', - testId: 'slow-3', - label: 'Slow 3', - value: 'slow-3', - delayMs: 500, - }, - { - key: 'verySlow1', - testId: 'very-slow-1', - label: 'Very Slow 1', - value: 'very-slow-1', - delayMs: 600, - }, - { - key: 'verySlow2', - testId: 'very-slow-2', - label: 'Very Slow 2', - value: 'very-slow-2', - delayMs: 800, - }, -] as const - -export const concurrentBatchCount = 5 -export const concurrentBatchDelays = [100, 200, 300] as const - -export const queryHeavyItems = [ - { - type: 'sync', - id: 1, - value: 'sync-value-1', - delayMs: 0, - testId: 'sync-query-1', - fallback: 'Loading sync 1...', - }, - { - type: 'sync', - id: 2, - value: 'sync-value-2', - delayMs: 0, - testId: 'sync-query-2', - fallback: 'Loading sync 2...', - }, - { - type: 'sync', - id: 3, - value: 'sync-value-3', - delayMs: 0, - testId: 'sync-query-3', - fallback: 'Loading sync 3...', - }, - { - type: 'fast-async', - id: 1, - value: 'fast-async-1', - delayMs: 50, - testId: 'fast-async-query-1', - fallback: 'Loading fast 1...', - }, - { - type: 'fast-async', - id: 2, - value: 'fast-async-2', - delayMs: 75, - testId: 'fast-async-query-2', - fallback: 'Loading fast 2...', - }, - { - type: 'fast-async', - id: 3, - value: 'fast-async-3', - delayMs: 100, - testId: 'fast-async-query-3', - fallback: 'Loading fast 3...', - }, - { - type: 'slow-async', - id: 1, - value: 'slow-async-1', - delayMs: 200, - testId: 'slow-async-query-1', - fallback: 'Loading slow 1...', - }, - { - type: 'slow-async', - id: 2, - value: 'slow-async-2', - delayMs: 300, - testId: 'slow-async-query-2', - fallback: 'Loading slow 2...', - }, - { - type: 'slow-async', - id: 3, - value: 'slow-async-3', - delayMs: 400, - testId: 'slow-async-query-3', - fallback: 'Loading slow 3...', - }, -] as const - -export function sourceMarker(): SourceMarker { - return typeof window === 'undefined' ? 'server' : 'client' -} - -export function delay(ms: number): Promise { - return new Promise((resolve) => setTimeout(resolve, ms)) -} - -export function makeServerData(name: string): ServerData { - return { - name, - timestamp: Date.now(), - source: 'server', - } -} - -export function makeDeferred(value: T, delayMs: number): Promise { - return new Promise((resolve) => setTimeout(() => resolve(value), delayMs)) -} - -export function makeDeferredMessage( - message: string, - delayMs: number, -): Promise { - return makeDeferred({ message, source: sourceMarker() }, delayMs) -} - -export function makeFastSerialSmallData() { - return { - value: fastSerialSmallValue, - timestamp: Date.now(), - source: 'server' as const, - } -} - -export function makeSyncOnlyData() { - return { - message: syncOnlyMessage, - timestamp: Date.now(), - items: syncOnlyItems, - source: sourceMarker(), - } -} - -export function makeLevelData(level: number) { - return { level, timestamp: Date.now() } -} - -export function makeQueryData(item: { - type: QueryType - id: number - value: string -}): QueryData { - return { - type: item.type, - id: item.id, - value: item.value, - source: sourceMarker(), - } -} - -export function createManyPromises() { - return Object.fromEntries( - manyPromiseItems.map((item) => [ - item.key, - makeDeferred(item.value, item.delayMs), - ]), - ) as Record<(typeof manyPromiseItems)[number]['key'], Promise> -} - -export function createConcurrentPromises( - count: number, - delayMs: number, -): Array> { - const sharedPromise = delay(delayMs) - return Array.from({ length: count }, (_, i) => - sharedPromise.then(() => `concurrent-${i + 1}`), - ) -} - -export function createConcurrentLoaderData() { - const batch1 = createConcurrentPromises( - concurrentBatchCount, - concurrentBatchDelays[0], - ) - const batch2 = createConcurrentPromises( - concurrentBatchCount, - concurrentBatchDelays[1], - ) - const batch3 = createConcurrentPromises( - concurrentBatchCount, - concurrentBatchDelays[2], - ) - - return { - concurrent1_1: batch1[0], - concurrent1_2: batch1[1], - concurrent1_3: batch1[2], - concurrent1_4: batch1[3], - concurrent1_5: batch1[4], - concurrent2_1: batch2[0], - concurrent2_2: batch2[1], - concurrent2_3: batch2[2], - concurrent2_4: batch2[3], - concurrent2_5: batch2[4], - concurrent3_1: batch3[0], - concurrent3_2: batch3[1], - concurrent3_3: batch3[2], - concurrent3_4: batch3[3], - concurrent3_5: batch3[4], - } -} - -export function createStreamPromise(): Promise { - return makeDeferred(streamPromiseValue, streamPromiseDelay) -} - -export function createChunkStream(): ReadableStream { - return new ReadableStream({ - async start(controller) { - for (const chunk of streamChunks) { - await delay(streamChunkDelay) - controller.enqueue(chunk) - } - controller.close() - }, - }) -} - -export function createRouterHtmlPayload() { - return makeDeferred( - { - value: routerHtmlPayloadChar.repeat(routerHtmlPayloadChars), - source: sourceMarker(), - }, - routerHtmlPayloadDelay, - ) -} diff --git a/e2e/streaming-ssr-specs/client-navigation.ts b/e2e/streaming-ssr-specs/client-navigation.ts deleted file mode 100644 index 759f8e0282..0000000000 --- a/e2e/streaming-ssr-specs/client-navigation.ts +++ /dev/null @@ -1,372 +0,0 @@ -import { expect, test, testWithHydration } from '../streaming-ssr-assertions' - -test.describe('Client-side navigation between all routes', () => { - test.beforeEach(async ({ page }) => { - // Start from home page - await page.goto('/') - await page.waitForLoadState('networkidle') - }) - - test('home -> sync-only -> home works', async ({ page }) => { - // Navigate to sync-only - await page - .getByRole('navigation') - .getByRole('link', { name: 'Sync Only' }) - .click() - await expect(page).toHaveURL('/sync-only') - await expect(page.getByTestId('sync-message')).toBeVisible() - - // Navigate back to home - await page - .getByRole('navigation') - .getByRole('link', { name: 'Home' }) - .click() - await expect(page).toHaveURL('/') - await expect(page.getByTestId('index-title')).toBeVisible() - }) - - test('home -> deferred -> home works', async ({ page }) => { - // Navigate to deferred (use exact: true to avoid matching "Nested Deferred") - await page - .getByRole('navigation') - .getByRole('link', { name: 'Deferred', exact: true }) - .click() - await expect(page).toHaveURL('/deferred') - await expect(page.getByTestId('immediate-data')).toBeVisible() - - // Wait for deferred data - await expect(page.getByTestId('deferred-data')).toBeVisible({ - timeout: 5000, - }) - - // Navigate back to home - await page - .getByRole('navigation') - .getByRole('link', { name: 'Home' }) - .click() - await expect(page).toHaveURL('/') - }) - - test('home -> stream -> home works (no stream locking error)', async ({ - page, - }) => { - // This test specifically validates the ReadableStream locking fix - // Console errors are monitored by the fixture automatically - - // Navigate to stream - await page - .getByRole('navigation') - .getByRole('link', { name: 'Stream' }) - .click() - await expect(page).toHaveURL('/stream') - - // Wait for stream to start (at least one chunk or promise resolved) - await expect(page.getByTestId('promise-data')).toBeVisible({ - timeout: 5000, - }) - - // Navigate back without waiting for stream completion. - await page - .getByRole('navigation') - .getByRole('link', { name: 'Home' }) - .click() - await expect(page).toHaveURL('/') - }) - - test('home -> stream -> wait for completion -> home works', async ({ - page, - }) => { - // Navigate to stream - await page - .getByRole('navigation') - .getByRole('link', { name: 'Stream' }) - .click() - await expect(page).toHaveURL('/stream') - - // Wait for stream to complete - await expect(page.getByTestId('stream-complete')).toBeVisible({ - timeout: 10000, - }) - - // Navigate back to home - await page - .getByRole('navigation') - .getByRole('link', { name: 'Home' }) - .click() - await expect(page).toHaveURL('/') - await expect(page.getByTestId('index-title')).toBeVisible() - }) - - test('home -> stream -> home -> stream again works (fresh stream each time)', async ({ - page, - }) => { - // Console errors are monitored by the fixture automatically - - // First navigation to stream - await page - .getByRole('navigation') - .getByRole('link', { name: 'Stream' }) - .click() - await expect(page).toHaveURL('/stream') - await expect(page.getByTestId('promise-data')).toBeVisible({ - timeout: 5000, - }) - - // Navigate back to home - await page - .getByRole('navigation') - .getByRole('link', { name: 'Home' }) - .click() - await expect(page).toHaveURL('/') - - // Second navigation to stream - should get fresh stream without errors - await page - .getByRole('navigation') - .getByRole('link', { name: 'Stream' }) - .click() - await expect(page).toHaveURL('/stream') - - // Wait for stream to complete - await expect(page.getByTestId('stream-complete')).toBeVisible({ - timeout: 10000, - }) - - // Verify all chunks are present - await expect(page.getByTestId('stream-chunk-0')).toBeVisible() - await expect(page.getByTestId('stream-chunk-4')).toBeVisible() - }) - - test('home -> fast-serial -> home works', async ({ page }) => { - await page - .getByRole('navigation') - .getByRole('link', { name: 'Fast Serial' }) - .click() - await expect(page).toHaveURL('/fast-serial') - await expect(page.getByTestId('server-data')).toBeVisible() - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Home' }) - .click() - await expect(page).toHaveURL('/') - }) - - test('home -> slow-render -> home works', async ({ page }) => { - await page - .getByRole('navigation') - .getByRole('link', { name: 'Slow Render' }) - .click() - await expect(page).toHaveURL('/slow-render') - await expect(page.getByTestId('quick-data')).toBeVisible() - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Home' }) - .click() - await expect(page).toHaveURL('/') - }) - - test('home -> nested-deferred -> home works', async ({ page }) => { - await page - .getByRole('navigation') - .getByRole('link', { name: 'Nested Deferred' }) - .click() - await expect(page).toHaveURL('/nested-deferred') - - // Wait for all levels to load - await expect(page.getByTestId('level3-data')).toBeVisible({ timeout: 5000 }) - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Home' }) - .click() - await expect(page).toHaveURL('/') - }) - - test('navigation without waiting for route data works', async ({ page }) => { - // Console errors are monitored by the fixture automatically - - // Change routes as soon as each URL updates, without waiting for route data. - await page - .getByRole('navigation') - .getByRole('link', { name: 'Sync Only' }) - .click() - await expect(page).toHaveURL('/sync-only') - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Deferred', exact: true }) - .click() - await expect(page).toHaveURL('/deferred') - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Stream' }) - .click() - await expect(page).toHaveURL('/stream') - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Fast Serial' }) - .click() - await expect(page).toHaveURL('/fast-serial') - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Slow Render' }) - .click() - await expect(page).toHaveURL('/slow-render') - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Nested Deferred' }) - .click() - await expect(page).toHaveURL('/nested-deferred') - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Home' }) - .click() - await expect(page).toHaveURL('/') - }) -}) - -test.describe('Direct navigation followed by client navigation', () => { - test('direct to stream -> client nav to deferred works', async ({ page }) => { - // Direct navigation to stream - await page.goto('/stream') - await expect(page.getByTestId('promise-data')).toBeVisible({ - timeout: 5000, - }) - - // Client navigation to deferred (use exact: true) - await page - .getByRole('navigation') - .getByRole('link', { name: 'Deferred', exact: true }) - .click() - await expect(page).toHaveURL('/deferred') - await expect(page.getByTestId('immediate-data')).toBeVisible() - }) - - test('direct to deferred -> client nav to stream works', async ({ page }) => { - // Console errors are monitored by the fixture automatically - - // Direct navigation to deferred - await page.goto('/deferred') - await expect(page.getByTestId('immediate-data')).toBeVisible() - - // Client navigation to stream - await page - .getByRole('navigation') - .getByRole('link', { name: 'Stream' }) - .click() - await expect(page).toHaveURL('/stream') - await expect(page.getByTestId('stream-complete')).toBeVisible({ - timeout: 10000, - }) - }) - - test('direct to sync-only -> client nav to all routes works', async ({ - page, - }) => { - await page.goto('/sync-only') - await expect(page.getByTestId('sync-message')).toBeVisible() - - // Navigate through all routes - await page - .getByRole('navigation') - .getByRole('link', { name: 'Deferred', exact: true }) - .click() - await expect(page).toHaveURL('/deferred') - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Stream' }) - .click() - await expect(page).toHaveURL('/stream') - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Fast Serial' }) - .click() - await expect(page).toHaveURL('/fast-serial') - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Home' }) - .click() - await expect(page).toHaveURL('/') - }) -}) - -testWithHydration.describe('Hydration after client navigation', () => { - testWithHydration( - 'interactive elements work after navigating to deferred', - async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Deferred', exact: true }) - .click() - await expect(page).toHaveURL('/deferred') - - // Wait for the page to be fully loaded - await expect(page.getByTestId('immediate-data')).toBeVisible() - }, - ) - - testWithHydration( - 'interactive elements work after navigating to fast-serial', - async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Fast Serial' }) - .click() - await expect(page).toHaveURL('/fast-serial') - - // Wait for page to load - await expect(page.getByTestId('server-data')).toBeVisible() - }, - ) - - testWithHydration( - 'interactive elements work after navigating to nested-deferred', - async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Nested Deferred' }) - .click() - await expect(page).toHaveURL('/nested-deferred') - - // Wait for page to load - await expect(page.getByTestId('plain-deferred')).toBeVisible({ - timeout: 5000, - }) - }, - ) - - testWithHydration( - 'interactive elements work after navigating to slow-render', - async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Slow Render' }) - .click() - await expect(page).toHaveURL('/slow-render') - - // Wait for page to load (slow-render has blocking loops) - await expect(page.getByTestId('quick-data')).toBeVisible() - }, - ) -}) diff --git a/e2e/streaming-ssr-specs/concurrent.ts b/e2e/streaming-ssr-specs/concurrent.ts deleted file mode 100644 index ef14f80367..0000000000 --- a/e2e/streaming-ssr-specs/concurrent.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { expect, test, testWithHydration } from '../streaming-ssr-assertions' - -test.describe('Concurrent promise resolution (15 promises in 3 batches)', () => { - test('all concurrent promises resolve correctly', async ({ page }) => { - await page.goto('/concurrent') - - // Batch 1 (5 promises at 100ms) - await expect(page.getByTestId('concurrent-1-1')).toContainText( - 'concurrent-1', - { timeout: 5000 }, - ) - await expect(page.getByTestId('concurrent-1-2')).toContainText( - 'concurrent-2', - { timeout: 5000 }, - ) - await expect(page.getByTestId('concurrent-1-3')).toContainText( - 'concurrent-3', - { timeout: 5000 }, - ) - await expect(page.getByTestId('concurrent-1-4')).toContainText( - 'concurrent-4', - { timeout: 5000 }, - ) - await expect(page.getByTestId('concurrent-1-5')).toContainText( - 'concurrent-5', - { timeout: 5000 }, - ) - - // Batch 2 (5 promises at 200ms) - await expect(page.getByTestId('concurrent-2-1')).toContainText( - 'concurrent-1', - { timeout: 5000 }, - ) - await expect(page.getByTestId('concurrent-2-2')).toContainText( - 'concurrent-2', - { timeout: 5000 }, - ) - await expect(page.getByTestId('concurrent-2-3')).toContainText( - 'concurrent-3', - { timeout: 5000 }, - ) - await expect(page.getByTestId('concurrent-2-4')).toContainText( - 'concurrent-4', - { timeout: 5000 }, - ) - await expect(page.getByTestId('concurrent-2-5')).toContainText( - 'concurrent-5', - { timeout: 5000 }, - ) - - // Batch 3 (5 promises at 300ms) - await expect(page.getByTestId('concurrent-3-1')).toContainText( - 'concurrent-1', - { timeout: 5000 }, - ) - await expect(page.getByTestId('concurrent-3-2')).toContainText( - 'concurrent-2', - { timeout: 5000 }, - ) - await expect(page.getByTestId('concurrent-3-3')).toContainText( - 'concurrent-3', - { timeout: 5000 }, - ) - await expect(page.getByTestId('concurrent-3-4')).toContainText( - 'concurrent-4', - { timeout: 5000 }, - ) - await expect(page.getByTestId('concurrent-3-5')).toContainText( - 'concurrent-5', - { timeout: 5000 }, - ) - }) - - testWithHydration( - 'hydration works with concurrent resolutions', - async ({ page }) => { - await page.goto('/concurrent') - await page.waitForLoadState('networkidle') - - // Wait for all batches - await expect(page.getByTestId('concurrent-3-5')).toBeVisible({ - timeout: 5000, - }) - }, - ) -}) diff --git a/e2e/streaming-ssr-specs/deferred-rejection.ts b/e2e/streaming-ssr-specs/deferred-rejection.ts deleted file mode 100644 index 3e944b1c0c..0000000000 --- a/e2e/streaming-ssr-specs/deferred-rejection.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { expect, test } from '../streaming-ssr-assertions' - -test.use({ - whitelistErrors: ['Error in deferred object'], -}) - -test('rejected deferred Await renders the route error boundary without killing SSR', async ({ - page, -}) => { - await page.goto('/deferred-rejection') - - await expect(page.getByTestId('deferred-error-boundary')).toContainText( - 'Error in deferred object', - { timeout: 5000 }, - ) - - await page.goto('/sync-only') - await expect(page.getByTestId('sync-message')).toContainText( - 'Hello from sync loader!', - ) -}) diff --git a/e2e/streaming-ssr-specs/deferred.ts b/e2e/streaming-ssr-specs/deferred.ts deleted file mode 100644 index abece0b43e..0000000000 --- a/e2e/streaming-ssr-specs/deferred.ts +++ /dev/null @@ -1,113 +0,0 @@ -import { - expect, - expectDeferredRouteResponseOrder, - test, - testWithHydration, -} from '../streaming-ssr-assertions' - -test.describe('Deferred data streaming', () => { - test('finishes the router stream after renderer output', async ({ - baseURL, - }) => { - await expectDeferredRouteResponseOrder(baseURL) - }) - - test('renders immediate and deferred server data', async ({ page }) => { - await page.goto('/deferred') - - // Immediate loader data is rendered. - await expect(page.getByTestId('immediate-data')).toBeVisible() - await expect(page.getByTestId('immediate-data')).toContainText( - 'Immediate: Fast User', - ) - - // Verify immediate data came from server - await expect(page.getByTestId('immediate-source')).toContainText( - 'Immediate source: server', - ) - await expect(page.getByTestId('loader-source')).toContainText( - 'Loader source: server', - ) - - // Deferred data should eventually appear with server source - await expect(page.getByTestId('deferred-data')).toContainText( - 'Deferred data loaded!', - { timeout: 5000 }, - ) - await expect(page.getByTestId('deferred-data')).toContainText( - 'source: server', - { timeout: 5000 }, - ) - await expect(page.getByTestId('deferred-server-data')).toContainText( - 'Server: Slow User', - { timeout: 5000 }, - ) - await expect(page.getByTestId('deferred-server-data')).toContainText( - 'source: server', - { timeout: 5000 }, - ) - }) - - testWithHydration( - 'hydration works - interactive elements respond', - async ({ page }) => { - await page.goto('/deferred') - await page.waitForLoadState('networkidle') - - // Wait for all deferred content to load - await expect(page.getByTestId('deferred-data')).toBeVisible({ - timeout: 5000, - }) - - // Verify all data came from server after hydration - await expect(page.getByTestId('loader-source')).toContainText( - 'Loader source: server', - ) - await expect(page.getByTestId('deferred-data')).toContainText( - 'source: server', - ) - }, - ) - - test('client-side navigation to deferred route works', async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - - // Navigate via client-side routing using nav link - await page.getByRole('link', { name: 'Deferred' }).first().click() - await expect(page).toHaveURL('/deferred') - - // Data should load - await expect(page.getByTestId('immediate-data')).toContainText('Fast User') - await expect(page.getByTestId('deferred-data')).toContainText( - 'Deferred data loaded!', - { timeout: 5000 }, - ) - }) - - test('all data sources are server', async ({ page }) => { - await page.goto('/deferred') - - // Wait for all deferred content - await expect(page.getByTestId('deferred-data')).toBeVisible({ - timeout: 5000, - }) - await expect(page.getByTestId('deferred-server-data')).toBeVisible({ - timeout: 5000, - }) - - // Count all elements showing 'server' source - should be 4: - // 1. immediate-source - // 2. loader-source - // 3. deferred-data (contains "source: server") - // 4. deferred-server-data (contains "source: server") - await expect(page.getByTestId('immediate-source')).toContainText('server') - await expect(page.getByTestId('loader-source')).toContainText('server') - await expect(page.getByTestId('deferred-data')).toContainText( - 'source: server', - ) - await expect(page.getByTestId('deferred-server-data')).toContainText( - 'source: server', - ) - }) -}) diff --git a/e2e/streaming-ssr-specs/fast-serial.ts b/e2e/streaming-ssr-specs/fast-serial.ts deleted file mode 100644 index 03201f0a55..0000000000 --- a/e2e/streaming-ssr-specs/fast-serial.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { - expect, - expectRouterHydrationMarkers, - test, - testWithHydration, -} from '../streaming-ssr-assertions' - -test.describe('Fast serialization (serialization completes before render)', () => { - test('initial HTML contains router bootstrap + barrier', async ({ page }) => { - let responseHtml = '' - await page.route('/fast-serial', async (route) => { - const response = await route.fetch() - responseHtml = await response.text() - await route.fulfill({ response }) - }) - - await page.goto('/fast-serial') - await expect(page.getByTestId('server-data')).toBeVisible() - - expectRouterHydrationMarkers(responseHtml) - }) - - test('renders all server data', async ({ page }) => { - await page.goto('/fast-serial') - await page.waitForLoadState('networkidle') - - // All data should be visible - await expect(page.getByTestId('server-data')).toContainText('small-data') - await expect(page.getByTestId('static-data')).toContainText( - 'This is static data', - ) - await expect(page.getByTestId('loader-timestamp')).toBeVisible() - - // Verify the loader and server function ran during SSR. - await expect(page.getByTestId('loader-source')).toContainText( - 'Loader source: server', - ) - await expect(page.getByTestId('server-fn-source')).toContainText( - 'Server function source: server', - ) - }) - - testWithHydration('hydration works correctly', async ({ page }) => { - await page.goto('/fast-serial') - await page.waitForLoadState('networkidle') - - // Verify data came from server after hydration - await expect(page.getByTestId('loader-source')).toContainText( - 'Loader source: server', - ) - }) - - test('direct navigation renders correctly', async ({ page }) => { - // Direct navigation (SSR) - await page.goto('/fast-serial') - - // Should render without errors and show server source - await expect(page.getByTestId('server-data')).toBeVisible() - await expect(page.getByTestId('loader-source')).toContainText( - 'Loader source: server', - ) - }) - - test('client-side navigation works', async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - - // Navigate via nav link - await page.getByRole('link', { name: 'Fast Serial' }).first().click() - await expect(page).toHaveURL('/fast-serial') - - await expect(page.getByTestId('server-data')).toContainText('small-data') - }) -}) diff --git a/e2e/streaming-ssr-specs/home.ts b/e2e/streaming-ssr-specs/home.ts deleted file mode 100644 index d85e19bfa7..0000000000 --- a/e2e/streaming-ssr-specs/home.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { expect, test, testWithHydration } from '../streaming-ssr-assertions' - -test.describe('Home page', () => { - testWithHydration( - 'renders index page with all navigation links', - async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - - await expect(page.getByTestId('index-title')).toContainText( - 'Streaming SSR Test Scenarios', - ) - // Check links exist (they're in the nav and the body) - await expect( - page.getByRole('link', { name: 'Deferred' }).first(), - ).toBeVisible() - await expect( - page.getByRole('link', { name: 'Stream' }).first(), - ).toBeVisible() - }, - ) - - testWithHydration( - 'navigation from home to routes works', - async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - - // Use the link in the content (not nav) - await page.getByTestId('link-deferred').click() - await expect(page).toHaveURL('/deferred') - }, - ) -}) diff --git a/e2e/streaming-ssr-specs/many-promises.ts b/e2e/streaming-ssr-specs/many-promises.ts deleted file mode 100644 index 768859c7e4..0000000000 --- a/e2e/streaming-ssr-specs/many-promises.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { expect, test, testWithHydration } from '../streaming-ssr-assertions' - -test.describe('Many promises streaming (15 deferred)', () => { - test('all 15 promises eventually resolve', async ({ page }) => { - await page.goto('/many-promises') - - // Immediate group (0-20ms) - await expect(page.getByTestId('immediate-1')).toContainText('immediate-1', { - timeout: 5000, - }) - await expect(page.getByTestId('immediate-2')).toContainText('immediate-2', { - timeout: 5000, - }) - await expect(page.getByTestId('immediate-3')).toContainText('immediate-3', { - timeout: 5000, - }) - - // Fast group (50-125ms) - await expect(page.getByTestId('fast-1')).toContainText('fast-1', { - timeout: 5000, - }) - await expect(page.getByTestId('fast-2')).toContainText('fast-2', { - timeout: 5000, - }) - await expect(page.getByTestId('fast-3')).toContainText('fast-3', { - timeout: 5000, - }) - await expect(page.getByTestId('fast-4')).toContainText('fast-4', { - timeout: 5000, - }) - - // Medium group (150-250ms) - await expect(page.getByTestId('medium-1')).toContainText('medium-1', { - timeout: 5000, - }) - await expect(page.getByTestId('medium-2')).toContainText('medium-2', { - timeout: 5000, - }) - await expect(page.getByTestId('medium-3')).toContainText('medium-3', { - timeout: 5000, - }) - - // Slow group (300-500ms) - await expect(page.getByTestId('slow-1')).toContainText('slow-1', { - timeout: 5000, - }) - await expect(page.getByTestId('slow-2')).toContainText('slow-2', { - timeout: 5000, - }) - await expect(page.getByTestId('slow-3')).toContainText('slow-3', { - timeout: 5000, - }) - - // Very slow group (600-800ms) - await expect(page.getByTestId('very-slow-1')).toContainText('very-slow-1', { - timeout: 5000, - }) - await expect(page.getByTestId('very-slow-2')).toContainText('very-slow-2', { - timeout: 5000, - }) - }) - - testWithHydration('hydration works with many promises', async ({ page }) => { - await page.goto('/many-promises') - await page.waitForLoadState('networkidle') - - // Wait for all promises to resolve - await expect(page.getByTestId('very-slow-2')).toBeVisible({ timeout: 5000 }) - }) - - test('client-side navigation works', async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - - // Navigate via nav link - await page.getByRole('link', { name: 'Many Promises' }).click() - await expect(page).toHaveURL('/many-promises') - - // All promises should eventually resolve - await expect(page.getByTestId('very-slow-2')).toBeVisible({ timeout: 5000 }) - }) -}) diff --git a/e2e/streaming-ssr-specs/nested-deferred.ts b/e2e/streaming-ssr-specs/nested-deferred.ts deleted file mode 100644 index 0146a23162..0000000000 --- a/e2e/streaming-ssr-specs/nested-deferred.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { expect, test, testWithHydration } from '../streaming-ssr-assertions' - -test.describe('Nested deferred (multiple levels of deferred data)', () => { - test('all levels of deferred data eventually resolve', async ({ page }) => { - await page.goto('/nested-deferred') - - // All deferred values should eventually resolve. - await expect(page.getByTestId('plain-deferred')).toContainText( - 'Plain deferred resolved!', - { timeout: 5000 }, - ) - - await expect(page.getByTestId('level1-data')).toContainText('Level 1:', { - timeout: 5000, - }) - - await expect(page.getByTestId('level2-data')).toContainText('Level 2:', { - timeout: 5000, - }) - - await expect(page.getByTestId('level3-data')).toContainText('Level 3:', { - timeout: 5000, - }) - }) - - testWithHydration( - 'hydration works with nested deferred', - async ({ page }) => { - await page.goto('/nested-deferred') - await page.waitForLoadState('networkidle') - - // Wait for all data - await expect(page.getByTestId('level3-data')).toBeVisible({ - timeout: 10000, - }) - }, - ) - - test('client-side navigation works', async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - - // Navigate via nav link - await page.getByRole('link', { name: 'Nested Deferred' }).first().click() - await expect(page).toHaveURL('/nested-deferred') - - // All levels should eventually render - await expect(page.getByTestId('level3-data')).toBeVisible({ - timeout: 10000, - }) - }) -}) diff --git a/e2e/streaming-ssr-specs/preview-streaming.ts b/e2e/streaming-ssr-specs/preview-streaming.ts deleted file mode 100644 index 5087dff730..0000000000 --- a/e2e/streaming-ssr-specs/preview-streaming.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { - expectDeferredRouteResponseOrder, - test, -} from '../streaming-ssr-assertions' - -test.skip( - process.env.MODE !== 'preview', - 'Only runs against vite preview: pnpm test:e2e:preview', -) - -test('vite preview preserves deferred HTML order', async ({ baseURL }) => { - await expectDeferredRouteResponseOrder(baseURL) -}) diff --git a/e2e/streaming-ssr-specs/query-heavy.ts b/e2e/streaming-ssr-specs/query-heavy.ts deleted file mode 100644 index b33a64f366..0000000000 --- a/e2e/streaming-ssr-specs/query-heavy.ts +++ /dev/null @@ -1,142 +0,0 @@ -import { - expect, - expectQueryHeavyRouteStreamOrder, - test, - testWithHydration, -} from '../streaming-ssr-assertions' - -test.describe('Query heavy route (9 queries)', () => { - test('emits the complete router stream before document closes', async ({ - baseURL, - }) => { - await expectQueryHeavyRouteStreamOrder(baseURL) - }) - - test('all queries resolve with server data', async ({ page }) => { - await page.goto('/query-heavy') - - // Sync queries should show server source - await expect(page.getByTestId('sync-query-1')).toContainText( - 'source: server', - { timeout: 5000 }, - ) - await expect(page.getByTestId('sync-query-2')).toContainText( - 'source: server', - { timeout: 5000 }, - ) - await expect(page.getByTestId('sync-query-3')).toContainText( - 'source: server', - { timeout: 5000 }, - ) - - // Fast async queries should show server source - await expect(page.getByTestId('fast-async-query-1')).toContainText( - 'source: server', - { timeout: 5000 }, - ) - await expect(page.getByTestId('fast-async-query-2')).toContainText( - 'source: server', - { timeout: 5000 }, - ) - await expect(page.getByTestId('fast-async-query-3')).toContainText( - 'source: server', - { timeout: 5000 }, - ) - - // Slow async queries should show server source - await expect(page.getByTestId('slow-async-query-1')).toContainText( - 'source: server', - { timeout: 5000 }, - ) - await expect(page.getByTestId('slow-async-query-2')).toContainText( - 'source: server', - { timeout: 5000 }, - ) - await expect(page.getByTestId('slow-async-query-3')).toContainText( - 'source: server', - { timeout: 5000 }, - ) - }) - - test('sync queries have correct values', async ({ page }) => { - await page.goto('/query-heavy') - - await expect(page.getByTestId('sync-query-1')).toContainText('sync-value-1') - await expect(page.getByTestId('sync-query-2')).toContainText('sync-value-2') - await expect(page.getByTestId('sync-query-3')).toContainText('sync-value-3') - }) - - test('async queries have correct values', async ({ page }) => { - await page.goto('/query-heavy') - - await expect(page.getByTestId('fast-async-query-1')).toContainText( - 'fast-async-1', - { timeout: 5000 }, - ) - await expect(page.getByTestId('fast-async-query-2')).toContainText( - 'fast-async-2', - { timeout: 5000 }, - ) - await expect(page.getByTestId('fast-async-query-3')).toContainText( - 'fast-async-3', - { timeout: 5000 }, - ) - - await expect(page.getByTestId('slow-async-query-1')).toContainText( - 'slow-async-1', - { timeout: 5000 }, - ) - await expect(page.getByTestId('slow-async-query-2')).toContainText( - 'slow-async-2', - { timeout: 5000 }, - ) - await expect(page.getByTestId('slow-async-query-3')).toContainText( - 'slow-async-3', - { timeout: 5000 }, - ) - }) - - testWithHydration('hydration works with many queries', async ({ page }) => { - await page.goto('/query-heavy') - await page.waitForLoadState('networkidle') - - // Wait for all queries to resolve - await expect(page.getByTestId('slow-async-query-3')).toBeVisible({ - timeout: 5000, - }) - }) - - test('client-side navigation works', async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - - // Navigate via nav link - await page.getByRole('link', { name: 'Query Heavy' }).click() - await expect(page).toHaveURL('/query-heavy') - - // All queries should eventually resolve (on client) - await expect(page.getByTestId('slow-async-query-3')).toBeVisible({ - timeout: 5000, - }) - }) - - test('server query data hydrates without client refetch', async ({ - page, - }) => { - // If hydration missed the server data, these queries would re-execute on - // the client and show "client" as their source. - await page.goto('/query-heavy') - - // Wait for all queries - await expect(page.getByTestId('slow-async-query-3')).toBeVisible({ - timeout: 5000, - }) - - // Verify that all server results hydrated without a client refetch. - const serverSourceCount = await page - .locator('[data-testid*="query-"]') - .filter({ hasText: 'source: server' }) - .count() - expect(serverSourceCount).toBe(9) - }) -}) diff --git a/e2e/streaming-ssr-specs/slow-render.ts b/e2e/streaming-ssr-specs/slow-render.ts deleted file mode 100644 index 117559701e..0000000000 --- a/e2e/streaming-ssr-specs/slow-render.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { expect, test, testWithHydration } from '../streaming-ssr-assertions' - -test.describe('Slow render (render takes longer than serialization)', () => { - test('all data eventually renders with server source', async ({ page }) => { - await page.goto('/slow-render') - await page.waitForLoadState('networkidle') - - // Quick data should be available with server source - await expect(page.getByTestId('quick-data')).toContainText('Quick:') - await expect(page.getByTestId('quick-source')).toContainText( - 'Quick data source: server', - ) - await expect(page.getByTestId('loader-source')).toContainText( - 'Loader source: server', - ) - - // Deferred data should resolve with server source - await expect(page.getByTestId('deferred-resolved')).toContainText( - 'Deferred resolved!', - { timeout: 5000 }, - ) - await expect(page.getByTestId('deferred-resolved')).toContainText( - 'source: server', - { timeout: 5000 }, - ) - - // Slow components should have rendered - await expect(page.getByTestId('slow-component-1')).toBeVisible() - await expect(page.getByTestId('slow-component-2')).toBeVisible() - await expect(page.getByTestId('slow-component-3')).toBeVisible() - }) - - testWithHydration('hydration works after slow render', async ({ page }) => { - await page.goto('/slow-render') - await page.waitForLoadState('networkidle') - - // Wait for content and verify server source - await expect(page.getByTestId('slow-component-1')).toBeVisible() - await expect(page.getByTestId('loader-source')).toContainText( - 'Loader source: server', - ) - }) - - test('client-side navigation works', async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - - // Navigate via nav link - await page.getByRole('link', { name: 'Slow Render' }).first().click() - await expect(page).toHaveURL('/slow-render') - - await expect(page.getByTestId('quick-data')).toBeVisible({ timeout: 10000 }) - }) - - test('all data sources are server', async ({ page }) => { - await page.goto('/slow-render') - await page.waitForLoadState('networkidle') - - // Wait for deferred content - await expect(page.getByTestId('deferred-resolved')).toBeVisible({ - timeout: 5000, - }) - - // Verify all sources are server - await expect(page.getByTestId('quick-source')).toContainText('server') - await expect(page.getByTestId('loader-source')).toContainText('server') - await expect(page.getByTestId('deferred-resolved')).toContainText( - 'source: server', - ) - }) -}) diff --git a/e2e/streaming-ssr-specs/stream.ts b/e2e/streaming-ssr-specs/stream.ts deleted file mode 100644 index ee61f170de..0000000000 --- a/e2e/streaming-ssr-specs/stream.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { expect, test, testWithHydration } from '../streaming-ssr-assertions' - -const expectedStreamChunks = [ - 'chunk-0', - 'chunk-1', - 'chunk-2', - 'chunk-3', - 'chunk-4', -] - -test.describe('ReadableStream deserialization', () => { - testWithHydration('promise data deserializes correctly', async ({ page }) => { - await page.goto('/stream') - - await expect(page.getByTestId('promise-data')).toContainText( - 'promise-resolved', - { timeout: 5000 }, - ) - }) - - testWithHydration( - 'stream chunks deserialize in source order', - async ({ page }) => { - await page.goto('/stream') - - await expect(page.getByTestId('stream-complete')).toBeVisible({ - timeout: 10000, - }) - - const chunks = page - .getByTestId('stream-data') - .locator('[data-testid^="stream-chunk-"]') - await expect(chunks).toHaveText(expectedStreamChunks) - - // This browser assertion covers deserialization and source order. The - // raw `/deferred` assertion covers server-response and router ordering. - }, - ) - - testWithHydration( - 'client-side navigation to stream route works', - async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - - // Navigate via nav link - await page.getByRole('link', { name: 'Stream' }).first().click() - await expect(page).toHaveURL('/stream') - - await expect(page.getByTestId('stream-complete')).toBeVisible({ - timeout: 10000, - }) - }, - ) -}) diff --git a/e2e/streaming-ssr-specs/sync-only.ts b/e2e/streaming-ssr-specs/sync-only.ts deleted file mode 100644 index 9850265109..0000000000 --- a/e2e/streaming-ssr-specs/sync-only.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { - expect, - expectRouterHydrationMarkers, - test, - testWithHydration, -} from '../streaming-ssr-assertions' - -/** - * Tests for synchronous serialization - no deferred data, no streaming. - * This is the most common case where all loader data is immediately available. - * The hydration scripts should be included in the initial HTML response. - */ - -test('Sync-only route renders with loader data', async ({ page }) => { - await page.goto('/sync-only') - - // Verify the page content is rendered - await expect(page.getByTestId('sync-title')).toContainText( - 'Synchronous Serialization Test', - ) - await expect(page.getByTestId('sync-message')).toContainText( - 'Hello from sync loader!', - ) - - // Verify loader data items are rendered - await expect(page.getByTestId('sync-item-item-1')).toBeVisible() - await expect(page.getByTestId('sync-item-item-2')).toBeVisible() - await expect(page.getByTestId('sync-item-item-3')).toBeVisible() - - // Verify the loader ran during SSR. - await expect(page.getByTestId('sync-source')).toContainText('Source: server') -}) - -testWithHydration('Sync-only route hydrates correctly', async ({ page }) => { - await page.goto('/sync-only') - - // Verify client-side navigation works (proves hydration succeeded) - await page.getByRole('navigation').getByRole('link', { name: 'Home' }).click() - await expect(page.getByTestId('index-title')).toBeVisible() - - // Navigate back to sync-only via client-side navigation (use nav link to be specific) - await page - .getByRole('navigation') - .getByRole('link', { name: 'Sync Only' }) - .click() - await expect(page.getByTestId('sync-title')).toBeVisible() -}) - -test('Sync-only route has bootstrap scripts in initial HTML', async ({ - page, -}) => { - // Intercept the response to check the raw HTML - let responseHtml = '' - await page.route('/sync-only', async (route) => { - const response = await route.fetch() - responseHtml = await response.text() - await route.fulfill({ response }) - }) - - await page.goto('/sync-only') - - // Wait for page to load - await expect(page.getByTestId('sync-title')).toBeVisible() - - // Bootstrap, end record, and the boundary rendered by . - expectRouterHydrationMarkers(responseHtml) -}) - -test('Navigating to sync-only from home page', async ({ page }) => { - await page.goto('/') - - await page.getByTestId('link-sync-only').click() - - await expect(page.getByTestId('sync-title')).toContainText( - 'Synchronous Serialization Test', - ) - await expect(page.getByTestId('sync-message')).toContainText( - 'Hello from sync loader!', - ) -}) diff --git a/e2e/vue-router/basepath-file-based/package.json b/e2e/vue-router/basepath-file-based/package.json index 3af9176e83..a30c7fa6ec 100644 --- a/e2e/vue-router/basepath-file-based/package.json +++ b/e2e/vue-router/basepath-file-based/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -17,17 +17,17 @@ "@tanstack/vue-query-devtools": "^6.1.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "catalog:", + "redaxios": "^0.5.1", "tailwindcss": "^4.2.2", "vue": "^3.5.16" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", "typescript": "~5.8.3", - "vite": "^8.0.14", - "vue-tsc": "^3.3.8" + "vite": "^8.0.0", + "vue-tsc": "^3.1.5" } } diff --git a/e2e/vue-router/basepath-file-based/playwright.config.ts b/e2e/vue-router/basepath-file-based/playwright.config.ts index 4eead86444..6069bbe59f 100644 --- a/e2e/vue-router/basepath-file-based/playwright.config.ts +++ b/e2e/vue-router/basepath-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/basepath-file-based/src/routeTree.gen.ts b/e2e/vue-router/basepath-file-based/src/routeTree.gen.ts index 75b8119285..82b561baf1 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 IndexRouteImport } from './routes/index' import { Route as AboutRouteImport } from './routes/about' +import { Route as IndexRouteImport } from './routes/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const AboutRoute = AboutRouteImport.update({ id: '/about', path: '/about', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/about': { id: '/about' path: '/about' @@ -65,6 +58,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof AboutRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + 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 new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/basepath-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basepath-file-based/tests/setup/global.teardown.ts b/e2e/vue-router/basepath-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/basepath-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic-esbuild-file-based/package.json b/e2e/vue-router/basic-esbuild-file-based/package.json index a51cf9149c..936bb1eb6c 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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; 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": "catalog:", + "redaxios": "^0.5.1", "vue": "^3.5.16", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { "@eslint/js": "^9.36.0", - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", "@typescript-eslint/eslint-plugin": "^8.44.1", "@typescript-eslint/parser": "^8.44.1", "esbuild": "^0.27.4", "esbuild-plugin-vue3": "^0.5.1", "eslint-plugin-vue": "^9.33.0", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", + "typescript": "^5.8.3", "vue-eslint-parser": "^9.4.3", - "vue-tsc": "^3.3.8" + "vue-tsc": "^3.1.5" } } diff --git a/e2e/vue-router/basic-esbuild-file-based/playwright.config.ts b/e2e/vue-router/basic-esbuild-file-based/playwright.config.ts index 9d9c8d49a3..836ea41bd8 100644 --- a/e2e/vue-router/basic-esbuild-file-based/playwright.config.ts +++ b/e2e/vue-router/basic-esbuild-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic-esbuild-file-based/src/esbuild.config.js b/e2e/vue-router/basic-esbuild-file-based/src/esbuild.config.js index 16f6fbca44..c4aba8798e 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/esbuild.config.js +++ b/e2e/vue-router/basic-esbuild-file-based/src/esbuild.config.js @@ -9,6 +9,7 @@ export default { }), tanstackRouter({ target: 'vue', + autoCodeSplitting: true, }), ], } diff --git a/e2e/vue-router/basic-esbuild-file-based/src/esbuild.run.js b/e2e/vue-router/basic-esbuild-file-based/src/esbuild.run.js index 0ab294f2bf..19e882c1a9 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/esbuild.run.js +++ b/e2e/vue-router/basic-esbuild-file-based/src/esbuild.run.js @@ -1,7 +1,8 @@ -import http from 'node:http' -import { createReadStream, promises as fs } from 'node:fs' -import path from 'node:path' import * as esbuild from 'esbuild' +import http from 'node:http' +import { createReadStream } from 'node:fs' +import { promises as fs } from 'node:fs' +import path from 'node:path' import esbuildConfig from './esbuild.config.js' const args = process.argv.slice(2) @@ -17,7 +18,7 @@ function getPort() { const fromArg = getArgValue('--port') const fromEnv = process.env.VITE_SERVER_PORT const port = Number(fromArg ?? fromEnv ?? 5601) - if (!Number.isFinite(port) || port < 0) { + if (!Number.isFinite(port) || port <= 0) { throw new Error(`Invalid port: ${String(fromArg ?? fromEnv)}`) } return port @@ -137,7 +138,7 @@ function startStaticServer({ port }) { return new Promise((resolve) => { server.listen(port, () => { - console.log(`E2E app: http://localhost:${server.address().port}`) + console.log(`http://localhost:${port}`) resolve(server) }) }) diff --git a/e2e/vue-router/basic-esbuild-file-based/src/routes/(another-group)/onlyrouteinside.tsx b/e2e/vue-router/basic-esbuild-file-based/src/routes/(another-group)/onlyrouteinside.tsx index 8869cefc01..83036509ba 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,32 +1,28 @@ -import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' import { z } from 'zod' - -const OnlyRouteInsideComponent = defineComponent({ - setup() { - const searchViaHook = useSearch({ - from: '/(another-group)/onlyrouteinside', - }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return () => ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) - }, -}) +import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(another-group)/onlyrouteinside')({ - validateSearch: z.object({ hello: z.string().optional() }), + validateSearch: zodValidator(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 f2998803fd..557503a0c2 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,30 +1,28 @@ -import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' import { z } from 'zod' - -const InsideLayoutComponent = defineComponent({ - setup() { - const searchViaHook = useSearch({ from: '/(group)/_layout/insidelayout' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return () => ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) - }, -}) +import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(group)/_layout/insidelayout')({ - validateSearch: z.object({ hello: z.string().optional() }), + validateSearch: zodValidator(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 20e0d5afdb..bec12d8de2 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,30 +1,28 @@ -import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' import { z } from 'zod' - -const InsideComponent = defineComponent({ - setup() { - const searchViaHook = useSearch({ from: '/(group)/inside' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return () => ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) - }, -}) +import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(group)/inside')({ - validateSearch: z.object({ hello: z.string().optional() }), + validateSearch: zodValidator(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 a46da658d6..56d8d6cae8 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,30 +1,28 @@ -import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' import { z } from 'zod' - -const LazyInsideComponent = defineComponent({ - setup() { - const searchViaHook = useSearch({ from: '/(group)/lazyinside' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return () => ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) - }, -}) +import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(group)/lazyinside')({ - validateSearch: z.object({ hello: z.string().optional() }), + validateSearch: zodValidator(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 715d2cc972..b4487d163d 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,30 +1,28 @@ -import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' import { z } from 'zod' - -const SubfolderInsideComponent = defineComponent({ - setup() { - const searchViaHook = useSearch({ from: '/(group)/subfolder/inside' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return () => ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) - }, -}) +import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(group)/subfolder/inside')({ - validateSearch: z.object({ hello: z.string().optional() }), + validateSearch: zodValidator(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 62c4af3aa4..59c9e6fa48 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,4 +1,3 @@ -import { defineComponent } from 'vue' import { HeadContent, Link, @@ -11,97 +10,95 @@ 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 54ae789c8e..15d17387c8 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,27 +1,24 @@ -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 e0afd27b4c..ae580dfc02 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,38 +1,7 @@ -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: [ @@ -44,3 +13,31 @@ 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 22979c93c9..57963c6b64 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,28 +1,23 @@ -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 deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/vue-router/basic-esbuild-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/vue-router/basic-esbuild-file-based/tests/app.spec.ts b/e2e/vue-router/basic-esbuild-file-based/tests/app.spec.ts index 7380859e7b..543746d64d 100644 --- a/e2e/vue-router/basic-esbuild-file-based/tests/app.spec.ts +++ b/e2e/vue-router/basic-esbuild-file-based/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' import type { Page } from '@playwright/test' test.beforeEach(async ({ page }) => { diff --git a/e2e/vue-router/basic-esbuild-file-based/tests/setup/global.setup.ts b/e2e/vue-router/basic-esbuild-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/basic-esbuild-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic-esbuild-file-based/tests/setup/global.teardown.ts b/e2e/vue-router/basic-esbuild-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/basic-esbuild-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic-file-based-jsx/package.json b/e2e/vue-router/basic-file-based-jsx/package.json index 9ab7f21e82..f8664f2cc2 100644 --- a/e2e/vue-router/basic-file-based-jsx/package.json +++ b/e2e/vue-router/basic-file-based-jsx/package.json @@ -8,21 +8,22 @@ "build": "vite build && vue-tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/router-plugin": "workspace:^", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "catalog:", + "@tanstack/zod-adapter": "workspace:^", + "redaxios": "^0.5.1", "tailwindcss": "^4.2.2", "vue": "^3.5.16", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { "@eslint/js": "^9.36.0", - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", "@typescript-eslint/eslint-plugin": "^8.44.1", "@typescript-eslint/parser": "^8.44.1", @@ -30,8 +31,8 @@ "@vitejs/plugin-vue-jsx": "^5.1.5", "eslint-plugin-vue": "^9.33.0", "typescript": "~5.8.3", - "vite": "^8.0.14", + "vite": "^8.0.0", "vue-eslint-parser": "^9.4.3", - "vue-tsc": "^3.3.8" + "vue-tsc": "^3.1.5" } } diff --git a/e2e/vue-router/basic-file-based-jsx/playwright.config.ts b/e2e/vue-router/basic-file-based-jsx/playwright.config.ts index 4eead86444..836ea41bd8 100644 --- a/e2e/vue-router/basic-file-based-jsx/playwright.config.ts +++ b/e2e/vue-router/basic-file-based-jsx/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic-file-based-jsx/src/posts.tsx b/e2e/vue-router/basic-file-based-jsx/src/posts.tsx index f7a1941605..1b4c92b41d 100644 --- a/e2e/vue-router/basic-file-based-jsx/src/posts.tsx +++ b/e2e/vue-router/basic-file-based-jsx/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/vue-router/basic-file-based-jsx/src/routeTree.gen.ts b/e2e/vue-router/basic-file-based-jsx/src/routeTree.gen.ts index 5922c5f7b1..f5cd519d7f 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,62 +11,34 @@ import { lazyRouteComponent } from '@tanstack/vue-router' import { Route as rootRouteImport } from './routes/__root' -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 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 PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -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 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' -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 Char45824Char54620Char48124Char44397Route = + Char45824Char54620Char48124Char44397RouteImport.update({ + id: '/대한민국', + path: '/대한민국', + getParentRoute: () => rootRouteImport, + } as any) const SfcComponentRoute = SfcComponentRouteImport.update({ id: '/sfcComponent', path: '/sfcComponent', @@ -77,35 +49,39 @@ const SfcComponentRoute = SfcComponentRouteImport.update({ 'default', ), }) -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', +const RemountDepsRoute = RemountDepsRouteImport.update({ + id: '/remountDeps', + path: '/remountDeps', getParentRoute: () => rootRouteImport, } as any) -const groupInsideRoute = groupInsideRouteImport.update({ - id: '/(group)/inside', - path: '/inside', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const groupLazyinsideRoute = groupLazyinsideRouteImport.update({ - id: '/(group)/lazyinside', - path: '/lazyinside', +const NotRemountDepsRoute = NotRemountDepsRouteImport.update({ + id: '/notRemountDeps', + path: '/notRemountDeps', getParentRoute: () => rootRouteImport, } as any) -const LayoutLayout2Route = LayoutLayout2RouteImport.update({ - id: '/_layout-2', - getParentRoute: () => LayoutRoute, +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, } as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', @@ -117,31 +93,55 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ path: '/$postId', getParentRoute: () => PostsRoute, } as any) -const groupLayoutInsidelayoutRoute = groupLayoutInsidelayoutRouteImport.update({ - id: '/insidelayout', - path: '/insidelayout', - getParentRoute: () => groupLayoutRoute, +const LayoutLayout2Route = LayoutLayout2RouteImport.update({ + id: '/_layout-2', + getParentRoute: () => LayoutRoute, } as any) -const groupSubfolderInsideRoute = groupSubfolderInsideRouteImport.update({ - id: '/(group)/subfolder/inside', - path: '/subfolder/inside', +const groupLazyinsideRoute = groupLazyinsideRouteImport.update({ + id: '/(group)/lazyinside', + path: '/lazyinside', getParentRoute: () => rootRouteImport, } as any) -const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => LayoutLayout2Route, +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 PostsPostIdEditRoute = PostsPostIdEditRouteImport.update({ - id: '/posts_/$postId/edit', - path: '/posts/$postId/edit', +const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => LayoutLayout2Route, +} as any) +const groupSubfolderInsideRoute = groupSubfolderInsideRouteImport.update({ + id: '/(group)/subfolder/inside', + path: '/subfolder/inside', getParentRoute: () => rootRouteImport, } as any) +const groupLayoutInsidelayoutRoute = groupLayoutInsidelayoutRouteImport.update({ + id: '/insidelayout', + path: '/insidelayout', + getParentRoute: () => groupLayoutRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -291,53 +291,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_layout': { - id: '/_layout' - path: '' - fullPath: '/' - preLoaderRoute: typeof LayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/editing-a': { - id: '/editing-a' - path: '/editing-a' - fullPath: '/editing-a' - preLoaderRoute: typeof EditingARouteImport - parentRoute: typeof rootRouteImport - } - '/editing-b': { - id: '/editing-b' - path: '/editing-b' - fullPath: '/editing-b' - preLoaderRoute: typeof EditingBRouteImport - parentRoute: typeof rootRouteImport - } - '/notRemountDeps': { - id: '/notRemountDeps' - path: '/notRemountDeps' - fullPath: '/notRemountDeps' - preLoaderRoute: typeof NotRemountDepsRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/remountDeps': { - id: '/remountDeps' - path: '/remountDeps' - fullPath: '/remountDeps' - preLoaderRoute: typeof RemountDepsRouteImport + '/대한민국': { + id: '/대한민국' + path: '/대한민국' + fullPath: '/대한민국' + preLoaderRoute: typeof Char45824Char54620Char48124Char44397RouteImport parentRoute: typeof rootRouteImport } '/sfcComponent': { @@ -347,47 +305,54 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof SfcComponentRouteImport parentRoute: typeof rootRouteImport } - '/대한민국': { - id: '/대한민국' - path: '/대한민국' - fullPath: '/대한민국' - preLoaderRoute: typeof Char45824Char54620Char48124Char44397RouteImport + '/remountDeps': { + id: '/remountDeps' + path: '/remountDeps' + fullPath: '/remountDeps' + preLoaderRoute: typeof RemountDepsRouteImport parentRoute: typeof rootRouteImport } - '/(another-group)/onlyrouteinside': { - id: '/(another-group)/onlyrouteinside' - path: '/onlyrouteinside' - fullPath: '/onlyrouteinside' - preLoaderRoute: typeof anotherGroupOnlyrouteinsideRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } - '/(group)/_layout': { - id: '/(group)/_layout' + '/notRemountDeps': { + id: '/notRemountDeps' + path: '/notRemountDeps' + fullPath: '/notRemountDeps' + preLoaderRoute: typeof NotRemountDepsRouteImport + parentRoute: typeof rootRouteImport + } + '/editing-b': { + id: '/editing-b' + path: '/editing-b' + fullPath: '/editing-b' + preLoaderRoute: typeof EditingBRouteImport + parentRoute: typeof rootRouteImport + } + '/editing-a': { + id: '/editing-a' + path: '/editing-a' + fullPath: '/editing-a' + preLoaderRoute: typeof EditingARouteImport + parentRoute: typeof rootRouteImport + } + '/_layout': { + id: '/_layout' path: '' fullPath: '/' - preLoaderRoute: typeof groupLayoutRouteImport + preLoaderRoute: typeof LayoutRouteImport 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: '' + '/': { + id: '/' + path: '/' fullPath: '/' - preLoaderRoute: typeof LayoutLayout2RouteImport - parentRoute: typeof LayoutRoute + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport } '/posts/': { id: '/posts/' @@ -403,26 +368,47 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRoute } - '/(group)/_layout/insidelayout': { - id: '/(group)/_layout/insidelayout' - path: '/insidelayout' - fullPath: '/insidelayout' - preLoaderRoute: typeof groupLayoutInsidelayoutRouteImport - parentRoute: typeof groupLayoutRoute + '/_layout/_layout-2': { + id: '/_layout/_layout-2' + path: '' + fullPath: '/' + preLoaderRoute: typeof LayoutLayout2RouteImport + parentRoute: typeof LayoutRoute } - '/(group)/subfolder/inside': { - id: '/(group)/subfolder/inside' - path: '/subfolder/inside' - fullPath: '/subfolder/inside' - preLoaderRoute: typeof groupSubfolderInsideRouteImport + '/(group)/lazyinside': { + id: '/(group)/lazyinside' + path: '/lazyinside' + fullPath: '/lazyinside' + preLoaderRoute: typeof groupLazyinsideRouteImport parentRoute: typeof rootRouteImport } - '/_layout/_layout-2/layout-a': { - id: '/_layout/_layout-2/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof LayoutLayout2LayoutARouteImport - parentRoute: typeof LayoutLayout2Route + '/(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' @@ -431,13 +417,27 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport parentRoute: typeof LayoutLayout2Route } - '/posts_/$postId/edit': { - id: '/posts_/$postId/edit' - path: '/posts/$postId/edit' - fullPath: '/posts/$postId/edit' - preLoaderRoute: typeof PostsPostIdEditRouteImport + '/_layout/_layout-2/layout-a': { + id: '/_layout/_layout-2/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof LayoutLayout2LayoutARouteImport + parentRoute: typeof LayoutLayout2Route + } + '/(group)/subfolder/inside': { + id: '/(group)/subfolder/inside' + path: '/subfolder/inside' + fullPath: '/subfolder/inside' + preLoaderRoute: typeof groupSubfolderInsideRouteImport parentRoute: typeof rootRouteImport } + '/(group)/_layout/insidelayout': { + id: '/(group)/_layout/insidelayout' + path: '/insidelayout' + fullPath: '/insidelayout' + preLoaderRoute: typeof groupLayoutInsidelayoutRouteImport + parentRoute: typeof groupLayoutRoute + } } } 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 8869cefc01..83036509ba 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,32 +1,28 @@ -import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' import { z } from 'zod' - -const OnlyRouteInsideComponent = defineComponent({ - setup() { - const searchViaHook = useSearch({ - from: '/(another-group)/onlyrouteinside', - }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return () => ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) - }, -}) +import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(another-group)/onlyrouteinside')({ - validateSearch: z.object({ hello: z.string().optional() }), + validateSearch: zodValidator(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 f2998803fd..557503a0c2 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,30 +1,28 @@ -import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' import { z } from 'zod' - -const InsideLayoutComponent = defineComponent({ - setup() { - const searchViaHook = useSearch({ from: '/(group)/_layout/insidelayout' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return () => ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) - }, -}) +import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(group)/_layout/insidelayout')({ - validateSearch: z.object({ hello: z.string().optional() }), + validateSearch: zodValidator(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 20e0d5afdb..bec12d8de2 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,30 +1,28 @@ -import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' import { z } from 'zod' - -const InsideComponent = defineComponent({ - setup() { - const searchViaHook = useSearch({ from: '/(group)/inside' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return () => ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) - }, -}) +import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(group)/inside')({ - validateSearch: z.object({ hello: z.string().optional() }), + validateSearch: zodValidator(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 a46da658d6..56d8d6cae8 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,30 +1,28 @@ -import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' import { z } from 'zod' - -const LazyInsideComponent = defineComponent({ - setup() { - const searchViaHook = useSearch({ from: '/(group)/lazyinside' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return () => ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) - }, -}) +import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(group)/lazyinside')({ - validateSearch: z.object({ hello: z.string().optional() }), + validateSearch: zodValidator(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 715d2cc972..b4487d163d 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,30 +1,28 @@ -import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' import { z } from 'zod' - -const SubfolderInsideComponent = defineComponent({ - setup() { - const searchViaHook = useSearch({ from: '/(group)/subfolder/inside' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return () => ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) - }, -}) +import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(group)/subfolder/inside')({ - validateSearch: z.object({ hello: z.string().optional() }), + validateSearch: zodValidator(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 62c4af3aa4..59c9e6fa48 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,4 +1,3 @@ -import { defineComponent } from 'vue' import { HeadContent, Link, @@ -11,97 +10,95 @@ 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 54ae789c8e..15d17387c8 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,27 +1,24 @@ -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 e0afd27b4c..ae580dfc02 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,38 +1,7 @@ -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: [ @@ -44,3 +13,31 @@ 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 22979c93c9..57963c6b64 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,28 +1,23 @@ -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/vite-env.d.ts b/e2e/vue-router/basic-file-based-jsx/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/vue-router/basic-file-based-jsx/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/vue-router/basic-file-based-jsx/tests/app.spec.ts b/e2e/vue-router/basic-file-based-jsx/tests/app.spec.ts index 7380859e7b..543746d64d 100644 --- a/e2e/vue-router/basic-file-based-jsx/tests/app.spec.ts +++ b/e2e/vue-router/basic-file-based-jsx/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' import type { Page } from '@playwright/test' test.beforeEach(async ({ page }) => { diff --git a/e2e/vue-router/basic-file-based-jsx/tests/setup/global.setup.ts b/e2e/vue-router/basic-file-based-jsx/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/basic-file-based-jsx/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic-file-based-jsx/tests/setup/global.teardown.ts b/e2e/vue-router/basic-file-based-jsx/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/basic-file-based-jsx/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic-file-based-sfc/package.json b/e2e/vue-router/basic-file-based-sfc/package.json index e6ffa156f9..567b7fca4e 100644 --- a/e2e/vue-router/basic-file-based-sfc/package.json +++ b/e2e/vue-router/basic-file-based-sfc/package.json @@ -8,25 +8,26 @@ "build": "vite build && vue-tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/router-plugin": "workspace:^", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "catalog:", + "@tanstack/zod-adapter": "workspace:^", + "redaxios": "^0.5.1", "tailwindcss": "^4.2.2", "vue": "^3.5.16", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", "typescript": "~5.8.3", - "vite": "^8.0.14", - "vue-tsc": "^3.3.8" + "vite": "^8.0.0", + "vue-tsc": "^3.1.5" } } diff --git a/e2e/vue-router/basic-file-based-sfc/playwright.config.ts b/e2e/vue-router/basic-file-based-sfc/playwright.config.ts index 4eead86444..836ea41bd8 100644 --- a/e2e/vue-router/basic-file-based-sfc/playwright.config.ts +++ b/e2e/vue-router/basic-file-based-sfc/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic-file-based-sfc/src/posts.ts b/e2e/vue-router/basic-file-based-sfc/src/posts.ts index f7a1941605..1b4c92b41d 100644 --- a/e2e/vue-router/basic-file-based-sfc/src/posts.ts +++ b/e2e/vue-router/basic-file-based-sfc/src/posts.ts @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/vue-router/basic-file-based-sfc/src/routeTree.gen.ts b/e2e/vue-router/basic-file-based-sfc/src/routeTree.gen.ts index 0bfdddab3d..fa00eb1ce0 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,73 +11,45 @@ import { lazyRouteComponent } from '@tanstack/vue-router' import { Route as rootRouteImport } from './routes/__root' -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 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 PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -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 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' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +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', getParentRoute: () => rootRouteImport, } as any).update({ component: lazyRouteComponent( - () => import('./routes/index.component.vue'), - 'default', - ), -}) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', - getParentRoute: () => rootRouteImport, -} as any).update({ - component: lazyRouteComponent( - () => import('./routes/_layout.component.vue'), - 'default', - ), -}) -const EditingARoute = EditingARouteImport.update({ - id: '/editing-a', - path: '/editing-a', - getParentRoute: () => rootRouteImport, -} as any).update({ - component: lazyRouteComponent( - () => import('./routes/editing-a.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'), - 'default', - ), -}) -const NotRemountDepsRoute = NotRemountDepsRouteImport.update({ - id: '/notRemountDeps', - path: '/notRemountDeps', - getParentRoute: () => rootRouteImport, -} as any).update({ - component: lazyRouteComponent( - () => import('./routes/notRemountDeps.component.vue'), + () => import('./routes/remountDeps.component.vue'), 'default', ), }) @@ -91,80 +63,52 @@ const PostsRoute = PostsRouteImport.update({ 'default', ), }) -const RemountDepsRoute = RemountDepsRouteImport.update({ - id: '/remountDeps', - path: '/remountDeps', +const NotRemountDepsRoute = NotRemountDepsRouteImport.update({ + id: '/notRemountDeps', + path: '/notRemountDeps', getParentRoute: () => rootRouteImport, } as any).update({ component: lazyRouteComponent( - () => import('./routes/remountDeps.component.vue'), + () => import('./routes/notRemountDeps.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, +const EditingBRoute = EditingBRouteImport.update({ + id: '/editing-b', + path: '/editing-b', + getParentRoute: () => rootRouteImport, } as any).update({ component: lazyRouteComponent( - () => import('./routes/_layout/_layout-2.component.vue'), + () => import('./routes/editing-b.component.vue'), + 'default', + ), +}) +const EditingARoute = EditingARouteImport.update({ + id: '/editing-a', + path: '/editing-a', + getParentRoute: () => rootRouteImport, +} as any).update({ + component: lazyRouteComponent( + () => import('./routes/editing-a.component.vue'), + 'default', + ), +}) +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', + getParentRoute: () => rootRouteImport, +} as any).update({ + component: lazyRouteComponent( + () => import('./routes/_layout.component.vue'), + 'default', + ), +}) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any).update({ + component: lazyRouteComponent( + () => import('./routes/index.component.vue'), 'default', ), }) @@ -192,37 +136,69 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ 'default', ), }) -const groupLayoutInsidelayoutRoute = groupLayoutInsidelayoutRouteImport +const LayoutLayout2Route = LayoutLayout2RouteImport.update({ + id: '/_layout-2', + getParentRoute: () => LayoutRoute, +} as any).update({ + component: lazyRouteComponent( + () => import('./routes/_layout/_layout-2.component.vue'), + 'default', + ), +}) +const groupLazyinsideRoute = groupLazyinsideRouteImport .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', + id: '/(group)/lazyinside', + path: '/lazyinside', getParentRoute: () => rootRouteImport, } as any) .update({ component: lazyRouteComponent( - () => import('./routes/(group)/subfolder/inside.component.vue'), + () => import('./routes/(group)/lazyinside.component.vue'), 'default', ), }) -const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => LayoutLayout2Route, +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/_layout/_layout-2/layout-a.component.vue'), + () => import('./routes/posts_.$postId.edit.component.vue'), 'default', ), }) @@ -236,16 +212,40 @@ const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ 'default', ), }) -const PostsPostIdEditRoute = PostsPostIdEditRouteImport.update({ - id: '/posts_/$postId/edit', - path: '/posts/$postId/edit', - getParentRoute: () => rootRouteImport, +const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => LayoutLayout2Route, } as any).update({ component: lazyRouteComponent( - () => import('./routes/posts_.$postId.edit.component.vue'), + () => import('./routes/_layout/_layout-2/layout-a.component.vue'), 'default', ), }) +const groupSubfolderInsideRoute = groupSubfolderInsideRouteImport + .update({ + id: '/(group)/subfolder/inside', + path: '/subfolder/inside', + getParentRoute: () => rootRouteImport, + } as any) + .update({ + component: lazyRouteComponent( + () => import('./routes/(group)/subfolder/inside.component.vue'), + 'default', + ), + }) +const groupLayoutInsidelayoutRoute = groupLayoutInsidelayoutRouteImport + .update({ + id: '/insidelayout', + path: '/insidelayout', + getParentRoute: () => groupLayoutRoute, + } as any) + .update({ + component: lazyRouteComponent( + () => import('./routes/(group)/_layout.insidelayout.component.vue'), + 'default', + ), + }) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -388,46 +388,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_layout': { - id: '/_layout' - path: '' - fullPath: '/' - preLoaderRoute: typeof LayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/editing-a': { - id: '/editing-a' - path: '/editing-a' - fullPath: '/editing-a' - preLoaderRoute: typeof EditingARouteImport - parentRoute: typeof rootRouteImport - } - '/editing-b': { - id: '/editing-b' - path: '/editing-b' - fullPath: '/editing-b' - preLoaderRoute: typeof EditingBRouteImport - parentRoute: typeof rootRouteImport - } - '/notRemountDeps': { - id: '/notRemountDeps' - path: '/notRemountDeps' - fullPath: '/notRemountDeps' - preLoaderRoute: typeof NotRemountDepsRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport + '/대한민국': { + id: '/대한민국' + path: '/대한민국' + fullPath: '/대한민국' + preLoaderRoute: typeof Char45824Char54620Char48124Char44397RouteImport parentRoute: typeof rootRouteImport } '/remountDeps': { @@ -437,47 +402,47 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof RemountDepsRouteImport parentRoute: typeof rootRouteImport } - '/대한민국': { - id: '/대한민국' - path: '/대한민국' - fullPath: '/대한민국' - preLoaderRoute: typeof Char45824Char54620Char48124Char44397RouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } - '/(another-group)/onlyrouteinside': { - id: '/(another-group)/onlyrouteinside' - path: '/onlyrouteinside' - fullPath: '/onlyrouteinside' - preLoaderRoute: typeof anotherGroupOnlyrouteinsideRouteImport + '/notRemountDeps': { + id: '/notRemountDeps' + path: '/notRemountDeps' + fullPath: '/notRemountDeps' + preLoaderRoute: typeof NotRemountDepsRouteImport parentRoute: typeof rootRouteImport } - '/(group)/_layout': { - id: '/(group)/_layout' + '/editing-b': { + id: '/editing-b' + path: '/editing-b' + fullPath: '/editing-b' + preLoaderRoute: typeof EditingBRouteImport + parentRoute: typeof rootRouteImport + } + '/editing-a': { + id: '/editing-a' + path: '/editing-a' + fullPath: '/editing-a' + preLoaderRoute: typeof EditingARouteImport + parentRoute: typeof rootRouteImport + } + '/_layout': { + id: '/_layout' path: '' fullPath: '/' - preLoaderRoute: typeof groupLayoutRouteImport + preLoaderRoute: typeof LayoutRouteImport 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: '' + '/': { + id: '/' + path: '/' fullPath: '/' - preLoaderRoute: typeof LayoutLayout2RouteImport - parentRoute: typeof LayoutRoute + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport } '/posts/': { id: '/posts/' @@ -493,26 +458,47 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRoute } - '/(group)/_layout/insidelayout': { - id: '/(group)/_layout/insidelayout' - path: '/insidelayout' - fullPath: '/insidelayout' - preLoaderRoute: typeof groupLayoutInsidelayoutRouteImport - parentRoute: typeof groupLayoutRoute + '/_layout/_layout-2': { + id: '/_layout/_layout-2' + path: '' + fullPath: '/' + preLoaderRoute: typeof LayoutLayout2RouteImport + parentRoute: typeof LayoutRoute } - '/(group)/subfolder/inside': { - id: '/(group)/subfolder/inside' - path: '/subfolder/inside' - fullPath: '/subfolder/inside' - preLoaderRoute: typeof groupSubfolderInsideRouteImport + '/(group)/lazyinside': { + id: '/(group)/lazyinside' + path: '/lazyinside' + fullPath: '/lazyinside' + preLoaderRoute: typeof groupLazyinsideRouteImport parentRoute: typeof rootRouteImport } - '/_layout/_layout-2/layout-a': { - id: '/_layout/_layout-2/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof LayoutLayout2LayoutARouteImport - parentRoute: typeof LayoutLayout2Route + '/(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' @@ -521,13 +507,27 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport parentRoute: typeof LayoutLayout2Route } - '/posts_/$postId/edit': { - id: '/posts_/$postId/edit' - path: '/posts/$postId/edit' - fullPath: '/posts/$postId/edit' - preLoaderRoute: typeof PostsPostIdEditRouteImport + '/_layout/_layout-2/layout-a': { + id: '/_layout/_layout-2/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof LayoutLayout2LayoutARouteImport + parentRoute: typeof LayoutLayout2Route + } + '/(group)/subfolder/inside': { + id: '/(group)/subfolder/inside' + path: '/subfolder/inside' + fullPath: '/subfolder/inside' + preLoaderRoute: typeof groupSubfolderInsideRouteImport parentRoute: typeof rootRouteImport } + '/(group)/_layout/insidelayout': { + id: '/(group)/_layout/insidelayout' + path: '/insidelayout' + fullPath: '/insidelayout' + preLoaderRoute: typeof groupLayoutInsidelayoutRouteImport + parentRoute: typeof groupLayoutRoute + } } } 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 f427c79321..491bb03649 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,6 +1,7 @@ import { createFileRoute } from '@tanstack/vue-router' import { z } from 'zod' +import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(another-group)/onlyrouteinside')({ - validateSearch: z.object({ hello: z.string().optional() }), + validateSearch: zodValidator(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 3b605763af..49ef8f7bb9 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,6 +1,7 @@ import { createFileRoute } from '@tanstack/vue-router' import { z } from 'zod' +import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(group)/_layout/insidelayout')({ - validateSearch: z.object({ hello: z.string().optional() }), + validateSearch: zodValidator(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 456e8fe169..f7b06f6a94 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,6 +1,7 @@ import { createFileRoute } from '@tanstack/vue-router' import { z } from 'zod' +import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(group)/inside')({ - validateSearch: z.object({ hello: z.string().optional() }), + validateSearch: zodValidator(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 7fba56aae4..b66d18a729 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,6 +1,7 @@ import { createFileRoute } from '@tanstack/vue-router' import { z } from 'zod' +import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(group)/lazyinside')({ - validateSearch: z.object({ hello: z.string().optional() }), + validateSearch: zodValidator(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 21e5d7ba0a..50aa8a44ad 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,6 +1,7 @@ import { createFileRoute } from '@tanstack/vue-router' import { z } from 'zod' +import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(group)/subfolder/inside')({ - validateSearch: z.object({ hello: z.string().optional() }), + validateSearch: zodValidator(z.object({ hello: z.string().optional() })), }) 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 deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/vue-router/basic-file-based-sfc/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/vue-router/basic-file-based-sfc/tests/app.spec.ts b/e2e/vue-router/basic-file-based-sfc/tests/app.spec.ts index 7380859e7b..543746d64d 100644 --- a/e2e/vue-router/basic-file-based-sfc/tests/app.spec.ts +++ b/e2e/vue-router/basic-file-based-sfc/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' import type { Page } from '@playwright/test' test.beforeEach(async ({ page }) => { diff --git a/e2e/vue-router/basic-file-based-sfc/tests/setup/global.setup.ts b/e2e/vue-router/basic-file-based-sfc/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/basic-file-based-sfc/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic-file-based-sfc/tests/setup/global.teardown.ts b/e2e/vue-router/basic-file-based-sfc/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/basic-file-based-sfc/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic-scroll-restoration/package.json b/e2e/vue-router/basic-scroll-restoration/package.json index f4616a5651..05d5954615 100644 --- a/e2e/vue-router/basic-scroll-restoration/package.json +++ b/e2e/vue-router/basic-scroll-restoration/package.json @@ -8,24 +8,24 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-virtual": "^3.13.0", - "redaxios": "catalog:", + "redaxios": "^0.5.1", "vue": "^3.5.16", "tailwindcss": "^4.2.2" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", - "vite": "^8.0.14", - "vue-tsc": "^3.3.8", - "typescript": "~5.9.0" + "typescript": "~5.8.3", + "vite": "^8.0.0", + "vue-tsc": "^3.1.5" } } diff --git a/e2e/vue-router/basic-scroll-restoration/playwright.config.ts b/e2e/vue-router/basic-scroll-restoration/playwright.config.ts index 6a684ac89e..0c5cee43e4 100644 --- a/e2e/vue-router/basic-scroll-restoration/playwright.config.ts +++ b/e2e/vue-router/basic-scroll-restoration/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic-scroll-restoration/src/vite-env.d.ts b/e2e/vue-router/basic-scroll-restoration/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/vue-router/basic-scroll-restoration/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/vue-router/basic-virtual-file-based/package.json b/e2e/vue-router/basic-virtual-file-based/package.json index 3701c2254c..9e37cef47e 100644 --- a/e2e/vue-router/basic-virtual-file-based/package.json +++ b/e2e/vue-router/basic-virtual-file-based/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -18,17 +18,17 @@ "@tanstack/vue-query-devtools": "^6.1.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "catalog:", + "redaxios": "^0.5.1", "tailwindcss": "^4.2.2", "vue": "^3.5.16" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", "typescript": "~5.8.3", - "vite": "^8.0.14", - "vue-tsc": "^3.3.8" + "vite": "^8.0.0", + "vue-tsc": "^3.1.5" } } diff --git a/e2e/vue-router/basic-virtual-file-based/playwright.config.ts b/e2e/vue-router/basic-virtual-file-based/playwright.config.ts index 4eead86444..836ea41bd8 100644 --- a/e2e/vue-router/basic-virtual-file-based/playwright.config.ts +++ b/e2e/vue-router/basic-virtual-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic-virtual-file-based/src/posts.tsx b/e2e/vue-router/basic-virtual-file-based/src/posts.tsx index 5f5463a668..8576a3799a 100644 --- a/e2e/vue-router/basic-virtual-file-based/src/posts.tsx +++ b/e2e/vue-router/basic-virtual-file-based/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/vue-router/basic-virtual-file-based/src/routeTree.gen.ts b/e2e/vue-router/basic-virtual-file-based/src/routeTree.gen.ts index 1bae3d69a1..a4c92111db 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,77 +8,79 @@ // 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 homeRouteImport } from './routes/home' -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 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 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' +import type { CreateFileRoute, FileRoutesByPath } from '@tanstack/vue-router' -const homeRoute = homeRouteImport.update({ - id: '/', - path: '/', +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 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 aRouteImport } from './routes/a' + +const postsPostsRoute = postsPostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) const layoutFirstLayoutRoute = layoutFirstLayoutRouteImport.update({ id: '/_first', getParentRoute: () => rootRouteImport, } as any) -const postsPostsRoute = postsPostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) -const layoutSecondLayoutRoute = layoutSecondLayoutRouteImport.update({ - id: '/_second', - getParentRoute: () => layoutFirstLayoutRoute, -} as any) -const ClassicHelloRouteRoute = ClassicHelloRouteRouteImport.update({ - id: '/classic/hello', - path: '/classic/hello', - getParentRoute: () => rootRouteImport, -} as any) -const postsPostsHomeRoute = postsPostsHomeRouteImport.update({ +const homeRoute = homeRouteImport.update({ id: '/', path: '/', - getParentRoute: () => postsPostsRoute, + getParentRoute: () => rootRouteImport, } 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, +const layoutSecondLayoutRoute = layoutSecondLayoutRouteImport.update({ + id: '/_second', + getParentRoute: () => layoutFirstLayoutRoute, } as any) -const bRoute = bRouteImport.update({ - id: '/layout-b', - path: '/layout-b', - getParentRoute: () => layoutSecondLayoutRoute, +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 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 ClassicHelloWorldRoute = ClassicHelloWorldRouteImport.update({ - id: '/world', - path: '/world', - getParentRoute: () => ClassicHelloRouteRoute, +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, } as any) export interface FileRoutesByFullPath { @@ -166,11 +168,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof homeRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof postsPostsRouteImport parentRoute: typeof rootRouteImport } '/_first': { @@ -180,33 +182,12 @@ declare module '@tanstack/vue-router' { 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: '/' - preLoaderRoute: typeof layoutSecondLayoutRouteImport - parentRoute: typeof layoutFirstLayoutRoute - } - '/classic/hello': { - id: '/classic/hello' - path: '/classic/hello' - fullPath: '/classic/hello' - preLoaderRoute: typeof ClassicHelloRouteRouteImport - parentRoute: typeof rootRouteImport - } - '/posts/': { - id: '/posts/' + '/': { + id: '/' path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof postsPostsHomeRouteImport - parentRoute: typeof postsPostsRoute + fullPath: '/' + preLoaderRoute: typeof homeRouteImport + parentRoute: typeof rootRouteImport } '/posts/$postId': { id: '/posts/$postId' @@ -215,19 +196,26 @@ declare module '@tanstack/vue-router' { 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': { + id: '/_first/_second' + path: '' + fullPath: '/' + preLoaderRoute: typeof layoutSecondLayoutRouteImport + parentRoute: typeof layoutFirstLayoutRoute } - '/_first/_second/layout-b': { - id: '/_first/_second/layout-b' - path: '/layout-b' - fullPath: '/layout-b' - preLoaderRoute: typeof bRouteImport - parentRoute: typeof layoutSecondLayoutRoute + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof postsPostsHomeRouteImport + parentRoute: typeof postsPostsRoute + } + '/classic/hello': { + id: '/classic/hello' + path: '/classic/hello' + fullPath: '/classic/hello' + preLoaderRoute: typeof ClassicHelloRouteRouteImport + parentRoute: typeof rootRouteImport } '/classic/hello/': { id: '/classic/hello/' @@ -236,13 +224,6 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof ClassicHelloIndexRouteImport parentRoute: typeof ClassicHelloRouteRoute } - '/classic/hello/universe': { - id: '/classic/hello/universe' - path: '/universe' - fullPath: '/classic/hello/universe' - preLoaderRoute: typeof ClassicHelloUniverseRouteImport - parentRoute: typeof ClassicHelloRouteRoute - } '/classic/hello/world': { id: '/classic/hello/world' path: '/world' @@ -250,9 +231,139 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof ClassicHelloWorldRouteImport parentRoute: typeof ClassicHelloRouteRoute } + '/classic/hello/universe': { + id: '/classic/hello/universe' + path: '/universe' + fullPath: '/classic/hello/universe' + 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 + } } } +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 133d40f19e..a190b24202 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,5 +1,4 @@ -import { createFileRoute } from '@tanstack/vue-router' -export const Route = createFileRoute('/_first/_second/layout-a')({ +export const Route = createFileRoute({ 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 caae6c1ded..505f8f6fbf 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,5 +1,4 @@ -import { createFileRoute } from '@tanstack/vue-router' -export const Route = createFileRoute('/_first/_second/layout-b')({ +export const Route = createFileRoute({ 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 9b0d21d191..f86335e291 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,4 +1,3 @@ -import { createFileRoute } from '@tanstack/vue-router' -export const Route = createFileRoute('/classic/hello/')({ +export const Route = createFileRoute({ 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 24c72f2fb9..f07d58fd3e 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, createFileRoute } from '@tanstack/vue-router' +import { Link, Outlet } from '@tanstack/vue-router' -export const Route = createFileRoute('/classic/hello')({ +export const Route = createFileRoute({ component: () => (
)} /> - - Loading stuff...
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 650dd2ee62..20b07c41cc 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,4 +1,3 @@ -import { createFileRoute } from '@tanstack/vue-router' -export const Route = createFileRoute('/classic/hello/universe')({ +export const Route = createFileRoute({ 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 c752e6b5a4..4af11357a2 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,4 +1,3 @@ -import { createFileRoute } from '@tanstack/vue-router' -export const Route = createFileRoute('/classic/hello/world')({ +export const Route = createFileRoute({ 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 acf99ce567..510db79b73 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,5 +1,4 @@ -import { createFileRoute } from '@tanstack/vue-router' -export const Route = createFileRoute('/')({ +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 7b82bcd7c5..9e66c18e33 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, createFileRoute } from '@tanstack/vue-router' +import { Outlet } from '@tanstack/vue-router' -export const Route = createFileRoute('/_first')({ +export const Route = createFileRoute({ 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 cc1dafa5a1..acb6d2c8ae 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, createFileRoute } from '@tanstack/vue-router' +import { Link, Outlet } from '@tanstack/vue-router' -export const Route = createFileRoute('/_first/_second')({ +export const Route = createFileRoute({ 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 aa5387a4d8..9b416bcf82 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,5 +1,4 @@ -import { defineComponent } from 'vue' -import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' +import { ErrorComponent } from '@tanstack/vue-router' import { fetchPost } from '../../posts' import type { ErrorComponentProps } from '@tanstack/vue-router' @@ -7,20 +6,7 @@ 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')({ +export const Route = createFileRoute({ loader: async ({ params: { postId } }) => fetchPost(postId), errorComponent: PostErrorComponent as any, notFoundComponent: () => { @@ -28,3 +14,14 @@ export const Route = createFileRoute('/posts/$postId')({ }, component: PostComponent, }) + +function PostComponent() { + const post = Route.useLoaderData() + + return ( +
+

{post.value?.title}

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

{post.value?.title}

+
{post.value?.body}
+
+ ) +} diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/posts/posts-home.tsx b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/posts/posts-home.tsx index 67a4268fae..13529228bb 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,5 +1,4 @@ -import { createFileRoute } from '@tanstack/vue-router' -export const Route = createFileRoute('/posts/')({ +export const Route = createFileRoute({ 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 2a4e8deddd..5942bac97e 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,42 +1,39 @@ -import { defineComponent } from 'vue' -import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' +import { Link, Outlet } 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')({ +export const Route = createFileRoute({ 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/vite-env.d.ts b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/app.spec.ts b/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/app.spec.ts index fbf093cd51..3e5a69ccaa 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/app.spec.ts +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts b/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts b/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/vite.config.ts b/e2e/vue-router/basic-virtual-named-export-config-file-based/vite.config.ts index f02a0c0d95..a5ba51ea2f 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 @@ -11,6 +11,7 @@ export default defineConfig({ tanstackRouter({ target: 'vue', autoCodeSplitting: true, + verboseFileRoutes: false, virtualRouteConfig: './routes.ts', }), vue(), diff --git a/e2e/vue-router/basic-vue-query-file-based/package.json b/e2e/vue-router/basic-vue-query-file-based/package.json index 3b4422d8d8..c98530f42a 100644 --- a/e2e/vue-router/basic-vue-query-file-based/package.json +++ b/e2e/vue-router/basic-vue-query-file-based/package.json @@ -8,27 +8,27 @@ "build": "vite build && vue-tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@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:^", - "redaxios": "catalog:", + "@tanstack/router-plugin": "workspace:^", + "redaxios": "^0.5.1", "tailwindcss": "^4.2.2", "vue": "^3.5.16", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", "typescript": "~5.8.3", - "vite": "^8.0.14", - "vue-tsc": "^3.3.8" + "vite": "^8.0.0", + "vue-tsc": "^3.1.5" } } diff --git a/e2e/vue-router/basic-vue-query-file-based/playwright.config.ts b/e2e/vue-router/basic-vue-query-file-based/playwright.config.ts index fbda9bd451..6e7c123f74 100644 --- a/e2e/vue-router/basic-vue-query-file-based/playwright.config.ts +++ b/e2e/vue-router/basic-vue-query-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -12,15 +17,17 @@ export default defineConfig({ workers: 1, reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic-vue-query-file-based/src/posts.tsx b/e2e/vue-router/basic-vue-query-file-based/src/posts.tsx index 1f6cb8e308..1becc2c242 100644 --- a/e2e/vue-router/basic-vue-query-file-based/src/posts.tsx +++ b/e2e/vue-router/basic-vue-query-file-based/src/posts.tsx @@ -8,7 +8,11 @@ export type PostType = { export class PostNotFoundError extends Error {} -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/vue-router/basic-vue-query-file-based/src/routeTree.gen.ts b/e2e/vue-router/basic-vue-query-file-based/src/routeTree.gen.ts index 0af0e21dbd..9dd7ada796 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,33 +9,29 @@ // Additionally, you should also exclude this file 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 PostsRouteImport } from './routes/posts' -import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' +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 LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' +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' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) const LayoutRoute = LayoutRouteImport.update({ id: '/_layout', getParentRoute: () => rootRouteImport, } as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const LayoutLayout2Route = LayoutLayout2RouteImport.update({ - id: '/_layout-2', - getParentRoute: () => LayoutRoute, -} as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -46,16 +42,20 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ path: '/$postId', getParentRoute: () => PostsRoute, } as any) -const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => LayoutLayout2Route, +const LayoutLayout2Route = LayoutLayout2RouteImport.update({ + id: '/_layout-2', + getParentRoute: () => LayoutRoute, } as any) const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ id: '/layout-b', path: '/layout-b', getParentRoute: () => LayoutLayout2Route, } as any) +const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => LayoutLayout2Route, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -114,11 +114,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } '/_layout': { @@ -128,19 +128,12 @@ declare module '@tanstack/vue-router' { 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: '' + '/': { + id: '/' + path: '/' fullPath: '/' - preLoaderRoute: typeof LayoutLayout2RouteImport - parentRoute: typeof LayoutRoute + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport } '/posts/': { id: '/posts/' @@ -156,12 +149,12 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRoute } - '/_layout/_layout-2/layout-a': { - id: '/_layout/_layout-2/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof LayoutLayout2LayoutARouteImport - parentRoute: typeof LayoutLayout2Route + '/_layout/_layout-2': { + id: '/_layout/_layout-2' + path: '' + fullPath: '/' + preLoaderRoute: typeof LayoutLayout2RouteImport + parentRoute: typeof LayoutRoute } '/_layout/_layout-2/layout-b': { id: '/_layout/_layout-2/layout-b' @@ -170,6 +163,13 @@ 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 e8b66ddf5d..72109fc891 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,4 +1,3 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { ErrorComponent, useRouter } from '@tanstack/vue-router' import { useQuery } from '@tanstack/vue-query' @@ -6,21 +5,6 @@ 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)) @@ -48,3 +32,16 @@ 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 e1c35d59ad..f9e20f99d6 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,45 +1,42 @@ -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/vite-env.d.ts b/e2e/vue-router/basic-vue-query-file-based/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/vue-router/basic-vue-query-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/vue-router/basic-vue-query-file-based/tests/app.spec.ts b/e2e/vue-router/basic-vue-query-file-based/tests/app.spec.ts index 2b42d6d589..d80e8dada5 100644 --- a/e2e/vue-router/basic-vue-query-file-based/tests/app.spec.ts +++ b/e2e/vue-router/basic-vue-query-file-based/tests/app.spec.ts @@ -1,23 +1,24 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' +import { getDummyServerPort } from '@tanstack/router-e2e-utils' +import packageJson from '../package.json' with { type: 'json' } test.beforeEach(async ({ page }) => { await page.goto('/') }) -test('GetPosts with networking disabled', async ({ page, context }) => { - await page.goto('about:blank') - await context.setOffline(true) - const { status, posts, post } = await page.evaluate(async () => { - const response = await fetch('https://jsonplaceholder.typicode.com/posts') - const posts = await response.json() - const post = await fetch( - 'https://jsonplaceholder.typicode.com/posts/1', - ).then((r) => r.json()) - return { status: response.status, posts, post } - }) - expect(status).toBe(200) +test('GetPosts', async () => { + const port = await getDummyServerPort(packageJson.name) + const res = await fetch(`http://localhost:${port}/posts`) + + expect(res.status).toBe(200) + + const posts = await res.json() + expect(posts.length).toBeGreaterThan(0) + + const postRes = await fetch(`http://localhost:${port}/posts/1`) + expect(postRes.status).toBe(200) + const post = await postRes.json() expect(post).toEqual(posts[0]) }) diff --git a/e2e/vue-router/basic-vue-query-file-based/tests/setup/global.setup.ts b/e2e/vue-router/basic-vue-query-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/basic-vue-query-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic-vue-query-file-based/tests/setup/global.teardown.ts b/e2e/vue-router/basic-vue-query-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/basic-vue-query-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic-vue-query-file-based/tsconfig.json b/e2e/vue-router/basic-vue-query-file-based/tsconfig.json index 28889522fc..123a2f4122 100644 --- a/e2e/vue-router/basic-vue-query-file-based/tsconfig.json +++ b/e2e/vue-router/basic-vue-query-file-based/tsconfig.json @@ -10,7 +10,7 @@ "skipLibCheck": true, "noEmit": true, "resolveJsonModule": true, - "types": ["vite/client", "node"] + "types": ["vite/client"] }, "include": ["src", "tests"], "exclude": ["node_modules", "dist"] diff --git a/e2e/vue-router/basic-vue-query/package.json b/e2e/vue-router/basic-vue-query/package.json index 68f1a8c9ea..b9e12f2355 100644 --- a/e2e/vue-router/basic-vue-query/package.json +++ b/e2e/vue-router/basic-vue-query/package.json @@ -8,7 +8,7 @@ "build": "vite build && vue-tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -16,17 +16,17 @@ "@tanstack/vue-query-devtools": "^6.1.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "catalog:", + "redaxios": "^0.5.1", "tailwindcss": "^4.2.2", "vue": "^3.5.16" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", "typescript": "~5.8.3", - "vite": "^8.0.14", - "vue-tsc": "^3.3.8" + "vite": "^8.0.0", + "vue-tsc": "^3.1.5" } } diff --git a/e2e/vue-router/basic-vue-query/playwright.config.ts b/e2e/vue-router/basic-vue-query/playwright.config.ts index 4eead86444..836ea41bd8 100644 --- a/e2e/vue-router/basic-vue-query/playwright.config.ts +++ b/e2e/vue-router/basic-vue-query/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic-vue-query/src/main.tsx b/e2e/vue-router/basic-vue-query/src/main.tsx index 3235f26ce3..4f862a9b31 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, defineComponent } from 'vue' +import { createApp } from 'vue' import { ErrorComponent, Link, @@ -108,21 +108,6 @@ 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', @@ -152,6 +137,19 @@ 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 d42d3d49dc..eb844bc68d 100644 --- a/e2e/vue-router/basic-vue-query/src/posts.lazy.tsx +++ b/e2e/vue-router/basic-vue-query/src/posts.lazy.tsx @@ -1,42 +1,39 @@ -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 69e1814af5..18f8a9f93f 100644 --- a/e2e/vue-router/basic-vue-query/src/posts.ts +++ b/e2e/vue-router/basic-vue-query/src/posts.ts @@ -9,7 +9,11 @@ type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} const fetchPosts = async () => { console.info('Fetching posts...') diff --git a/e2e/vue-router/basic-vue-query/src/vite-env.d.ts b/e2e/vue-router/basic-vue-query/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/vue-router/basic-vue-query/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/vue-router/basic-vue-query/tests/app.spec.ts b/e2e/vue-router/basic-vue-query/tests/app.spec.ts index fbf093cd51..3e5a69ccaa 100644 --- a/e2e/vue-router/basic-vue-query/tests/app.spec.ts +++ b/e2e/vue-router/basic-vue-query/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-router/basic-vue-query/tests/setup/global.setup.ts b/e2e/vue-router/basic-vue-query/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/basic-vue-query/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic-vue-query/tests/setup/global.teardown.ts b/e2e/vue-router/basic-vue-query/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/basic-vue-query/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic/package.json b/e2e/vue-router/basic/package.json index 1b57dae772..f09ba20e9e 100644 --- a/e2e/vue-router/basic/package.json +++ b/e2e/vue-router/basic/package.json @@ -8,22 +8,22 @@ "build": "vite build && vue-tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "catalog:", + "redaxios": "^0.5.1", "tailwindcss": "^4.2.2", "vue": "^3.5.16" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", "@vitejs/plugin-vue-jsx": "^5.1.5", "typescript": "~5.8.3", - "vite": "^8.0.14", - "vue-tsc": "^3.3.8" + "vite": "^8.0.0", + "vue-tsc": "^3.1.5" } } diff --git a/e2e/vue-router/basic/playwright.config.ts b/e2e/vue-router/basic/playwright.config.ts index 4eead86444..836ea41bd8 100644 --- a/e2e/vue-router/basic/playwright.config.ts +++ b/e2e/vue-router/basic/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic/src/main.tsx b/e2e/vue-router/basic/src/main.tsx index c2293018fc..3e5ac6f1e0 100644 --- a/e2e/vue-router/basic/src/main.tsx +++ b/e2e/vue-router/basic/src/main.tsx @@ -1,4 +1,4 @@ -import { createApp, defineComponent } from 'vue' +import { createApp } from 'vue' import { ErrorComponent, Link, @@ -133,20 +133,6 @@ 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', @@ -155,6 +141,18 @@ 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', @@ -317,30 +315,14 @@ 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: ParamsNamedFoo, -}) - -const ParamsNamedFooMarkdown = defineComponent({ - setup() { - const p = paramsPsNamedFooPrefixRoute.useParams() - return () => ( + component: function ParamsNamedFoo() { + const p = paramsPsNamedFooRoute.useParams() + return (
-

ParamsNamedFooPrefix

+

ParamsNamedFoo

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

ParamsNamedFooSuffix

+

ParamsNamedFooPrefix

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

ParamsNamedFooSuffix

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

ParamsWildcardSplat

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

ParamsWildcardSplatPrefix

+

ParamsWildcardSplat

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

ParamsWildcardSplatSuffix

+

ParamsWildcardSplatPrefix

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

ParamsWildcardSplatSuffix

+
{JSON.stringify(p.value)}
+
+ ) + }, }) 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 a236404d84..b2df740010 100644 --- a/e2e/vue-router/basic/src/posts.lazy.tsx +++ b/e2e/vue-router/basic/src/posts.lazy.tsx @@ -1,39 +1,36 @@ -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 f72d16fee3..e859645746 100644 --- a/e2e/vue-router/basic/src/posts.ts +++ b/e2e/vue-router/basic/src/posts.ts @@ -8,7 +8,11 @@ type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPosts = async () => { console.info('Fetching posts...') diff --git a/e2e/vue-router/basic/src/vite-env.d.ts b/e2e/vue-router/basic/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/vue-router/basic/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/vue-router/basic/tests/app.spec.ts b/e2e/vue-router/basic/tests/app.spec.ts index 9c0a6b6901..ec0e24d8a4 100644 --- a/e2e/vue-router/basic/tests/app.spec.ts +++ b/e2e/vue-router/basic/tests/app.spec.ts @@ -1,7 +1,8 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from '../package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-router/basic/tests/params.spec.ts b/e2e/vue-router/basic/tests/params.spec.ts index f673138047..ac18f39864 100644 --- a/e2e/vue-router/basic/tests/params.spec.ts +++ b/e2e/vue-router/basic/tests/params.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.describe('params operations + prefix/suffix', () => { test.beforeEach(async ({ page }) => { diff --git a/e2e/vue-router/basic/tests/setup/global.setup.ts b/e2e/vue-router/basic/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/basic/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic/tests/setup/global.teardown.ts b/e2e/vue-router/basic/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/basic/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/generator-cli-only/package.json b/e2e/vue-router/generator-cli-only/package.json index f9324643ac..3219f78a2c 100644 --- a/e2e/vue-router/generator-cli-only/package.json +++ b/e2e/vue-router/generator-cli-only/package.json @@ -8,24 +8,24 @@ "build": "tsr generate && vite build && tsc --noEmit", "preview": "vite preview", "start": "tsr generate && vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/router-cli": "workspace:^", - "redaxios": "catalog:", + "redaxios": "^0.5.1", "vue": "^3.5.16", "tailwindcss": "^4.2.2" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", "typescript": "~5.8.3", - "vite": "^8.0.14", - "vue-tsc": "^3.3.8" + "vite": "^8.0.0", + "vue-tsc": "^3.1.5" } } diff --git a/e2e/vue-router/generator-cli-only/playwright.config.ts b/e2e/vue-router/generator-cli-only/playwright.config.ts index 4eead86444..c9d9a76ae7 100644 --- a/e2e/vue-router/generator-cli-only/playwright.config.ts +++ b/e2e/vue-router/generator-cli-only/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/generator-cli-only/src/posts.ts b/e2e/vue-router/generator-cli-only/src/posts.ts index f72d16fee3..e859645746 100644 --- a/e2e/vue-router/generator-cli-only/src/posts.ts +++ b/e2e/vue-router/generator-cli-only/src/posts.ts @@ -8,7 +8,11 @@ type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPosts = async () => { console.info('Fetching posts...') diff --git a/e2e/vue-router/generator-cli-only/src/routeTree.gen.ts b/e2e/vue-router/generator-cli-only/src/routeTree.gen.ts index decb53754c..c769c841f0 100644 --- a/e2e/vue-router/generator-cli-only/src/routeTree.gen.ts +++ b/e2e/vue-router/generator-cli-only/src/routeTree.gen.ts @@ -9,20 +9,15 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as PostsRouteRouteImport } from './routes/posts.route' -import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-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 PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +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' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, @@ -32,11 +27,11 @@ const PostsRouteRoute = PostsRouteRouteImport.update({ path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const PathlessLayoutNestedLayoutRoute = - PathlessLayoutNestedLayoutRouteImport.update({ - id: '/_nested-layout', - getParentRoute: () => PathlessLayoutRoute, - } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -47,11 +42,10 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ path: '/$postId', getParentRoute: () => PostsRouteRoute, } as any) -const PathlessLayoutNestedLayoutRouteARoute = - PathlessLayoutNestedLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, +const PathlessLayoutNestedLayoutRoute = + PathlessLayoutNestedLayoutRouteImport.update({ + id: '/_nested-layout', + getParentRoute: () => PathlessLayoutRoute, } as any) const PathlessLayoutNestedLayoutRouteBRoute = PathlessLayoutNestedLayoutRouteBRouteImport.update({ @@ -59,6 +53,12 @@ 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,13 +117,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/_pathlessLayout': { id: '/_pathlessLayout' path: '' @@ -138,12 +131,12 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' - path: '' + '/': { + id: '/' + path: '/' fullPath: '/' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport } '/posts/': { id: '/posts/' @@ -159,12 +152,12 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRouteRoute } - '/_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': { + id: '/_pathlessLayout/_nested-layout' + path: '' + fullPath: '/' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -173,6 +166,13 @@ 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 bb2d728afd..f4f1b04f88 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,21 +1,7 @@ -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, @@ -28,3 +14,14 @@ 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 518bdc3d70..eaaa35fd5c 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,42 +1,39 @@ -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/vite-env.d.ts b/e2e/vue-router/generator-cli-only/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/vue-router/generator-cli-only/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/vue-router/generator-cli-only/tests/app.spec.ts b/e2e/vue-router/generator-cli-only/tests/app.spec.ts index ced5ac9310..5a83a314f2 100644 --- a/e2e/vue-router/generator-cli-only/tests/app.spec.ts +++ b/e2e/vue-router/generator-cli-only/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-router/generator-cli-only/tests/setup/global.setup.ts b/e2e/vue-router/generator-cli-only/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/generator-cli-only/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/generator-cli-only/tests/setup/global.teardown.ts b/e2e/vue-router/generator-cli-only/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/generator-cli-only/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/js-only-file-based/package.json b/e2e/vue-router/js-only-file-based/package.json index cda098978c..1e3bac6cd5 100644 --- a/e2e/vue-router/js-only-file-based/package.json +++ b/e2e/vue-router/js-only-file-based/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -17,15 +17,15 @@ "@tanstack/vue-query-devtools": "^6.1.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "catalog:", + "redaxios": "^0.5.1", "tailwindcss": "^4.2.2", "vue": "^3.5.16" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", - "vite": "^8.0.14" + "vite": "^8.0.0" } } diff --git a/e2e/vue-router/js-only-file-based/playwright.config.ts b/e2e/vue-router/js-only-file-based/playwright.config.ts index 0925936d55..4f93bc1413 100644 --- a/e2e/vue-router/js-only-file-based/playwright.config.ts +++ b/e2e/vue-router/js-only-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -13,15 +18,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/js-only-file-based/src/posts.js b/e2e/vue-router/js-only-file-based/src/posts.js index 36c1c281f6..979e5e381c 100644 --- a/e2e/vue-router/js-only-file-based/src/posts.js +++ b/e2e/vue-router/js-only-file-based/src/posts.js @@ -2,7 +2,11 @@ import axios from 'redaxios' export class NotFoundError extends Error {} -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPosts = async () => { console.info('Fetching posts...') diff --git a/e2e/vue-router/js-only-file-based/src/routeTree.gen.ts b/e2e/vue-router/js-only-file-based/src/routeTree.gen.ts index decb53754c..c769c841f0 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,20 +9,15 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as PostsRouteRouteImport } from './routes/posts.route' -import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-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 PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +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' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, @@ -32,11 +27,11 @@ const PostsRouteRoute = PostsRouteRouteImport.update({ path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const PathlessLayoutNestedLayoutRoute = - PathlessLayoutNestedLayoutRouteImport.update({ - id: '/_nested-layout', - getParentRoute: () => PathlessLayoutRoute, - } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -47,11 +42,10 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ path: '/$postId', getParentRoute: () => PostsRouteRoute, } as any) -const PathlessLayoutNestedLayoutRouteARoute = - PathlessLayoutNestedLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, +const PathlessLayoutNestedLayoutRoute = + PathlessLayoutNestedLayoutRouteImport.update({ + id: '/_nested-layout', + getParentRoute: () => PathlessLayoutRoute, } as any) const PathlessLayoutNestedLayoutRouteBRoute = PathlessLayoutNestedLayoutRouteBRouteImport.update({ @@ -59,6 +53,12 @@ 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,13 +117,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/_pathlessLayout': { id: '/_pathlessLayout' path: '' @@ -138,12 +131,12 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' - path: '' + '/': { + id: '/' + path: '/' fullPath: '/' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport } '/posts/': { id: '/posts/' @@ -159,12 +152,12 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRouteRoute } - '/_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': { + id: '/_pathlessLayout/_nested-layout' + path: '' + fullPath: '/' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -173,6 +166,13 @@ 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 05599a6780..b769e23862 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,22 +1,8 @@ -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, @@ -29,3 +15,14 @@ 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 5925dbed54..c1fef7213d 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,44 +1,41 @@ -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/vite-env.d.ts b/e2e/vue-router/js-only-file-based/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/vue-router/js-only-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/vue-router/js-only-file-based/tests/app.spec.ts b/e2e/vue-router/js-only-file-based/tests/app.spec.ts index ced5ac9310..5a83a314f2 100644 --- a/e2e/vue-router/js-only-file-based/tests/app.spec.ts +++ b/e2e/vue-router/js-only-file-based/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-router/js-only-file-based/tests/setup/global.setup.ts b/e2e/vue-router/js-only-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/js-only-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/js-only-file-based/tests/setup/global.teardown.ts b/e2e/vue-router/js-only-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/js-only-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/rspack-basic-file-based/package.json b/e2e/vue-router/rspack-basic-file-based/package.json index 93439f7d5b..81695c8269 100644 --- a/e2e/vue-router/rspack-basic-file-based/package.json +++ b/e2e/vue-router/rspack-basic-file-based/package.json @@ -7,28 +7,27 @@ "build": "rsbuild build && tsc --noEmit", "preview": "rsbuild preview", "start": "rsbuild preview", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "catalog:", + "redaxios": "^0.5.1", "vue": "^3.5.16" }, "devDependencies": { - "@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", + "@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.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@tanstack/router-plugin": "workspace:^", "@tanstack/virtual-file-routes": "workspace:^", "postcss": "^8.5.1", "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vue-tsc": "^3.3.8" + "typescript": "^5.7.2", + "vue-tsc": "^3.1.5" } } diff --git a/e2e/vue-router/rspack-basic-file-based/playwright.config.ts b/e2e/vue-router/rspack-basic-file-based/playwright.config.ts index 4eead86444..5f20415459 100644 --- a/e2e/vue-router/rspack-basic-file-based/playwright.config.ts +++ b/e2e/vue-router/rspack-basic-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `PUBLIC_NODE_ENV="test" PUBLIC_EXTERNAL_PORT=${EXTERNAL_PORT} PUBLIC_SERVER_PORT=${PORT} pnpm build && PUBLIC_NODE_ENV="test" PUBLIC_EXTERNAL_PORT=${EXTERNAL_PORT} PUBLIC_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/rspack-basic-file-based/rsbuild.config.ts b/e2e/vue-router/rspack-basic-file-based/rsbuild.config.ts index c91449b6c3..d5e4b7456c 100644 --- a/e2e/vue-router/rspack-basic-file-based/rsbuild.config.ts +++ b/e2e/vue-router/rspack-basic-file-based/rsbuild.config.ts @@ -12,6 +12,19 @@ export default defineConfig({ pluginVue(), pluginVueJsx(), ], + source: { + define: { + // Rsbuild only defines `import.meta.env.PUBLIC_*` when the env var exists. + // When it doesn't, rspack can transform `import.meta.env` to `void 0`, which + // makes `import.meta.env.PUBLIC_*` crash at runtime. + 'import.meta.env.PUBLIC_NODE_ENV': JSON.stringify( + process.env.PUBLIC_NODE_ENV ?? '', + ), + 'import.meta.env.PUBLIC_EXTERNAL_PORT': JSON.stringify( + process.env.PUBLIC_EXTERNAL_PORT ?? '', + ), + }, + }, tools: { rspack: { plugins: [tanstackRouter({ target: 'vue', autoCodeSplitting: true })], diff --git a/e2e/vue-router/rspack-basic-file-based/src/posts.tsx b/e2e/vue-router/rspack-basic-file-based/src/posts.tsx index 5f5463a668..0b557a0f65 100644 --- a/e2e/vue-router/rspack-basic-file-based/src/posts.tsx +++ b/e2e/vue-router/rspack-basic-file-based/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.PUBLIC_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.PUBLIC_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/vue-router/rspack-basic-file-based/src/routes/posts.$postId.tsx b/e2e/vue-router/rspack-basic-file-based/src/routes/posts.$postId.tsx index a86ea0762f..e271c139f5 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,4 +1,3 @@ -import { defineComponent } from 'vue' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import { fetchPost } from '../posts' import type { ErrorComponentProps } from '@tanstack/vue-router' @@ -7,19 +6,6 @@ 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, @@ -28,3 +14,14 @@ 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 90744370ff..653918c370 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,43 +1,40 @@ -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/vite-env.d.ts b/e2e/vue-router/rspack-basic-file-based/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/vue-router/rspack-basic-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/vue-router/rspack-basic-file-based/tests/app.spec.ts b/e2e/vue-router/rspack-basic-file-based/tests/app.spec.ts index d230263bfe..10beff655f 100644 --- a/e2e/vue-router/rspack-basic-file-based/tests/app.spec.ts +++ b/e2e/vue-router/rspack-basic-file-based/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-router/rspack-basic-file-based/tests/setup/global.setup.ts b/e2e/vue-router/rspack-basic-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/rspack-basic-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/rspack-basic-file-based/tests/setup/global.teardown.ts b/e2e/vue-router/rspack-basic-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/rspack-basic-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/rspack-basic-file-based/tsconfig.json b/e2e/vue-router/rspack-basic-file-based/tsconfig.json index 8fc6c76d61..25149257a3 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", "tests"], + "include": ["src", "playwright.config.ts", "tests"], "exclude": ["node_modules", "dist"] } diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/package.json b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/package.json index 536435a09e..48f2c2715f 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,28 +7,27 @@ "build": "rsbuild build && tsc --noEmit", "preview": "rsbuild preview", "start": "rsbuild preview", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "catalog:", + "redaxios": "^0.5.1", "vue": "^3.5.16" }, "devDependencies": { - "@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", + "@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.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@tanstack/router-plugin": "workspace:^", "@tanstack/virtual-file-routes": "workspace:^", "postcss": "^8.5.1", "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vue-tsc": "^3.3.8" + "typescript": "^5.7.2", + "vue-tsc": "^3.1.5" } } diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/playwright.config.ts b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/playwright.config.ts index 1c1d021f2f..bf3adc082c 100644 --- a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/playwright.config.ts +++ b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm start --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `PUBLIC_NODE_ENV="test" PUBLIC_EXTERNAL_PORT=${EXTERNAL_PORT} PUBLIC_SERVER_PORT=${PORT} pnpm build && PUBLIC_SERVER_PORT=${PORT} pnpm start --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/rsbuild.config.ts b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/rsbuild.config.ts index e5c7e8b77e..b09f6ccda8 100644 --- a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/rsbuild.config.ts +++ b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/rsbuild.config.ts @@ -12,6 +12,19 @@ export default defineConfig({ pluginVue(), pluginVueJsx(), ], + source: { + define: { + // Rsbuild only defines `import.meta.env.PUBLIC_*` when the env var exists. + // When it doesn't, rspack can transform `import.meta.env` to `void 0`, which + // makes `import.meta.env.PUBLIC_*` crash at runtime. + 'import.meta.env.PUBLIC_NODE_ENV': JSON.stringify( + process.env.PUBLIC_NODE_ENV ?? '', + ), + 'import.meta.env.PUBLIC_EXTERNAL_PORT': JSON.stringify( + process.env.PUBLIC_EXTERNAL_PORT ?? '', + ), + }, + }, tools: { rspack: { plugins: [ diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/posts.tsx b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/posts.tsx index 5f5463a668..0b557a0f65 100644 --- a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/posts.tsx +++ b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.PUBLIC_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.PUBLIC_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/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 5e3fe4d130..cb1924e993 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,4 +1,3 @@ -import { defineComponent } from 'vue' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import { fetchPost } from '../../posts' import type { ErrorComponentProps } from '@tanstack/vue-router' @@ -7,19 +6,6 @@ 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, @@ -28,3 +14,14 @@ 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 2a4e8deddd..265faaf650 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,42 +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) => { - 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/vite-env.d.ts b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts index d230263bfe..10beff655f 100644 --- a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts +++ b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/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 ff457aa547..23855253ad 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", "tests", "./routes.ts"], + "include": ["src", "playwright.config.ts", "tests", "./routes.ts"], "exclude": ["node_modules", "dist"] } 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 new file mode 100644 index 0000000000..1f78534259 --- /dev/null +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/index-BwsVWHwV.js @@ -0,0 +1,18 @@ +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 new file mode 100644 index 0000000000..b6e247a9c9 --- /dev/null +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/index-ElfLiipA.css @@ -0,0 +1 @@ +/*! 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 new file mode 100644 index 0000000000..7dff2a5190 --- /dev/null +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/index-rPfEOKs3.js @@ -0,0 +1 @@ +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 new file mode 100644 index 0000000000..b2ab5a4389 --- /dev/null +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/lazy-page.lazy-BzoMuhUY.js @@ -0,0 +1 @@ +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 new file mode 100644 index 0000000000..ab267814ce --- /dev/null +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/lazy-with-loader-page.lazy-BzLmn584.js @@ -0,0 +1 @@ +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 new file mode 100644 index 0000000000..ec26f71d98 --- /dev/null +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/normal-page-BPOVyYTF.js @@ -0,0 +1 @@ +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 new file mode 100644 index 0000000000..67ce6cd937 --- /dev/null +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/page-with-search-BhJv4yJI.js @@ -0,0 +1 @@ +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 new file mode 100644 index 0000000000..89ed1c6988 --- /dev/null +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/scroll-block-BAas_Ct-.js @@ -0,0 +1 @@ +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 new file mode 100644 index 0000000000..82d2cac67f --- /dev/null +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/virtual-page.lazy-BCqvdivF.js @@ -0,0 +1 @@ +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 new file mode 100644 index 0000000000..2a9c6c3574 --- /dev/null +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/index.html @@ -0,0 +1,12 @@ + + + + + + + + + +
+ + diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/package.json b/e2e/vue-router/scroll-restoration-sandbox-vite/package.json index d071ee546a..40423a1c63 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/package.json +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/package.json @@ -11,35 +11,26 @@ "start": "vite", "test:e2e:browser": "VITE_APP_HISTORY=browser playwright test --config=playwright.browser.config.ts --project=chromium", "test:e2e:hash": "VITE_APP_HISTORY=hash playwright test --config=playwright.hash.config.ts --project=chromium", - "test:e2e": "pnpm run test:e2e:browser && pnpm run test:e2e:hash" + "test:e2e": "rm -rf port*.txt; pnpm run test:e2e:browser && pnpm run test:e2e:hash" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/router-plugin": "workspace:^", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "catalog:", + "@tanstack/zod-adapter": "workspace:^", + "redaxios": "^0.5.1", "tailwindcss": "^4.2.2", "vue": "^3.5.16", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", "typescript": "~5.8.3", - "vite": "^8.0.14", - "vue-tsc": "^3.3.8" - }, - "nx": { - "targets": { - "test:e2e": { - "outputs": [ - "...", - "{projectRoot}/dist-hash" - ] - } - } + "vite": "^8.0.0", + "vue-tsc": "^3.1.5" } } diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts b/e2e/vue-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts index e2681daea5..9d7691f0fd 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts @@ -1,7 +1,15 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, + resolveRuntimeSuffix, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort( + packageJson.name + `-${resolveRuntimeSuffix('browser')}`, +) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +20,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_APP_HISTORY=browser pnpm build && VITE_APP_HISTORY=browser pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} VITE_APP_HISTORY=browser pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} VITE_APP_HISTORY=browser pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts b/e2e/vue-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts index 445616b9bd..80a340cef4 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts @@ -1,7 +1,15 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, + resolveRuntimeSuffix, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort( + packageJson.name + `-${resolveRuntimeSuffix('hash')}`, +) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +20,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_APP_HISTORY=hash vite build --outDir dist-hash && VITE_APP_HISTORY=hash pnpm preview --port ${PORT} --outDir dist-hash`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} VITE_APP_HISTORY=hash vite build --outDir dist-hash && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} VITE_APP_HISTORY=hash pnpm preview --port ${PORT} --outDir dist-hash`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/src/posts.tsx b/e2e/vue-router/scroll-restoration-sandbox-vite/src/posts.tsx index bc56dff904..c6cba486ab 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/src/posts.tsx +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/src/posts.tsx @@ -12,7 +12,11 @@ export type PostType = { export class PostNotFoundError extends Error {} -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/src/routeTree.gen.ts b/e2e/vue-router/scroll-restoration-sandbox-vite/src/routeTree.gen.ts index e85be2bf37..69dda324fe 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 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' +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' const testsVirtualPageLazyRouteImport = createFileRoute( '/(tests)/virtual-page', @@ -26,13 +26,23 @@ const IndexRoute = IndexRouteImport.update({ path: '/', getParentRoute: () => rootRouteImport, } as any) -const testsLazyPageRoute = testsLazyPageRouteImport +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)) +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) const testsLazyWithLoaderPageRoute = testsLazyWithLoaderPageRouteImport .update({ id: '/(tests)/lazy-with-loader-page', @@ -42,23 +52,13 @@ const testsLazyWithLoaderPageRoute = testsLazyWithLoaderPageRouteImport .lazy(() => import('./routes/(tests)/lazy-with-loader-page.lazy').then((d) => d.Route), ) -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 +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)) + .lazy(() => import('./routes/(tests)/lazy-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)/lazy-page': { - id: '/(tests)/lazy-page' - path: '/lazy-page' - fullPath: '/lazy-page' - preLoaderRoute: typeof testsLazyPageRouteImport - parentRoute: typeof rootRouteImport - } - '/(tests)/lazy-with-loader-page': { - id: '/(tests)/lazy-with-loader-page' - path: '/lazy-with-loader-page' - fullPath: '/lazy-with-loader-page' - preLoaderRoute: typeof testsLazyWithLoaderPageRouteImport - parentRoute: typeof rootRouteImport - } - '/(tests)/normal-page': { - id: '/(tests)/normal-page' - path: '/normal-page' - fullPath: '/normal-page' - preLoaderRoute: typeof testsNormalPageRouteImport + '/(tests)/virtual-page': { + id: '/(tests)/virtual-page' + path: '/virtual-page' + fullPath: '/virtual-page' + preLoaderRoute: typeof testsVirtualPageLazyRouteImport parentRoute: typeof rootRouteImport } '/(tests)/page-with-search': { @@ -158,11 +144,25 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof testsPageWithSearchRouteImport parentRoute: typeof rootRouteImport } - '/(tests)/virtual-page': { - id: '/(tests)/virtual-page' - path: '/virtual-page' - fullPath: '/virtual-page' - preLoaderRoute: typeof testsVirtualPageLazyRouteImport + '/(tests)/normal-page': { + id: '/(tests)/normal-page' + path: '/normal-page' + fullPath: '/normal-page' + preLoaderRoute: typeof testsNormalPageRouteImport + parentRoute: typeof rootRouteImport + } + '/(tests)/lazy-with-loader-page': { + id: '/(tests)/lazy-with-loader-page' + path: '/lazy-with-loader-page' + fullPath: '/lazy-with-loader-page' + preLoaderRoute: typeof testsLazyWithLoaderPageRouteImport + parentRoute: typeof rootRouteImport + } + '/(tests)/lazy-page': { + id: '/(tests)/lazy-page' + path: '/lazy-page' + fullPath: '/lazy-page' + preLoaderRoute: typeof testsLazyPageRouteImport 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 f608b9e379..3e1ec1eeba 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,9 +1,10 @@ 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: z.object({ where: z.string() }), + validateSearch: zodValidator(z.object({ where: z.string() })), component: Component, }) 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 deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/tests/app.spec.ts b/e2e/vue-router/scroll-restoration-sandbox-vite/tests/app.spec.ts index 067f0341c4..5f226c6db3 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/tests/app.spec.ts +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' import { toRuntimePath } from '@tanstack/router-e2e-utils' test('Smoke - Renders home', async ({ page }) => { diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/tests/setup/global.setup.ts b/e2e/vue-router/scroll-restoration-sandbox-vite/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/tests/setup/global.teardown.ts b/e2e/vue-router/scroll-restoration-sandbox-vite/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/tsconfig.json b/e2e/vue-router/scroll-restoration-sandbox-vite/tsconfig.json index b47cca9589..3e5b04987f 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/tsconfig.json +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/tsconfig.json @@ -12,5 +12,5 @@ "allowJs": true, "types": ["vite/client", "node"] }, - "exclude": ["node_modules", "dist", "dist-hash"] + "exclude": ["node_modules", "dist"] } diff --git a/e2e/vue-router/sentry-integration/package.json b/e2e/vue-router/sentry-integration/package.json index 045ddd99be..001e8eb1dd 100644 --- a/e2e/vue-router/sentry-integration/package.json +++ b/e2e/vue-router/sentry-integration/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@sentry/vue": "^10.32.0", @@ -17,16 +17,16 @@ "@tailwindcss/vite": "^4.2.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "catalog:", + "redaxios": "^0.5.1", "tailwindcss": "^4.2.2", "vue": "^3.5.16" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", "@vitejs/plugin-vue-jsx": "^5.1.5", "typescript": "~5.8.3", - "vite": "^8.0.14", - "vue-tsc": "^3.3.8" + "vite": "^8.0.0", + "vue-tsc": "^3.1.5" } } diff --git a/e2e/vue-router/sentry-integration/playwright.config.ts b/e2e/vue-router/sentry-integration/playwright.config.ts index 6a684ac89e..0c5cee43e4 100644 --- a/e2e/vue-router/sentry-integration/playwright.config.ts +++ b/e2e/vue-router/sentry-integration/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/sentry-integration/src/vite-env.d.ts b/e2e/vue-router/sentry-integration/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/vue-router/sentry-integration/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/vue-router/view-transitions/package.json b/e2e/vue-router/view-transitions/package.json index 21a0f1d8a0..73d7f05146 100644 --- a/e2e/vue-router/view-transitions/package.json +++ b/e2e/vue-router/view-transitions/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -17,17 +17,17 @@ "@tanstack/vue-query-devtools": "^6.1.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "catalog:", + "redaxios": "^0.5.1", "tailwindcss": "^4.2.2", "vue": "^3.5.16" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", "typescript": "~5.8.3", - "vite": "^8.0.14", - "vue-tsc": "^3.3.8" + "vite": "^8.0.0", + "vue-tsc": "^3.1.5" } } diff --git a/e2e/vue-router/view-transitions/playwright.config.ts b/e2e/vue-router/view-transitions/playwright.config.ts index 4eead86444..c5de6b5611 100644 --- a/e2e/vue-router/view-transitions/playwright.config.ts +++ b/e2e/vue-router/view-transitions/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,10 +22,13 @@ export default defineConfig({ baseURL, }, + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/view-transitions/src/routeTree.gen.ts b/e2e/vue-router/view-transitions/src/routeTree.gen.ts index 04708c29a8..465362a7a2 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 IndexRouteImport } from './routes/index' -import { Route as ExploreRouteImport } from './routes/explore' 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 PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const HowItWorksRoute = HowItWorksRouteImport.update({ + id: '/how-it-works', + path: '/how-it-works', 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 { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/how-it-works': { + id: '/how-it-works' + path: '/how-it-works' + fullPath: '/how-it-works' + preLoaderRoute: typeof HowItWorksRouteImport parentRoute: typeof rootRouteImport } '/explore': { @@ -115,13 +115,6 @@ 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' @@ -129,6 +122,13 @@ 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 a86ea0762f..e271c139f5 100644 --- a/e2e/vue-router/view-transitions/src/routes/posts.$postId.tsx +++ b/e2e/vue-router/view-transitions/src/routes/posts.$postId.tsx @@ -1,4 +1,3 @@ -import { defineComponent } from 'vue' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import { fetchPost } from '../posts' import type { ErrorComponentProps } from '@tanstack/vue-router' @@ -7,19 +6,6 @@ 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, @@ -28,3 +14,14 @@ 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 6802b073f6..01d90b7ad6 100644 --- a/e2e/vue-router/view-transitions/src/routes/posts.route.tsx +++ b/e2e/vue-router/view-transitions/src/routes/posts.route.tsx @@ -1,46 +1,43 @@ -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/vite-env.d.ts b/e2e/vue-router/view-transitions/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/vue-router/view-transitions/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/vue-router/view-transitions/tests/app.spec.ts b/e2e/vue-router/view-transitions/tests/app.spec.ts index 6c1ccf1a6e..472bd6ed0b 100644 --- a/e2e/vue-router/view-transitions/tests/app.spec.ts +++ b/e2e/vue-router/view-transitions/tests/app.spec.ts @@ -1,4 +1,4 @@ -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-router/view-transitions/tests/setup/global.setup.ts b/e2e/vue-router/view-transitions/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/view-transitions/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/view-transitions/tests/setup/global.teardown.ts b/e2e/vue-router/view-transitions/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/view-transitions/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/view-transitions/tests/view-transitions.spec.ts b/e2e/vue-router/view-transitions/tests/view-transitions.spec.ts index e62662a1d2..31d8b12b04 100644 --- a/e2e/vue-router/view-transitions/tests/view-transitions.spec.ts +++ b/e2e/vue-router/view-transitions/tests/view-transitions.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.addInitScript(() => { diff --git a/e2e/vue-start/basic-auth/package.json b/e2e/vue-start/basic-auth/package.json index 7f6fb798da..546013eacc 100644 --- a/e2e/vue-start/basic-auth/package.json +++ b/e2e/vue-start/basic-auth/package.json @@ -10,7 +10,7 @@ "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", "prisma-generate": "prisma generate", - "test:e2e": "mkdir -p .tmp; rm -f .tmp/dev.db .tmp/dev.db-journal .tmp/dev.db-wal .tmp/dev.db-shm; export DATABASE_URL=file:./.tmp/dev.db; pnpm run prisma-generate && pnpm exec prisma migrate deploy && playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; mkdir -p .tmp; rm -f .tmp/dev.db .tmp/dev.db-journal .tmp/dev.db-wal .tmp/dev.db-shm; export DATABASE_URL=file:./.tmp/dev.db; pnpm run prisma-generate && pnpm exec prisma migrate deploy && playwright test --project=chromium" }, "dependencies": { "@libsql/client": "^0.15.15", @@ -19,35 +19,22 @@ "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-start": "workspace:^", - "iron-session": "^9.0.1", - "redaxios": "catalog:", - "tailwind-merge": "^3.6.0", + "redaxios": "^0.5.1", + "tailwind-merge": "^2.6.0", + "vite": "^8.0.0", "vue": "^3.5.25" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@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", "prisma": "^7.0.0", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" - }, - "nx": { - "targets": { - "test:e2e": { - "outputs": [ - "...", - "{projectRoot}/.tmp", - "{projectRoot}/src/prisma-generated" - ] - } - } + "typescript": "^5.7.2", + "@vitejs/plugin-vue": "^6.0.5", + "@vitejs/plugin-vue-jsx": "^5.1.5" } } diff --git a/e2e/vue-start/basic-auth/playwright.config.ts b/e2e/vue-start/basic-auth/playwright.config.ts index 82678ac00b..18b8905468 100644 --- a/e2e/vue-start/basic-auth/playwright.config.ts +++ b/e2e/vue-start/basic-auth/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-start/basic-auth/src/components/DefaultCatchBoundary.tsx b/e2e/vue-start/basic-auth/src/components/DefaultCatchBoundary.tsx index 0687372ae0..e11970b600 100644 --- a/e2e/vue-start/basic-auth/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/basic-auth/src/components/DefaultCatchBoundary.tsx @@ -1,61 +1,53 @@ -import { defineComponent } from 'vue' -import type { PropType } from 'vue' import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, useRouter, } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' -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 - - )} -
-
- ) - } - }, -}) +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 + + )} +
+
+ ) +} diff --git a/e2e/vue-start/basic-auth/src/routeTree.gen.ts b/e2e/vue-start/basic-auth/src/routeTree.gen.ts index 058f8674ac..a0a61b0279 100644 --- a/e2e/vue-start/basic-auth/src/routeTree.gen.ts +++ b/e2e/vue-start/basic-auth/src/routeTree.gen.ts @@ -9,27 +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 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 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 AuthedPostsRouteImport } from './routes/_authed/posts' import { Route as AuthedPostsIndexRouteImport } from './routes/_authed/posts.index' import { Route as AuthedPostsPostIdRouteImport } from './routes/_authed/posts.$postId' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const AuthedRoute = AuthedRouteImport.update({ - id: '/_authed', - getParentRoute: () => rootRouteImport, -} as any) -const LoginRoute = LoginRouteImport.update({ - id: '/login', - path: '/login', +const SignupRoute = SignupRouteImport.update({ + id: '/signup', + path: '/signup', getParentRoute: () => rootRouteImport, } as any) const LogoutRoute = LogoutRouteImport.update({ @@ -37,9 +28,18 @@ const LogoutRoute = LogoutRouteImport.update({ path: '/logout', getParentRoute: () => rootRouteImport, } as any) -const SignupRoute = SignupRouteImport.update({ - id: '/signup', - path: '/signup', +const LoginRoute = LoginRouteImport.update({ + id: '/login', + path: '/login', + getParentRoute: () => rootRouteImport, +} as any) +const AuthedRoute = AuthedRouteImport.update({ + id: '/_authed', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AuthedPostsRoute = AuthedPostsRouteImport.update({ @@ -120,25 +120,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_authed': { - id: '/_authed' - path: '' - fullPath: '/' - preLoaderRoute: typeof AuthedRouteImport - parentRoute: typeof rootRouteImport - } - '/login': { - id: '/login' - path: '/login' - fullPath: '/login' - preLoaderRoute: typeof LoginRouteImport + '/signup': { + id: '/signup' + path: '/signup' + fullPath: '/signup' + preLoaderRoute: typeof SignupRouteImport parentRoute: typeof rootRouteImport } '/logout': { @@ -148,11 +134,25 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof LogoutRouteImport parentRoute: typeof rootRouteImport } - '/signup': { - id: '/signup' - path: '/signup' - fullPath: '/signup' - preLoaderRoute: typeof SignupRouteImport + '/login': { + id: '/login' + path: '/login' + fullPath: '/login' + preLoaderRoute: typeof LoginRouteImport + parentRoute: typeof rootRouteImport + } + '/_authed': { + id: '/_authed' + path: '' + fullPath: '/' + preLoaderRoute: typeof AuthedRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport 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 e5b6f6778f..89802cfd2f 100644 --- a/e2e/vue-start/basic-auth/src/routes/__root.tsx +++ b/e2e/vue-start/basic-auth/src/routes/__root.tsx @@ -1,5 +1,4 @@ /// -import { defineComponent } from 'vue' import { Body, HeadContent, @@ -16,69 +15,21 @@ import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary.js' import { NotFound } from '~/components/NotFound.js' import appCss from '~/styles/app.css?url' import { seo } from '~/utils/seo.js' -import { getAppSession } from '~/utils/session.js' +import { useAppSession } from '~/utils/session.js' const fetchUser = createServerFn({ method: 'GET' }).handler(async () => { // We need to auth on the server so we have access to secure cookies - const session = await getAppSession() + const session = await useAppSession() - if (!session.userEmail) { + if (!session.data.userEmail) { return null } return { - email: session.userEmail, + email: session.data.userEmail, } }) -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() @@ -130,3 +81,50 @@ 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 606de3e487..53e16ebe33 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 { getAppSession } from '~/utils/session' +import { useAppSession } from '~/utils/session' export const loginFn = createServerFn({ method: 'POST', }) - .validator((payload: { email: string; password: string }) => payload) + .inputValidator((payload: { email: string; password: string }) => payload) .handler(async ({ data }) => { // Find the user const user = await prismaClient.user.findUnique({ @@ -37,11 +37,12 @@ export const loginFn = createServerFn({ } // Create a session - const session = await getAppSession() + const session = await useAppSession() // Store the user's email in the session - session.userEmail = user.email - await session.save() + await session.update({ + userEmail: user.email, + }) }) export const Route = createFileRoute('/_authed')({ @@ -51,7 +52,7 @@ export const Route = createFileRoute('/_authed')({ } }, errorComponent: ({ error }) => { - if (error instanceof Error && error.message === 'Not authenticated') { + if (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 45d6bbab0d..da0c26f27f 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,4 +1,3 @@ -import { defineComponent } from 'vue' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' @@ -9,18 +8,6 @@ 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, @@ -29,3 +16,14 @@ 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 6b8b54c666..cfac133b51 100644 --- a/e2e/vue-start/basic-auth/src/routes/_authed/posts.tsx +++ b/e2e/vue-start/basic-auth/src/routes/_authed/posts.tsx @@ -1,38 +1,36 @@ -import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '~/utils/posts.js' -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)}
    - -
  • - ))} -
-
- -
- ) - }, -}) +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)}
    + +
  • + ))} +
+
+ +
+ ) +} 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 8372b33608..f1d7b58e29 100644 --- a/e2e/vue-start/basic-auth/src/routes/logout.tsx +++ b/e2e/vue-start/basic-auth/src/routes/logout.tsx @@ -1,12 +1,12 @@ import { redirect, createFileRoute } from '@tanstack/vue-router' import { createServerFn } from '@tanstack/vue-start' -import { getAppSession } from '~/utils/session' +import { useAppSession } from '~/utils/session' const logoutFn = createServerFn({ method: 'POST' }).handler(async () => { - const session = await getAppSession() + const session = await useAppSession() - session.destroy() + session.clear() throw redirect({ href: '/', diff --git a/e2e/vue-start/basic-auth/src/routes/signup.tsx b/e2e/vue-start/basic-auth/src/routes/signup.tsx index 5f37f109c7..22fd7d4ca5 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 { getAppSession } from '~/utils/session' +import { useAppSession } from '~/utils/session' export const signupFn = createServerFn({ method: 'POST', }) - .validator( + .inputValidator( (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 getAppSession() + const session = await useAppSession() if (found) { if (found.password !== password) { @@ -37,8 +37,9 @@ export const signupFn = createServerFn({ } // Store the user's email in the session - session.userEmail = found.email - await session.save() + await session.update({ + userEmail: found.email, + }) // Redirect to the prev page stored in the "redirect" search param throw redirect({ @@ -55,8 +56,9 @@ export const signupFn = createServerFn({ }) // Store the user's email in the session - session.userEmail = user.email - await session.save() + await session.update({ + userEmail: user.email, + }) // Redirect to the prev page stored in the "redirect" search param throw redirect({ diff --git a/e2e/vue-start/basic-auth/src/utils/posts.ts b/e2e/vue-start/basic-auth/src/utils/posts.ts index 04dbccaa11..d72d7719a4 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' }) - .validator((postId: string) => postId) + .inputValidator((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 7d078225a0..7cf2a41792 100644 --- a/e2e/vue-start/basic-auth/src/utils/session.ts +++ b/e2e/vue-start/basic-auth/src/utils/session.ts @@ -1,25 +1,13 @@ -import { getIronSession } from 'iron-session' -import { getCookie, setCookie } from '@tanstack/vue-start/server' +// src/services/session.server.ts +import { useSession } from '@tanstack/vue-start/server' import type { User } from '~/prisma-generated/client' type SessionUser = { userEmail: User['email'] } -export function getAppSession() { - return getIronSession( - { read: getCookie, write: setCookie }, - { - cookieName: 'test-auth-session', - // This fixture only runs locally with test credentials. - password: 'local-e2e-only-session-password-at-least-32-characters', - ttl: 60 * 60, - cookieOptions: { - httpOnly: true, - secure: false, - sameSite: 'lax', - path: '/', - }, - }, - ) +export function useAppSession() { + return useSession({ + password: 'ChangeThisBeforeShippingToProdOrYouWillBeFired', + }) } diff --git a/e2e/vue-start/basic-auth/tsconfig.json b/e2e/vue-start/basic-auth/tsconfig.json index 390dad84c0..f9f5aab3da 100644 --- a/e2e/vue-start/basic-auth/tsconfig.json +++ b/e2e/vue-start/basic-auth/tsconfig.json @@ -14,6 +14,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/vue-start/basic-cloudflare/package.json b/e2e/vue-start/basic-cloudflare/package.json index 5ab77db8fc..12d06274fa 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": "WRANGLER_LOG=warn npm run --silent cf-typegen", - "test:e2e": "playwright test --project=chromium" + "postinstall": "npm run cf-typegen", + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", @@ -20,26 +20,15 @@ }, "devDependencies": { "@cloudflare/vite-plugin": "^1.29.0", - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", + "typescript": "^5.7.2", + "vite": "^8.0.0", "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", "wrangler": "^4.74.0" - }, - "nx": { - "targets": { - "test:e2e": { - "outputs": [ - "...", - "{projectRoot}/.wrangler/deploy" - ] - } - } } } diff --git a/e2e/vue-start/basic-cloudflare/playwright.config.ts b/e2e/vue-start/basic-cloudflare/playwright.config.ts index 0925936d55..a545dff891 100644 --- a/e2e/vue-start/basic-cloudflare/playwright.config.ts +++ b/e2e/vue-start/basic-cloudflare/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -13,6 +14,9 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, @@ -20,8 +24,8 @@ export default defineConfig({ webServer: { command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-start/basic-cloudflare/src/components/DefaultCatchBoundary.tsx b/e2e/vue-start/basic-cloudflare/src/components/DefaultCatchBoundary.tsx index 0687372ae0..e11970b600 100644 --- a/e2e/vue-start/basic-cloudflare/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/basic-cloudflare/src/components/DefaultCatchBoundary.tsx @@ -1,61 +1,53 @@ -import { defineComponent } from 'vue' -import type { PropType } from 'vue' import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, useRouter, } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' -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 - - )} -
-
- ) - } - }, -}) +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 + + )} +
+
+ ) +} diff --git a/e2e/vue-start/basic-cloudflare/src/routeTree.gen.ts b/e2e/vue-start/basic-cloudflare/src/routeTree.gen.ts index c52a88360b..30451e7ab7 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 IndexRouteImport } from './routes/index' import { Route as StaticRouteImport } from './routes/static' +import { Route as IndexRouteImport } from './routes/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const StaticRoute = StaticRouteImport.update({ id: '/static', path: '/static', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/static': { id: '/static' path: '/static' @@ -65,6 +58,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof StaticRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + 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 d3a020c7ad..1c708a7ec6 100644 --- a/e2e/vue-start/basic-cloudflare/src/routes/index.tsx +++ b/e2e/vue-start/basic-cloudflare/src/routes/index.tsx @@ -1,21 +1,7 @@ -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, @@ -27,3 +13,15 @@ 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 14d0c06294..7b0f9fd232 100644 --- a/e2e/vue-start/basic-cloudflare/src/routes/static.tsx +++ b/e2e/vue-start/basic-cloudflare/src/routes/static.tsx @@ -1,20 +1,7 @@ -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, @@ -25,3 +12,14 @@ const getData = createServerFn().handler(() => { myVar: env.MY_VAR, } }) + +function StaticPage() { + const data = Route.useLoaderData() + + return ( +
+

Static Page

+

The value is {data.value.myVar}

+
+ ) +} diff --git a/e2e/vue-start/basic-cloudflare/tests/setup/global.setup.ts b/e2e/vue-start/basic-cloudflare/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-start/basic-cloudflare/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-start/basic-cloudflare/tests/setup/global.teardown.ts b/e2e/vue-start/basic-cloudflare/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-start/basic-cloudflare/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-start/basic-cloudflare/tsconfig.json b/e2e/vue-start/basic-cloudflare/tsconfig.json index 572d840872..8bf3d33789 100644 --- a/e2e/vue-start/basic-cloudflare/tsconfig.json +++ b/e2e/vue-start/basic-cloudflare/tsconfig.json @@ -14,6 +14,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/vue-start/basic-tsr-config/package.json b/e2e/vue-start/basic-tsr-config/package.json index 828dce5b2a..af2b8ac381 100644 --- a/e2e/vue-start/basic-tsr-config/package.json +++ b/e2e/vue-start/basic-tsr-config/package.json @@ -8,23 +8,21 @@ "dev:e2e": "vite dev", "build": "rimraf ./count.txt && vite build && tsc --noEmit", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-start": "workspace:^", + "vite": "^8.0.0", "vue": "^3.5.25" }, "devDependencies": { "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", - "srvx": "^1.0.0", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", + "srvx": "^0.11.9", + "typescript": "^5.7.2", "@vitejs/plugin-vue": "^6.0.5", - "@vitejs/plugin-vue-jsx": "^5.1.5", - "vite": "^8.0.14", - "rimraf": "catalog:" + "@vitejs/plugin-vue-jsx": "^5.1.5" } } diff --git a/e2e/vue-start/basic-tsr-config/playwright.config.ts b/e2e/vue-start/basic-tsr-config/playwright.config.ts index e6b92ce385..f6dd61ba6c 100644 --- a/e2e/vue-start/basic-tsr-config/playwright.config.ts +++ b/e2e/vue-start/basic-tsr-config/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -20,8 +21,8 @@ export default defineConfig({ webServer: { command: `pnpm build && VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-start/basic-tsr-config/src/app/routes/index.tsx b/e2e/vue-start/basic-tsr-config/src/app/routes/index.tsx index b4b520e8af..feaff21c25 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,4 +1,3 @@ -import { defineComponent } from 'vue' import * as fs from 'node:fs' import { createFileRoute, useRouter } from '@tanstack/vue-router' import { createServerFn } from '@tanstack/vue-start' @@ -13,31 +12,30 @@ const getCount = createServerFn({ }) const updateCount = createServerFn({ method: 'POST' }) - .validator((d: number) => d) + .inputValidator((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 e8f3ecf0c9..010db955bf 100644 --- a/e2e/vue-start/basic-tsr-config/tsconfig.json +++ b/e2e/vue-start/basic-tsr-config/tsconfig.json @@ -14,6 +14,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/app/*"] }, diff --git a/e2e/vue-start/basic-vue-query/package.json b/e2e/vue-start/basic-vue-query/package.json index ab9589376d..e820457bd8 100644 --- a/e2e/vue-start/basic-vue-query/package.json +++ b/e2e/vue-start/basic-vue-query/package.json @@ -9,7 +9,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-query": "^5.92.1", @@ -18,22 +18,21 @@ "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-router-ssr-query": "workspace:^", "@tanstack/vue-start": "workspace:^", - "redaxios": "catalog:", - "tailwind-merge": "^3.6.0", + "redaxios": "^0.5.1", + "tailwind-merge": "^2.6.0", + "vite": "^8.0.0", "vue": "^3.5.25", - "zod": "^4.4.3" + "zod": "^4.1.12" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", - "@vitejs/plugin-vue": "^6.0.5", - "@vitejs/plugin-vue-jsx": "^5.1.5", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "typescript": "^5.7.2", + "@vitejs/plugin-vue": "^6.0.5", + "@vitejs/plugin-vue-jsx": "^5.1.5" } } diff --git a/e2e/vue-start/basic-vue-query/playwright.config.ts b/e2e/vue-start/basic-vue-query/playwright.config.ts index 0618b7272a..84636ab0f9 100644 --- a/e2e/vue-start/basic-vue-query/playwright.config.ts +++ b/e2e/vue-start/basic-vue-query/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` @@ -11,18 +16,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { baseURL, }, webServer: { - command: `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', - env: { - NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, - }, }, projects: [ diff --git a/e2e/vue-start/basic-vue-query/src/routeTree.gen.ts b/e2e/vue-start/basic-vue-query/src/routeTree.gen.ts index 10e8a56450..2c514d54ea 100644 --- a/e2e/vue-start/basic-vue-query/src/routeTree.gen.ts +++ b/e2e/vue-start/basic-vue-query/src/routeTree.gen.ts @@ -9,41 +9,27 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -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 ApiUsersRouteImport } from './routes/api.users' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +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 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 PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as ApiUsersRouteImport } from './routes/api.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 LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', - getParentRoute: () => rootRouteImport, -} as any) -const DeferredRoute = DeferredRouteImport.update({ - id: '/deferred', - path: '/deferred', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', getParentRoute: () => rootRouteImport, } as any) const SuspenseTransitionRoute = SuspenseTransitionRouteImport.update({ @@ -51,64 +37,78 @@ const SuspenseTransitionRoute = SuspenseTransitionRouteImport.update({ path: '/suspense-transition', getParentRoute: () => rootRouteImport, } as any) -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', 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', +const DeferredRoute = DeferredRouteImport.update({ + id: '/deferred', + path: '/deferred', getParentRoute: () => rootRouteImport, } as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', - getParentRoute: () => PostsRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, + 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 LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => LayoutLayout2Route, +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, } as any) -const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ - id: '/layout-b', - path: '/layout-b', - getParentRoute: () => LayoutLayout2Route, +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/users', + getParentRoute: () => rootRouteImport, } as any) -const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => ApiUsersRoute, +const LayoutLayout2Route = LayoutLayout2RouteImport.update({ + id: '/_layout-2', + getParentRoute: () => LayoutRoute, +} as any) +const TransitionCountQueryRoute = TransitionCountQueryRouteImport.update({ + id: '/transition/count/query', + path: '/transition/count/query', + getParentRoute: () => rootRouteImport, } 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, +const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => ApiUsersRoute, +} as any) +const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ + id: '/layout-b', + path: '/layout-b', + getParentRoute: () => LayoutLayout2Route, +} as any) +const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => LayoutLayout2Route, } as any) export interface FileRoutesByFullPath { @@ -231,32 +231,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_layout': { - id: '/_layout' - path: '' - fullPath: '/' - preLoaderRoute: typeof LayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport parentRoute: typeof rootRouteImport } '/suspense-transition': { @@ -266,11 +245,67 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof SuspenseTransitionRouteImport parentRoute: typeof rootRouteImport } - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout': { + id: '/_layout' + 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 + } + '/api/users': { + id: '/api/users' + path: '/api/users' + fullPath: '/api/users' + preLoaderRoute: typeof ApiUsersRouteImport parentRoute: typeof rootRouteImport } '/_layout/_layout-2': { @@ -280,62 +315,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof LayoutLayout2RouteImport parentRoute: typeof LayoutRoute } - '/api/users': { - id: '/api/users' - path: '/api/users' - fullPath: '/api/users' - preLoaderRoute: typeof ApiUsersRouteImport + '/transition/count/query': { + id: '/transition/count/query' + path: '/transition/count/query' + fullPath: '/transition/count/query' + preLoaderRoute: typeof TransitionCountQueryRouteImport 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 - } - '/_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 - } '/posts_/$postId/deep': { id: '/posts_/$postId/deep' path: '/posts/$postId/deep' @@ -343,12 +329,26 @@ declare module '@tanstack/vue-router' { 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 + '/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 } } } diff --git a/e2e/vue-start/basic-vue-query/src/routes/api.users.ts b/e2e/vue-start/basic-vue-query/src/routes/api.users.ts index f9330a87db..cab4cafc3f 100644 --- a/e2e/vue-start/basic-vue-query/src/routes/api.users.ts +++ b/e2e/vue-start/basic-vue-query/src/routes/api.users.ts @@ -2,7 +2,11 @@ import { createFileRoute } from '@tanstack/vue-router' import axios from 'redaxios' import type { User } from '../utils/users' -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const Route = createFileRoute('/api/users')({ server: { diff --git a/e2e/vue-start/basic-vue-query/src/routes/api/users.$id.ts b/e2e/vue-start/basic-vue-query/src/routes/api/users.$id.ts index d138746730..4cc4b33a0b 100644 --- a/e2e/vue-start/basic-vue-query/src/routes/api/users.$id.ts +++ b/e2e/vue-start/basic-vue-query/src/routes/api/users.$id.ts @@ -2,7 +2,11 @@ import { createFileRoute } from '@tanstack/vue-router' import axios from 'redaxios' import type { User } from '../../utils/users' -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const Route = createFileRoute('/api/users/$id')({ server: { diff --git a/e2e/vue-start/basic-vue-query/src/routes/posts.$postId.tsx b/e2e/vue-start/basic-vue-query/src/routes/posts.$postId.tsx index fd8deaf291..5ec224eb2d 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,10 +1,9 @@ -import { defineComponent } from 'vue' import { useQuery } from '@tanstack/vue-query' import { ErrorComponent, Link, createFileRoute, - ErrorComponentProps, + type ErrorComponentProps, } from '@tanstack/vue-router' import { postQueryOptions } from '~/utils/posts' @@ -12,30 +11,27 @@ export function PostErrorComponent(props: ErrorComponentProps) { 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 - -
- ) - }, -}) +function PostComponent() { + 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 211b3ca4b1..38e7429f6e 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,26 +1,22 @@ -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' -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}
-
- ) - }, -}) +function PostDeepComponent() { + 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 f5004aa21d..6d12790dc9 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 { defineComponent, ref, watchEffect } from 'vue' +import { ref, watchEffect } from 'vue' const doubleQueryOptions = (n: number) => queryOptions({ @@ -19,37 +19,6 @@ 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 (
@@ -70,3 +39,34 @@ 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 32b1943c71..2ab0562203 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,4 +1,3 @@ -import { defineComponent } from 'vue' import { Link, createFileRoute } from '@tanstack/vue-router' import { queryOptions, useQuery } from '@tanstack/vue-query' import { z } from 'zod' @@ -17,32 +16,6 @@ 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 }) => { @@ -51,3 +24,28 @@ 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 bf1b75861e..91376b9498 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,4 +1,3 @@ -import { defineComponent } from 'vue' import { useQuery } from '@tanstack/vue-query' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' @@ -6,20 +5,19 @@ import type { ErrorComponentProps } from '@tanstack/vue-router' import { NotFound } from '~/components/NotFound' import { userQueryOptions } from '~/utils/users' -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 ?? ''}
-
- ) - }, -}) +function UserComponent() { + const params = Route.useParams() + const userQuery = useQuery(() => userQueryOptions(params.value.userId)) + + return ( +
+

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

+
{userQuery.data.value?.email ?? ''}
+
+ ) +} export const Route = createFileRoute('/users/$userId')({ loader: async ({ context, params: { userId } }) => { diff --git a/e2e/vue-start/basic-vue-query/src/utils/posts.tsx b/e2e/vue-start/basic-vue-query/src/utils/posts.tsx index c6b5e70a0b..7f1f564645 100644 --- a/e2e/vue-start/basic-vue-query/src/utils/posts.tsx +++ b/e2e/vue-start/basic-vue-query/src/utils/posts.tsx @@ -7,8 +7,6 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' - export const postsQueryOptions = () => queryOptions({ queryKey: ['posts'], @@ -16,7 +14,7 @@ export const postsQueryOptions = () => console.info('Fetching posts...') await new Promise((r) => setTimeout(r, 500)) return axios - .get>(`${queryURL}/posts`) + .get>('https://jsonplaceholder.typicode.com/posts') .then((r) => r.data.slice(0, 10)) }, }) @@ -29,7 +27,7 @@ export const postQueryOptions = (postId: string) => await new Promise((r) => setTimeout(r, 500)) return axios - .get(`${queryURL}/posts/${postId}`) + .get(`https://jsonplaceholder.typicode.com/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 fe7a902fa2..29bf08c315 100644 --- a/e2e/vue-start/basic-vue-query/src/utils/users.tsx +++ b/e2e/vue-start/basic-vue-query/src/utils/users.tsx @@ -1,6 +1,4 @@ import { queryOptions } from '@tanstack/vue-query' -import { createIsomorphicFn } from '@tanstack/vue-start' -import { getRequestUrl } from '@tanstack/vue-start/server' import axios from 'redaxios' export type User = { @@ -9,16 +7,17 @@ export type User = { email: string } -const getOrigin = createIsomorphicFn() - .server(() => getRequestUrl().origin) - .client(() => window.location.origin) +const PORT = + import.meta.env.VITE_SERVER_PORT || process.env.VITE_SERVER_PORT || 3000 + +export const DEPLOY_URL = `http://localhost:${PORT}` export const usersQueryOptions = () => queryOptions({ queryKey: ['users'], queryFn: () => axios - .get>(getOrigin() + '/api/users') + .get>(DEPLOY_URL + '/api/users') .then((r) => r.data) .catch(() => { throw new Error('Failed to fetch users') @@ -30,7 +29,7 @@ export const userQueryOptions = (id: string) => queryKey: ['users', id], queryFn: () => axios - .get(getOrigin() + '/api/users/' + id) + .get(DEPLOY_URL + '/api/users/' + id) .then((r) => r.data) .catch(() => { throw new Error('Failed to fetch user') diff --git a/e2e/react-start/i18n-paraglide/test-results/.last-run.json b/e2e/vue-start/basic-vue-query/test-results/.last-run.json similarity index 100% rename from e2e/react-start/i18n-paraglide/test-results/.last-run.json rename to e2e/vue-start/basic-vue-query/test-results/.last-run.json diff --git a/e2e/vue-start/basic-vue-query/tests/app.spec.ts b/e2e/vue-start/basic-vue-query/tests/app.spec.ts index 4ce5c20ef7..ab2469f68d 100644 --- a/e2e/vue-start/basic-vue-query/tests/app.spec.ts +++ b/e2e/vue-start/basic-vue-query/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test('Navigating to post', async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-start/basic-vue-query/tests/setup/global.setup.ts b/e2e/vue-start/basic-vue-query/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-start/basic-vue-query/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-start/basic-vue-query/tests/setup/global.teardown.ts b/e2e/vue-start/basic-vue-query/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-start/basic-vue-query/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-start/basic-vue-query/tests/transition.spec.ts b/e2e/vue-start/basic-vue-query/tests/transition.spec.ts index a0f3bf0964..2c28fc72a2 100644 --- a/e2e/vue-start/basic-vue-query/tests/transition.spec.ts +++ b/e2e/vue-start/basic-vue-query/tests/transition.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test('transitions/count/query should keep old values visible during navigation', async ({ page, diff --git a/e2e/vue-start/basic-vue-query/tsconfig.json b/e2e/vue-start/basic-vue-query/tsconfig.json index 572d840872..8bf3d33789 100644 --- a/e2e/vue-start/basic-vue-query/tsconfig.json +++ b/e2e/vue-start/basic-vue-query/tsconfig.json @@ -14,6 +14,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/vue-start/basic/.gitignore b/e2e/vue-start/basic/.gitignore index b9c2c7e5f6..a79d5cf129 100644 --- a/e2e/vue-start/basic/.gitignore +++ b/e2e/vue-start/basic/.gitignore @@ -18,4 +18,3 @@ 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 2ff8329543..f1ed50117c 100644 --- a/e2e/vue-start/basic/package.json +++ b/e2e/vue-start/basic/package.json @@ -6,32 +6,34 @@ "scripts": { "dev": "vite dev --port 3000", "dev:e2e": "vite dev", - "build": "pnpm build:vite", + "build": "vite build && tsc --noEmit", + "build:spa": "MODE=spa vite build && tsc --noEmit", + "build:prerender": "MODE=prerender vite build && tsc --noEmit", "preview": "vite preview", "start": "node server.js", - "test:e2e:local": "playwright test --project=chromium", - "build:vite": "vite build && tsc --noEmit", - "build:rsbuild": "rsbuild build && tsc --noEmit" + "test:e2e:startDummyServer": "node -e 'import(\"./tests/setup/global.setup.ts\").then(m => m.default())' &", + "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" }, "dependencies": { "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-start": "workspace:^", - "express": "^5.2.1", + "express": "^5.1.0", "http-proxy-middleware": "^3.0.5", "js-cookie": "^3.0.5", - "redaxios": "catalog:", - "tailwind-merge": "^3.6.0", + "redaxios": "^0.5.1", "vue": "^3.5.16", - "zod": "^4.4.3" + "tailwind-merge": "^2.6.0", + "vite": "^8.0.0", + "zod": "^3.24.2" }, "devDependencies": { - "@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", + "@playwright/test": "^1.50.1", "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@types/js-cookie": "^3.0.6", @@ -39,40 +41,8 @@ "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", "combinate": "^1.1.11", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "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" - } - ] - } + "typescript": "^5.7.2" } } diff --git a/e2e/vue-start/basic/playwright.config.ts b/e2e/vue-start/basic/playwright.config.ts index 9322874f3a..86c58bc1ce 100644 --- a/e2e/vue-start/basic/playwright.config.ts +++ b/e2e/vue-start/basic/playwright.config.ts @@ -1,37 +1,63 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +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' } -const mode = process.env.MODE ?? 'ssr' - -const distDir = process.env.E2E_DIST_DIR ?? 'dist' - -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +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 baseURL = `http://localhost:${PORT}` -const commandByMode = - mode === 'preview' - ? `pnpm preview --host 0.0.0.0 --outDir ${distDir} --port ${PORT}` - : `pnpm start` +const spaModeCommand = `pnpm build:spa && pnpm start` +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()) +/** + * 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: commandByMode, - wait: appServerReady, - reuseExistingServer: false, + command: getCommand(), + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { - NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, - MODE: mode, - START_PORT: '0', + MODE: process.env.MODE || '', + VITE_NODE_ENV: 'test', + VITE_EXTERNAL_PORT: String(EXTERNAL_PORT), + VITE_SERVER_PORT: String(PORT), + START_PORT: String(START_PORT), PORT: String(PORT), - E2E_DIST_DIR: distDir, }, }, diff --git a/e2e/vue-start/basic/postcss.config.mjs b/e2e/vue-start/basic/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/e2e/vue-start/basic/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/e2e/vue-start/basic/rsbuild.config.ts b/e2e/vue-start/basic/rsbuild.config.ts deleted file mode 100644 index aad3a76e73..0000000000 --- a/e2e/vue-start/basic/rsbuild.config.ts +++ /dev/null @@ -1,29 +0,0 @@ -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 3e1ddab400..83f5ff0079 100644 --- a/e2e/vue-start/basic/server.js +++ b/e2e/vue-start/basic/server.js @@ -1,42 +1,24 @@ -import fs from 'node:fs' -import path from 'node:path' import { toNodeHandler } from 'srvx/node' +import path from 'node:path' import express from 'express' import { createProxyMiddleware } from 'http-proxy-middleware' -const port = Number(process.env.PORT ?? 3000) +const port = process.env.PORT || 3000 -const startPort = Number(process.env.START_PORT ?? 0) +const startPort = process.env.START_PORT || 3001 const isSpaMode = process.env.MODE === 'spa' const isPrerender = process.env.MODE === 'prerender' -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 distServerEntryPath = resolveDistServerEntryPath() - const server = (await import(distServerEntryPath)).default + const server = (await import('./dist/server/server.js')).default const nodeHandler = toNodeHandler(server.fetch) const app = express() // 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(express.static('./dist/client', { redirect: !isPrerender })) app.use(async (req, res, next) => { try { @@ -49,13 +31,13 @@ export async function createStartServer() { return { app } } -export async function createSpaServer(backendPort) { +export async function createSpaServer() { const app = express() app.use( '/api', createProxyMiddleware({ - target: `http://localhost:${backendPort}/api`, // Replace with your target server's URL + target: `http://localhost:${startPort}/api`, // Replace with your target server's URL changeOrigin: false, // Needed for virtual hosted sites, }), ) @@ -63,36 +45,36 @@ export async function createSpaServer(backendPort) { app.use( '/_serverFn', createProxyMiddleware({ - target: `http://localhost:${backendPort}/_serverFn`, // Replace with your target server's URL + target: `http://localhost:${startPort}/_serverFn`, // Replace with your target server's URL changeOrigin: false, // Needed for virtual hosted sites, }), ) - app.use(express.static(distClientDir)) + app.use(express.static('./dist/client')) app.get('/{*splat}', (req, res) => { - res.sendFile('index.html', { root: distClientDir }) + res.sendFile(path.resolve('./dist/client/index.html')) }) return { app } } -// Bind the backend first so the SPA proxy receives the port actually held by it. -const { app: startApp } = await createStartServer() -const backend = startApp.listen(isSpaMode ? startPort : port, async (error) => { - if (error) { - throw error - } - const backendPort = backend.address().port - if (isSpaMode) { - const { app } = await createSpaServer(backendPort) - const frontend = app.listen(port, (frontendError) => { - if (frontendError) { - throw frontendError - } - console.info(`E2E app: http://localhost:${frontend.address().port}`) - }) - } else { - console.info(`E2E app: http://localhost:${backendPort}`) - } -}) +if (isSpaMode) { + createSpaServer().then(async ({ app }) => + app.listen(port, () => { + console.info(`Client Server: http://localhost:${port}`) + }), + ) + + createStartServer().then(async ({ app }) => + app.listen(startPort, () => { + console.info(`Start Server: http://localhost:${startPort}`) + }), + ) +} else { + createStartServer().then(async ({ app }) => + app.listen(port, () => { + console.info(`Start Server: http://localhost:${port}`) + }), + ) +} diff --git a/e2e/vue-start/basic/src/components/DefaultCatchBoundary.tsx b/e2e/vue-start/basic/src/components/DefaultCatchBoundary.tsx index cd0fa98fc7..fe99cf62f3 100644 --- a/e2e/vue-start/basic/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/basic/src/components/DefaultCatchBoundary.tsx @@ -1,9 +1,11 @@ import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, useRouter, } from '@tanstack/vue-router' +import type { ErrorComponentProps } from '@tanstack/vue-router' import { defineComponent } from 'vue' export const DefaultCatchBoundary = defineComponent({ @@ -15,8 +17,9 @@ export const DefaultCatchBoundary = defineComponent({ }, setup(props) { const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, }) 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 7d7265e214..187687192b 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() - .validator( + .inputValidator( (opts: { target: 'internal' | 'external' reloadDocument?: boolean diff --git a/e2e/vue-start/basic/src/routeTree.gen.ts b/e2e/vue-start/basic/src/routeTree.gen.ts index 7fbcd192b6..016a292835 100644 --- a/e2e/vue-start/basic/src/routeTree.gen.ts +++ b/e2e/vue-start/basic/src/routeTree.gen.ts @@ -9,116 +9,67 @@ // Additionally, you should also exclude this file 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 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 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 StreamRouteImport } from './routes/stream' +import { Route as ScriptsRouteImport } from './routes/scripts' +import { Route as RawStreamRouteImport } from './routes/raw-stream' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as LinksRouteImport } from './routes/links' +import { Route as InlineScriptsRouteImport } from './routes/inline-scripts' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as SpecialCharsRouteRouteImport } from './routes/specialChars/route' +import { Route as SearchParamsRouteRouteImport } from './routes/search-params/route' +import { Route as NotFoundRouteRouteImport } from './routes/not-found/route' +import { Route as IndexRouteImport } from './routes/index' import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as SearchParamsIndexRouteImport } from './routes/search-params/index' +import { Route as RedirectIndexRouteImport } from './routes/redirect/index' +import { Route as RawStreamIndexRouteImport } from './routes/raw-stream/index' +import { Route as PostsIndexRouteImport } from './routes/posts.index' +import { Route as NotFoundIndexRouteImport } from './routes/not-found/index' +import { Route as MultiCookieRedirectIndexRouteImport } from './routes/multi-cookie-redirect/index' import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as 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 SpecialCharsChar45824Char54620Char48124Char44397RouteImport } from './routes/specialChars/대한민국' +import { Route as SpecialCharsSearchRouteImport } from './routes/specialChars/search' +import { Route as SpecialCharsHashRouteImport } from './routes/specialChars/hash' +import { Route as SpecialCharsParamRouteImport } from './routes/specialChars/$param' +import { Route as SearchParamsLoaderThrowsRedirectRouteImport } from './routes/search-params/loader-throws-redirect' +import { Route as SearchParamsDefaultRouteImport } from './routes/search-params/default' +import { Route as RedirectTargetRouteImport } from './routes/redirect/$target' +import { Route as RawStreamSsrTextHintRouteImport } from './routes/raw-stream/ssr-text-hint' +import { Route as RawStreamSsrSingleRouteImport } from './routes/raw-stream/ssr-single' +import { Route as RawStreamSsrMultipleRouteImport } from './routes/raw-stream/ssr-multiple' +import { Route as RawStreamSsrMixedRouteImport } from './routes/raw-stream/ssr-mixed' +import { Route as RawStreamSsrBinaryHintRouteImport } from './routes/raw-stream/ssr-binary-hint' +import { Route as RawStreamClientCallRouteImport } from './routes/raw-stream/client-call' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as NotFoundViaLoaderRouteImport } from './routes/not-found/via-loader' +import { Route as NotFoundViaBeforeLoadTargetRootRouteImport } from './routes/not-found/via-beforeLoad-target-root' +import { Route as NotFoundViaBeforeLoadRouteImport } from './routes/not-found/via-beforeLoad' +import { Route as MultiCookieRedirectTargetRouteImport } from './routes/multi-cookie-redirect/target' +import { Route as ApiUsersRouteImport } from './routes/api/users' +import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' +import { Route as SpecialCharsMalformedRouteRouteImport } from './routes/specialChars/malformed/route' +import { Route as NotFoundParentBoundaryRouteRouteImport } from './routes/not-found/parent-boundary/route' import { Route as 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 SpecialCharsMalformedParamRouteImport } from './routes/specialChars/malformed/$param' +import { Route as RedirectTargetViaLoaderRouteImport } from './routes/redirect/$target/via-loader' +import { Route as RedirectTargetViaBeforeLoadRouteImport } from './routes/redirect/$target/via-beforeLoad' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' +import { Route as NotFoundParentBoundaryViaBeforeLoadRouteImport } from './routes/not-found/parent-boundary/via-beforeLoad' +import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' +import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' 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 RedirectTargetServerFnViaLoaderRouteImport } from './routes/redirect/$target/serverFn/via-loader' +import { Route as RedirectTargetServerFnViaBeforeLoadRouteImport } from './routes/redirect/$target/serverFn/via-beforeLoad' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', - getParentRoute: () => rootRouteImport, -} as any) -const DeferredRoute = DeferredRouteImport.update({ - id: '/deferred', - path: '/deferred', - getParentRoute: () => rootRouteImport, -} as any) -const InlineScriptsRoute = InlineScriptsRouteImport.update({ - id: '/inline-scripts', - path: '/inline-scripts', - getParentRoute: () => rootRouteImport, -} as any) -const LinksRoute = LinksRouteImport.update({ - id: '/links', - path: '/links', - getParentRoute: () => rootRouteImport, -} as any) -const NotFoundRouteRoute = NotFoundRouteRouteImport.update({ - id: '/not-found', - path: '/not-found', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) -const RawStreamRoute = RawStreamRouteImport.update({ - id: '/raw-stream', - path: '/raw-stream', - getParentRoute: () => rootRouteImport, -} as any) -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', +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', getParentRoute: () => rootRouteImport, } as any) const StreamRoute = StreamRouteImport.update({ @@ -126,46 +77,176 @@ const StreamRoute = StreamRouteImport.update({ path: '/stream', getParentRoute: () => rootRouteImport, } as any) -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const ScriptsRoute = ScriptsRouteImport.update({ + id: '/scripts', + path: '/scripts', 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', +const RawStreamRoute = RawStreamRouteImport.update({ + id: '/raw-stream', + path: '/raw-stream', getParentRoute: () => rootRouteImport, } as any) +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', + getParentRoute: () => rootRouteImport, +} as any) +const LinksRoute = LinksRouteImport.update({ + id: '/links', + path: '/links', + getParentRoute: () => rootRouteImport, +} as any) +const InlineScriptsRoute = InlineScriptsRouteImport.update({ + id: '/inline-scripts', + path: '/inline-scripts', + getParentRoute: () => rootRouteImport, +} as any) +const DeferredRoute = DeferredRouteImport.update({ + id: '/deferred', + path: '/deferred', + getParentRoute: () => rootRouteImport, +} as any) +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', + getParentRoute: () => rootRouteImport, +} as any) +const SpecialCharsRouteRoute = SpecialCharsRouteRouteImport.update({ + id: '/specialChars', + path: '/specialChars', + getParentRoute: () => rootRouteImport, +} as any) +const SearchParamsRouteRoute = SearchParamsRouteRouteImport.update({ + id: '/search-params', + path: '/search-params', + getParentRoute: () => rootRouteImport, +} as any) +const NotFoundRouteRoute = NotFoundRouteRouteImport.update({ + id: '/not-found', + path: '/not-found', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + 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/', + getParentRoute: () => rootRouteImport, +} as any) +const RawStreamIndexRoute = RawStreamIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => RawStreamRoute, +} as any) +const PostsIndexRoute = PostsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PostsRoute, +} as any) +const NotFoundIndexRoute = NotFoundIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => NotFoundRouteRoute, +} as any) const MultiCookieRedirectIndexRoute = MultiCookieRedirectIndexRouteImport.update({ id: '/multi-cookie-redirect/', path: '/multi-cookie-redirect/', getParentRoute: () => rootRouteImport, } as any) -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, +const UsersUserIdRoute = UsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => UsersRoute, } as any) -const NotFoundParentBoundaryRouteRoute = - NotFoundParentBoundaryRouteRouteImport.update({ - id: '/parent-boundary', - path: '/parent-boundary', - getParentRoute: () => NotFoundRouteRoute, +const SpecialCharsChar45824Char54620Char48124Char44397Route = + SpecialCharsChar45824Char54620Char48124Char44397RouteImport.update({ + id: '/대한민국', + path: '/대한민국', + getParentRoute: () => SpecialCharsRouteRoute, } as any) -const NotFoundViaBeforeLoadRoute = NotFoundViaBeforeLoadRouteImport.update({ - id: '/via-beforeLoad', - path: '/via-beforeLoad', +const SpecialCharsSearchRoute = SpecialCharsSearchRouteImport.update({ + id: '/search', + path: '/search', + getParentRoute: () => SpecialCharsRouteRoute, +} as any) +const SpecialCharsHashRoute = SpecialCharsHashRouteImport.update({ + id: '/hash', + path: '/hash', + getParentRoute: () => SpecialCharsRouteRoute, +} as any) +const SpecialCharsParamRoute = SpecialCharsParamRouteImport.update({ + id: '/$param', + path: '/$param', + getParentRoute: () => SpecialCharsRouteRoute, +} as any) +const SearchParamsLoaderThrowsRedirectRoute = + SearchParamsLoaderThrowsRedirectRouteImport.update({ + id: '/loader-throws-redirect', + path: '/loader-throws-redirect', + getParentRoute: () => SearchParamsRouteRoute, + } as any) +const SearchParamsDefaultRoute = SearchParamsDefaultRouteImport.update({ + id: '/default', + path: '/default', + getParentRoute: () => SearchParamsRouteRoute, +} as any) +const RedirectTargetRoute = RedirectTargetRouteImport.update({ + id: '/redirect/$target', + path: '/redirect/$target', + getParentRoute: () => rootRouteImport, +} as any) +const RawStreamSsrTextHintRoute = RawStreamSsrTextHintRouteImport.update({ + id: '/ssr-text-hint', + path: '/ssr-text-hint', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamSsrSingleRoute = RawStreamSsrSingleRouteImport.update({ + id: '/ssr-single', + path: '/ssr-single', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamSsrMultipleRoute = RawStreamSsrMultipleRouteImport.update({ + id: '/ssr-multiple', + path: '/ssr-multiple', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamSsrMixedRoute = RawStreamSsrMixedRouteImport.update({ + id: '/ssr-mixed', + path: '/ssr-mixed', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamSsrBinaryHintRoute = RawStreamSsrBinaryHintRouteImport.update({ + id: '/ssr-binary-hint', + path: '/ssr-binary-hint', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamClientCallRoute = RawStreamClientCallRouteImport.update({ + id: '/client-call', + path: '/client-call', + getParentRoute: () => RawStreamRoute, +} as any) +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, +} as any) +const NotFoundViaLoaderRoute = NotFoundViaLoaderRouteImport.update({ + id: '/via-loader', + path: '/via-loader', getParentRoute: () => NotFoundRouteRoute, } as any) const NotFoundViaBeforeLoadTargetRootRoute = @@ -174,91 +255,25 @@ const NotFoundViaBeforeLoadTargetRootRoute = path: '/via-beforeLoad-target-root', getParentRoute: () => NotFoundRouteRoute, } as any) -const NotFoundViaLoaderRoute = NotFoundViaLoaderRouteImport.update({ - id: '/via-loader', - path: '/via-loader', +const NotFoundViaBeforeLoadRoute = NotFoundViaBeforeLoadRouteImport.update({ + id: '/via-beforeLoad', + path: '/via-beforeLoad', getParentRoute: () => NotFoundRouteRoute, } as any) -const 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({ - id: '/loader-throws-redirect', - path: '/loader-throws-redirect', - getParentRoute: () => SearchParamsRouteRoute, +const MultiCookieRedirectTargetRoute = + MultiCookieRedirectTargetRouteImport.update({ + id: '/multi-cookie-redirect/target', + path: '/multi-cookie-redirect/target', + getParentRoute: () => rootRouteImport, } as any) -const SpecialCharsParamRoute = SpecialCharsParamRouteImport.update({ - id: '/$param', - path: '/$param', - getParentRoute: () => SpecialCharsRouteRoute, +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/users', + getParentRoute: () => rootRouteImport, } as any) -const SpecialCharsHashRoute = SpecialCharsHashRouteImport.update({ - id: '/hash', - path: '/hash', - getParentRoute: () => SpecialCharsRouteRoute, +const LayoutLayout2Route = LayoutLayout2RouteImport.update({ + id: '/_layout-2', + getParentRoute: () => LayoutRoute, } as any) const SpecialCharsMalformedRouteRoute = SpecialCharsMalformedRouteRouteImport.update({ @@ -266,91 +281,76 @@ const SpecialCharsMalformedRouteRoute = path: '/malformed', getParentRoute: () => SpecialCharsRouteRoute, } as any) -const SpecialCharsSearchRoute = SpecialCharsSearchRouteImport.update({ - id: '/search', - path: '/search', - getParentRoute: () => SpecialCharsRouteRoute, -} as any) -const SpecialCharsChar45824Char54620Char48124Char44397Route = - SpecialCharsChar45824Char54620Char48124Char44397RouteImport.update({ - id: '/대한민국', - path: '/대한민국', - getParentRoute: () => SpecialCharsRouteRoute, +const NotFoundParentBoundaryRouteRoute = + NotFoundParentBoundaryRouteRouteImport.update({ + id: '/parent-boundary', + path: '/parent-boundary', + getParentRoute: () => NotFoundRouteRoute, } as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRoute, -} as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => UsersRoute, -} as any) -const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => LayoutLayout2Route, -} as any) -const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ - id: '/layout-b', - path: '/layout-b', - getParentRoute: () => LayoutLayout2Route, -} as any) -const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => ApiUsersRoute, -} as any) -const NotFoundParentBoundaryViaBeforeLoadRoute = - NotFoundParentBoundaryViaBeforeLoadRouteImport.update({ - id: '/via-beforeLoad', - path: '/via-beforeLoad', - getParentRoute: () => NotFoundParentBoundaryRouteRoute, - } as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', - getParentRoute: () => rootRouteImport, -} as any) const RedirectTargetIndexRoute = RedirectTargetIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => RedirectTargetRoute, } as any) +const SpecialCharsMalformedSearchRoute = + SpecialCharsMalformedSearchRouteImport.update({ + id: '/search', + path: '/search', + getParentRoute: () => SpecialCharsMalformedRouteRoute, + } as any) +const SpecialCharsMalformedParamRoute = + SpecialCharsMalformedParamRouteImport.update({ + id: '/$param', + path: '/$param', + getParentRoute: () => SpecialCharsMalformedRouteRoute, + } as any) +const RedirectTargetViaLoaderRoute = RedirectTargetViaLoaderRouteImport.update({ + id: '/via-loader', + path: '/via-loader', + getParentRoute: () => RedirectTargetRoute, +} as any) const RedirectTargetViaBeforeLoadRoute = RedirectTargetViaBeforeLoadRouteImport.update({ id: '/via-beforeLoad', path: '/via-beforeLoad', getParentRoute: () => RedirectTargetRoute, } as any) -const RedirectTargetViaLoaderRoute = RedirectTargetViaLoaderRouteImport.update({ - id: '/via-loader', - path: '/via-loader', - getParentRoute: () => RedirectTargetRoute, +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', + getParentRoute: () => rootRouteImport, } as any) -const SpecialCharsMalformedParamRoute = - SpecialCharsMalformedParamRouteImport.update({ - id: '/$param', - path: '/$param', - getParentRoute: () => SpecialCharsMalformedRouteRoute, - } as any) -const SpecialCharsMalformedSearchRoute = - SpecialCharsMalformedSearchRouteImport.update({ - id: '/search', - path: '/search', - getParentRoute: () => SpecialCharsMalformedRouteRoute, +const NotFoundParentBoundaryViaBeforeLoadRoute = + NotFoundParentBoundaryViaBeforeLoadRouteImport.update({ + id: '/via-beforeLoad', + path: '/via-beforeLoad', + getParentRoute: () => NotFoundParentBoundaryRouteRoute, } as any) +const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => ApiUsersRoute, +} as any) +const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ + id: '/layout-b', + path: '/layout-b', + getParentRoute: () => LayoutLayout2Route, +} as any) +const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => LayoutLayout2Route, +} as any) const RedirectTargetServerFnIndexRoute = RedirectTargetServerFnIndexRouteImport.update({ id: '/serverFn/', path: '/serverFn/', getParentRoute: () => RedirectTargetRoute, } as any) -const RedirectTargetServerFnViaBeforeLoadRoute = - RedirectTargetServerFnViaBeforeLoadRouteImport.update({ - id: '/serverFn/via-beforeLoad', - path: '/serverFn/via-beforeLoad', +const RedirectTargetServerFnViaUseServerFnRoute = + RedirectTargetServerFnViaUseServerFnRouteImport.update({ + id: '/serverFn/via-useServerFn', + path: '/serverFn/via-useServerFn', getParentRoute: () => RedirectTargetRoute, } as any) const RedirectTargetServerFnViaLoaderRoute = @@ -359,10 +359,10 @@ const RedirectTargetServerFnViaLoaderRoute = path: '/serverFn/via-loader', getParentRoute: () => RedirectTargetRoute, } as any) -const RedirectTargetServerFnViaUseServerFnRoute = - RedirectTargetServerFnViaUseServerFnRouteImport.update({ - id: '/serverFn/via-useServerFn', - path: '/serverFn/via-useServerFn', +const RedirectTargetServerFnViaBeforeLoadRoute = + RedirectTargetServerFnViaBeforeLoadRouteImport.update({ + id: '/serverFn/via-beforeLoad', + path: '/serverFn/via-beforeLoad', getParentRoute: () => RedirectTargetRoute, } as any) @@ -728,81 +728,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_layout': { - id: '/_layout' - path: '' - fullPath: '/' - preLoaderRoute: typeof LayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport - 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': { - id: '/not-found' - path: '/not-found' - fullPath: '/not-found' - preLoaderRoute: typeof NotFoundRouteRouteImport - parentRoute: typeof rootRouteImport - } - '/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 + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport parentRoute: typeof rootRouteImport } '/stream': { @@ -812,152 +742,89 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof StreamRouteImport parentRoute: typeof rootRouteImport } - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport + '/scripts': { + id: '/scripts' + path: '/scripts' + fullPath: '/scripts' + preLoaderRoute: typeof ScriptsRouteImport parentRoute: typeof rootRouteImport } - '/_layout/_layout-2': { - id: '/_layout/_layout-2' + '/raw-stream': { + id: '/raw-stream' + path: '/raw-stream' + fullPath: '/raw-stream' + preLoaderRoute: typeof RawStreamRouteImport + parentRoute: typeof rootRouteImport + } + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } + '/links': { + id: '/links' + path: '/links' + fullPath: '/links' + preLoaderRoute: typeof LinksRouteImport + parentRoute: typeof rootRouteImport + } + '/inline-scripts': { + id: '/inline-scripts' + path: '/inline-scripts' + fullPath: '/inline-scripts' + preLoaderRoute: typeof InlineScriptsRouteImport + parentRoute: typeof rootRouteImport + } + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout': { + id: '/_layout' path: '' fullPath: '/' - preLoaderRoute: typeof LayoutLayout2RouteImport - parentRoute: typeof LayoutRoute - } - '/api/users': { - id: '/api/users' - path: '/api/users' - fullPath: '/api/users' - preLoaderRoute: typeof ApiUsersRouteImport + preLoaderRoute: typeof LayoutRouteImport parentRoute: typeof rootRouteImport } - '/multi-cookie-redirect/': { - id: '/multi-cookie-redirect/' - path: '/multi-cookie-redirect' - fullPath: '/multi-cookie-redirect/' - preLoaderRoute: typeof MultiCookieRedirectIndexRouteImport + '/specialChars': { + id: '/specialChars' + path: '/specialChars' + fullPath: '/specialChars' + preLoaderRoute: typeof SpecialCharsRouteRouteImport 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 + '/search-params': { + id: '/search-params' + path: '/search-params' + fullPath: '/search-params' + preLoaderRoute: typeof SearchParamsRouteRouteImport parentRoute: typeof rootRouteImport } - '/not-found/': { - id: '/not-found/' + '/not-found': { + id: '/not-found' + path: '/not-found' + fullPath: '/not-found' + preLoaderRoute: typeof NotFoundRouteRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' path: '/' - fullPath: '/not-found/' - preLoaderRoute: typeof NotFoundIndexRouteImport - parentRoute: typeof NotFoundRouteRoute - } - '/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': { - id: '/not-found/via-beforeLoad' - path: '/via-beforeLoad' - fullPath: '/not-found/via-beforeLoad' - preLoaderRoute: typeof NotFoundViaBeforeLoadRouteImport - parentRoute: typeof NotFoundRouteRoute - } - '/not-found/via-beforeLoad-target-root': { - id: '/not-found/via-beforeLoad-target-root' - path: '/via-beforeLoad-target-root' - fullPath: '/not-found/via-beforeLoad-target-root' - preLoaderRoute: typeof NotFoundViaBeforeLoadTargetRootRouteImport - parentRoute: typeof NotFoundRouteRoute - } - '/not-found/via-loader': { - id: '/not-found/via-loader' - path: '/via-loader' - fullPath: '/not-found/via-loader' - preLoaderRoute: typeof NotFoundViaLoaderRouteImport - parentRoute: typeof NotFoundRouteRoute - } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute - } - '/raw-stream/': { - id: '/raw-stream/' - path: '/' - fullPath: '/raw-stream/' - preLoaderRoute: typeof RawStreamIndexRouteImport - parentRoute: typeof RawStreamRoute - } - '/raw-stream/client-call': { - id: '/raw-stream/client-call' - path: '/client-call' - fullPath: '/raw-stream/client-call' - preLoaderRoute: typeof RawStreamClientCallRouteImport - parentRoute: typeof RawStreamRoute - } - '/raw-stream/ssr-binary-hint': { - id: '/raw-stream/ssr-binary-hint' - path: '/ssr-binary-hint' - fullPath: '/raw-stream/ssr-binary-hint' - preLoaderRoute: typeof RawStreamSsrBinaryHintRouteImport - parentRoute: typeof RawStreamRoute - } - '/raw-stream/ssr-mixed': { - id: '/raw-stream/ssr-mixed' - path: '/ssr-mixed' - fullPath: '/raw-stream/ssr-mixed' - preLoaderRoute: typeof RawStreamSsrMixedRouteImport - parentRoute: typeof RawStreamRoute - } - '/raw-stream/ssr-multiple': { - id: '/raw-stream/ssr-multiple' - path: '/ssr-multiple' - fullPath: '/raw-stream/ssr-multiple' - preLoaderRoute: typeof RawStreamSsrMultipleRouteImport - parentRoute: typeof RawStreamRoute - } - '/raw-stream/ssr-single': { - id: '/raw-stream/ssr-single' - path: '/ssr-single' - fullPath: '/raw-stream/ssr-single' - preLoaderRoute: typeof RawStreamSsrSingleRouteImport - parentRoute: typeof RawStreamRoute - } - '/raw-stream/ssr-text-hint': { - id: '/raw-stream/ssr-text-hint' - path: '/ssr-text-hint' - fullPath: '/raw-stream/ssr-text-hint' - preLoaderRoute: typeof RawStreamSsrTextHintRouteImport - parentRoute: typeof RawStreamRoute - } - '/redirect/': { - id: '/redirect/' - path: '/redirect' - fullPath: '/redirect/' - preLoaderRoute: typeof RedirectIndexRouteImport + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/redirect/$target': { - id: '/redirect/$target' - path: '/redirect/$target' - fullPath: '/redirect/$target' - preLoaderRoute: typeof RedirectTargetRouteImport - parentRoute: typeof rootRouteImport + '/users/': { + id: '/users/' + path: '/' + fullPath: '/users/' + preLoaderRoute: typeof UsersIndexRouteImport + parentRoute: typeof UsersRoute } '/search-params/': { id: '/search-params/' @@ -966,39 +833,53 @@ declare module '@tanstack/vue-router' { 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 + '/redirect/': { + id: '/redirect/' + path: '/redirect' + fullPath: '/redirect/' + preLoaderRoute: typeof RedirectIndexRouteImport + parentRoute: typeof rootRouteImport } - '/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 + '/raw-stream/': { + id: '/raw-stream/' + path: '/' + fullPath: '/raw-stream/' + preLoaderRoute: typeof RawStreamIndexRouteImport + parentRoute: typeof RawStreamRoute } - '/specialChars/$param': { - id: '/specialChars/$param' - path: '/$param' - fullPath: '/specialChars/$param' - preLoaderRoute: typeof SpecialCharsParamRouteImport - parentRoute: typeof SpecialCharsRouteRoute + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRoute } - '/specialChars/hash': { - id: '/specialChars/hash' - path: '/hash' - fullPath: '/specialChars/hash' - preLoaderRoute: typeof SpecialCharsHashRouteImport - parentRoute: typeof SpecialCharsRouteRoute + '/not-found/': { + id: '/not-found/' + path: '/' + fullPath: '/not-found/' + preLoaderRoute: typeof NotFoundIndexRouteImport + parentRoute: typeof NotFoundRouteRoute } - '/specialChars/malformed': { - id: '/specialChars/malformed' - path: '/malformed' - fullPath: '/specialChars/malformed' - preLoaderRoute: typeof SpecialCharsMalformedRouteRouteImport + '/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 + } + '/specialChars/대한민국': { + id: '/specialChars/대한민국' + path: '/대한민국' + fullPath: '/specialChars/대한민국' + preLoaderRoute: typeof SpecialCharsChar45824Char54620Char48124Char44397RouteImport parentRoute: typeof SpecialCharsRouteRoute } '/specialChars/search': { @@ -1008,62 +889,146 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof SpecialCharsSearchRouteImport parentRoute: typeof SpecialCharsRouteRoute } - '/specialChars/대한민국': { - id: '/specialChars/대한민국' - path: '/대한민국' - fullPath: '/specialChars/대한민국' - preLoaderRoute: typeof SpecialCharsChar45824Char54620Char48124Char44397RouteImport + '/specialChars/hash': { + id: '/specialChars/hash' + path: '/hash' + fullPath: '/specialChars/hash' + preLoaderRoute: typeof SpecialCharsHashRouteImport parentRoute: typeof SpecialCharsRouteRoute } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute + '/specialChars/$param': { + id: '/specialChars/$param' + path: '/$param' + fullPath: '/specialChars/$param' + preLoaderRoute: typeof SpecialCharsParamRouteImport + parentRoute: typeof SpecialCharsRouteRoute } - '/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 } - '/_layout/_layout-2/layout-a': { - id: '/_layout/_layout-2/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof LayoutLayout2LayoutARouteImport - parentRoute: typeof LayoutLayout2Route + '/search-params/default': { + id: '/search-params/default' + path: '/default' + fullPath: '/search-params/default' + preLoaderRoute: typeof SearchParamsDefaultRouteImport + parentRoute: typeof SearchParamsRouteRoute } - '/_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 + '/redirect/$target': { + id: '/redirect/$target' + path: '/redirect/$target' + fullPath: '/redirect/$target' + preLoaderRoute: typeof RedirectTargetRouteImport parentRoute: typeof rootRouteImport } + '/raw-stream/ssr-text-hint': { + id: '/raw-stream/ssr-text-hint' + path: '/ssr-text-hint' + fullPath: '/raw-stream/ssr-text-hint' + preLoaderRoute: typeof RawStreamSsrTextHintRouteImport + parentRoute: typeof RawStreamRoute + } + '/raw-stream/ssr-single': { + id: '/raw-stream/ssr-single' + path: '/ssr-single' + fullPath: '/raw-stream/ssr-single' + preLoaderRoute: typeof RawStreamSsrSingleRouteImport + parentRoute: typeof RawStreamRoute + } + '/raw-stream/ssr-multiple': { + id: '/raw-stream/ssr-multiple' + path: '/ssr-multiple' + fullPath: '/raw-stream/ssr-multiple' + preLoaderRoute: typeof RawStreamSsrMultipleRouteImport + parentRoute: typeof RawStreamRoute + } + '/raw-stream/ssr-mixed': { + id: '/raw-stream/ssr-mixed' + path: '/ssr-mixed' + fullPath: '/raw-stream/ssr-mixed' + preLoaderRoute: typeof RawStreamSsrMixedRouteImport + parentRoute: typeof RawStreamRoute + } + '/raw-stream/ssr-binary-hint': { + id: '/raw-stream/ssr-binary-hint' + path: '/ssr-binary-hint' + fullPath: '/raw-stream/ssr-binary-hint' + preLoaderRoute: typeof RawStreamSsrBinaryHintRouteImport + parentRoute: typeof RawStreamRoute + } + '/raw-stream/client-call': { + id: '/raw-stream/client-call' + path: '/client-call' + fullPath: '/raw-stream/client-call' + preLoaderRoute: typeof RawStreamClientCallRouteImport + parentRoute: typeof RawStreamRoute + } + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRoute + } + '/not-found/via-loader': { + id: '/not-found/via-loader' + path: '/via-loader' + fullPath: '/not-found/via-loader' + preLoaderRoute: typeof NotFoundViaLoaderRouteImport + parentRoute: typeof NotFoundRouteRoute + } + '/not-found/via-beforeLoad-target-root': { + id: '/not-found/via-beforeLoad-target-root' + path: '/via-beforeLoad-target-root' + fullPath: '/not-found/via-beforeLoad-target-root' + preLoaderRoute: typeof NotFoundViaBeforeLoadTargetRootRouteImport + parentRoute: typeof NotFoundRouteRoute + } + '/not-found/via-beforeLoad': { + id: '/not-found/via-beforeLoad' + path: '/via-beforeLoad' + fullPath: '/not-found/via-beforeLoad' + preLoaderRoute: typeof NotFoundViaBeforeLoadRouteImport + parentRoute: typeof NotFoundRouteRoute + } + '/multi-cookie-redirect/target': { + id: '/multi-cookie-redirect/target' + path: '/multi-cookie-redirect/target' + fullPath: '/multi-cookie-redirect/target' + preLoaderRoute: typeof MultiCookieRedirectTargetRouteImport + parentRoute: typeof rootRouteImport + } + '/api/users': { + id: '/api/users' + path: '/api/users' + fullPath: '/api/users' + preLoaderRoute: typeof ApiUsersRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout/_layout-2': { + id: '/_layout/_layout-2' + path: '' + fullPath: '/' + preLoaderRoute: typeof LayoutLayout2RouteImport + parentRoute: typeof LayoutRoute + } + '/specialChars/malformed': { + id: '/specialChars/malformed' + path: '/malformed' + fullPath: '/specialChars/malformed' + preLoaderRoute: typeof SpecialCharsMalformedRouteRouteImport + parentRoute: typeof SpecialCharsRouteRoute + } + '/not-found/parent-boundary': { + id: '/not-found/parent-boundary' + path: '/parent-boundary' + fullPath: '/not-found/parent-boundary' + preLoaderRoute: typeof NotFoundParentBoundaryRouteRouteImport + parentRoute: typeof NotFoundRouteRoute + } '/redirect/$target/': { id: '/redirect/$target/' path: '/' @@ -1071,6 +1036,27 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof RedirectTargetIndexRouteImport parentRoute: typeof RedirectTargetRoute } + '/specialChars/malformed/search': { + id: '/specialChars/malformed/search' + path: '/search' + fullPath: '/specialChars/malformed/search' + preLoaderRoute: typeof SpecialCharsMalformedSearchRouteImport + parentRoute: typeof SpecialCharsMalformedRouteRoute + } + '/specialChars/malformed/$param': { + id: '/specialChars/malformed/$param' + path: '/$param' + fullPath: '/specialChars/malformed/$param' + preLoaderRoute: typeof SpecialCharsMalformedParamRouteImport + parentRoute: typeof SpecialCharsMalformedRouteRoute + } + '/redirect/$target/via-loader': { + id: '/redirect/$target/via-loader' + path: '/via-loader' + fullPath: '/redirect/$target/via-loader' + preLoaderRoute: typeof RedirectTargetViaLoaderRouteImport + parentRoute: typeof RedirectTargetRoute + } '/redirect/$target/via-beforeLoad': { id: '/redirect/$target/via-beforeLoad' path: '/via-beforeLoad' @@ -1078,26 +1064,40 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof RedirectTargetViaBeforeLoadRouteImport parentRoute: typeof RedirectTargetRoute } - '/redirect/$target/via-loader': { - id: '/redirect/$target/via-loader' - path: '/via-loader' - fullPath: '/redirect/$target/via-loader' - preLoaderRoute: typeof RedirectTargetViaLoaderRouteImport - parentRoute: typeof RedirectTargetRoute + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport + parentRoute: typeof rootRouteImport } - '/specialChars/malformed/$param': { - id: '/specialChars/malformed/$param' - path: '/$param' - fullPath: '/specialChars/malformed/$param' - preLoaderRoute: typeof SpecialCharsMalformedParamRouteImport - parentRoute: typeof SpecialCharsMalformedRouteRoute + '/not-found/parent-boundary/via-beforeLoad': { + id: '/not-found/parent-boundary/via-beforeLoad' + path: '/via-beforeLoad' + fullPath: '/not-found/parent-boundary/via-beforeLoad' + preLoaderRoute: typeof NotFoundParentBoundaryViaBeforeLoadRouteImport + parentRoute: typeof NotFoundParentBoundaryRouteRoute } - '/specialChars/malformed/search': { - id: '/specialChars/malformed/search' - path: '/search' - fullPath: '/specialChars/malformed/search' - preLoaderRoute: typeof SpecialCharsMalformedSearchRouteImport - parentRoute: typeof SpecialCharsMalformedRouteRoute + '/api/users/$userId': { + id: '/api/users/$userId' + path: '/$userId' + fullPath: '/api/users/$userId' + preLoaderRoute: typeof ApiUsersUserIdRouteImport + parentRoute: typeof ApiUsersRoute + } + '/_layout/_layout-2/layout-b': { + id: '/_layout/_layout-2/layout-b' + path: '/layout-b' + fullPath: '/layout-b' + preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport + parentRoute: typeof LayoutLayout2Route + } + '/_layout/_layout-2/layout-a': { + id: '/_layout/_layout-2/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof LayoutLayout2LayoutARouteImport + parentRoute: typeof LayoutLayout2Route } '/redirect/$target/serverFn/': { id: '/redirect/$target/serverFn/' @@ -1106,11 +1106,11 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof RedirectTargetServerFnIndexRouteImport parentRoute: typeof RedirectTargetRoute } - '/redirect/$target/serverFn/via-beforeLoad': { - id: '/redirect/$target/serverFn/via-beforeLoad' - path: '/serverFn/via-beforeLoad' - fullPath: '/redirect/$target/serverFn/via-beforeLoad' - preLoaderRoute: typeof RedirectTargetServerFnViaBeforeLoadRouteImport + '/redirect/$target/serverFn/via-useServerFn': { + id: '/redirect/$target/serverFn/via-useServerFn' + path: '/serverFn/via-useServerFn' + fullPath: '/redirect/$target/serverFn/via-useServerFn' + preLoaderRoute: typeof RedirectTargetServerFnViaUseServerFnRouteImport parentRoute: typeof RedirectTargetRoute } '/redirect/$target/serverFn/via-loader': { @@ -1120,11 +1120,11 @@ declare module '@tanstack/vue-router' { 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 + '/redirect/$target/serverFn/via-beforeLoad': { + id: '/redirect/$target/serverFn/via-beforeLoad' + path: '/serverFn/via-beforeLoad' + fullPath: '/redirect/$target/serverFn/via-beforeLoad' + preLoaderRoute: typeof RedirectTargetServerFnViaBeforeLoadRouteImport parentRoute: typeof RedirectTargetRoute } } diff --git a/e2e/vue-start/basic/src/routes/__root.tsx b/e2e/vue-start/basic/src/routes/__root.tsx index 9da2c581fe..45b729c19c 100644 --- a/e2e/vue-start/basic/src/routes/__root.tsx +++ b/e2e/vue-start/basic/src/routes/__root.tsx @@ -1,135 +1,19 @@ /// -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 '~/styles/app.css' +import appCss from '~/styles/app.css?url' 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: [ @@ -144,6 +28,7 @@ export const Route = createRootRoute({ }), ], links: [ + { rel: 'stylesheet', href: appCss }, { rel: 'apple-touch-icon', sizes: '180x180', @@ -176,11 +61,107 @@ export const Route = createRootRoute({ }, ], }), - errorComponent: (props) => ( -

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

- ), + errorComponent: (props) =>

{props.error.stack}

, notFoundComponent: () => , component: RootComponent, }) + +function RootComponent() { + return ( + + + + + +
+ + Home + {' '} + + Posts + {' '} + + Users + {' '} + + Layout + {' '} + + Scripts + {' '} + + Inline Scripts + {' '} + + Deferred + {' '} + + redirect + {' '} + + Raw Stream + {' '} + + This Route Does Not Exist + +
+ +
This is an inline styled div
+ + + + + ) +} diff --git a/e2e/vue-start/basic/src/routes/api/users.$userId.ts b/e2e/vue-start/basic/src/routes/api/users.$userId.ts index 24938d51c2..50b9ca995a 100644 --- a/e2e/vue-start/basic/src/routes/api/users.$userId.ts +++ b/e2e/vue-start/basic/src/routes/api/users.$userId.ts @@ -1,15 +1,19 @@ import { createFileRoute } from '@tanstack/vue-router' import type { User } from '~/utils/users' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} + export const Route = createFileRoute('/api/users/$userId')({ server: { handlers: { GET: async ({ params, request }) => { console.info(`Fetching users by id=${params.userId}... @`, request.url) try { - const res = await fetch( - `https://jsonplaceholder.typicode.com/users/${params.userId}`, - ) + const res = await fetch(`${queryURL}/users/${params.userId}`) if (!res.ok) { throw new Error('Failed to fetch user') } diff --git a/e2e/vue-start/basic/src/routes/api/users.ts b/e2e/vue-start/basic/src/routes/api/users.ts index c6045977b8..97989b93ca 100644 --- a/e2e/vue-start/basic/src/routes/api/users.ts +++ b/e2e/vue-start/basic/src/routes/api/users.ts @@ -38,13 +38,19 @@ const testMiddleware = createMiddleware() return result }) +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} + export const Route = createFileRoute('/api/users')({ server: { middleware: [testMiddleware, userLoggerMiddleware, testParentMiddleware], handlers: { GET: async ({ request }) => { console.info('Fetching users... @', request.url) - const res = await fetch('https://jsonplaceholder.typicode.com/users') + const res = await fetch(`${queryURL}/users`) if (!res.ok) { throw new Error('Failed to fetch users') } diff --git a/e2e/vue-start/basic/src/routes/deferred.tsx b/e2e/vue-start/basic/src/routes/deferred.tsx index 18aae161ab..4f8fcd600c 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' }) - .validator((data: { name: string }) => data) + .inputValidator((data: { name: string }) => data) .handler(({ data }) => { return { name: data.name, randomNumber: Math.floor(Math.random() * 100) } }) const slowServerFn = createServerFn({ method: 'GET' }) - .validator((data: { name: string }) => data) + .inputValidator((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 ecd12d1dad..9f7e3b4b33 100644 --- a/e2e/vue-start/basic/src/routes/not-found/index.tsx +++ b/e2e/vue-start/basic/src/routes/not-found/index.tsx @@ -1,10 +1,9 @@ -import { defineComponent } from 'vue' import { Link, createFileRoute } from '@tanstack/vue-router' -const RouteComponent = defineComponent({ - setup() { +export const Route = createFileRoute('/not-found/')({ + component: () => { const preload = Route.useSearch({ select: (s) => s.preload }) - return () => ( + return (
( -
-
- {loaderData.value.parentLoaderData} -
-
- ) - }, -}) - export const Route = createFileRoute('/not-found/parent-boundary')({ loader: () => ({ parentLoaderData: 'ready', @@ -29,3 +15,15 @@ function RouteComponent() {
) } + +function ParentBoundaryNotFoundComponent() { + const loaderData = Route.useLoaderData() + + return ( +
+
+ {loaderData.value.parentLoaderData} +
+
+ ) +} diff --git a/e2e/vue-start/basic/src/routes/posts.$postId.tsx b/e2e/vue-start/basic/src/routes/posts.$postId.tsx index edda7f0017..4d71080d64 100644 --- a/e2e/vue-start/basic/src/routes/posts.$postId.tsx +++ b/e2e/vue-start/basic/src/routes/posts.$postId.tsx @@ -1,32 +1,9 @@ -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, @@ -35,3 +12,24 @@ 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 64d4754f2f..1a9d58a31d 100644 --- a/e2e/vue-start/basic/src/routes/posts.tsx +++ b/e2e/vue-start/basic/src/routes/posts.tsx @@ -1,36 +1,7 @@ -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: [ @@ -42,3 +13,30 @@ 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 f77ae7d3ab..a52c6f32f7 100644 --- a/e2e/vue-start/basic/src/routes/posts_.$postId.deep.tsx +++ b/e2e/vue-start/basic/src/routes/posts_.$postId.deep.tsx @@ -1,26 +1,24 @@ -import { defineComponent } from 'vue' import { Link, createFileRoute } from '@tanstack/vue-router' import { PostErrorComponent } from '~/components/PostErrorComponent' import { fetchPost } from '~/utils/posts' -const PostDeepComponent = defineComponent({ - setup() { - const post = Route.useLoaderData() - return () => ( -
- - ← All Posts - -

{post.value.title}

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

{post.value.title}

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

redirect test with server functions (target {params.value.target}) @@ -88,7 +87,3 @@ const RouteComponent = defineComponent({ ) }, }) - -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 093a591636..399e8ac995 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,12 +1,13 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { RedirectOnClick } from '~/components/RedirectOnClick' -const RouteComponent = defineComponent({ - setup() { +export const Route = createFileRoute( + '/redirect/$target/serverFn/via-useServerFn', +)({ + component: () => { 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'), @@ -29,5 +15,14 @@ export const Route = createFileRoute('/search-params/default')({ throw new Error('Context hello is not "world"') } }, - component: RouteComponent, + component: () => { + const search = Route.useSearch() + const context = Route.useRouteContext() + return ( + <> +
{search.value.default}
+
{context.value.hello}
+ + ) + }, }) 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 ccd1276387..14b137abc6 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,19 +1,6 @@ -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(), @@ -27,5 +14,13 @@ export const Route = createFileRoute('/search-params/loader-throws-redirect')({ }) } }, - component: RouteComponent, + component: () => { + const search = Route.useSearch() + return ( +
+

SearchParams

+
{search.value.step}
+
+ ) + }, }) diff --git a/e2e/vue-start/basic/src/routes/specialChars/$param.tsx b/e2e/vue-start/basic/src/routes/specialChars/$param.tsx index ec315ede1f..de3cba0a97 100644 --- a/e2e/vue-start/basic/src/routes/specialChars/$param.tsx +++ b/e2e/vue-start/basic/src/routes/specialChars/$param.tsx @@ -1,18 +1,15 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' -const RouteComponent = defineComponent({ - setup() { - const params = Route.useParams() - return () => ( -
- Hello "/specialChars/$param":{' '} - {params.value.param} -
- ) - }, -}) - export const Route = createFileRoute('/specialChars/$param')({ component: RouteComponent, }) + +function RouteComponent() { + const params = Route.useParams() + return ( +
+ Hello "/specialChars/$param":{' '} + {params.value.param} +
+ ) +} diff --git a/e2e/vue-start/basic/src/routes/specialChars/malformed/$param.tsx b/e2e/vue-start/basic/src/routes/specialChars/malformed/$param.tsx index 2b19e7e36e..7160964549 100644 --- a/e2e/vue-start/basic/src/routes/specialChars/malformed/$param.tsx +++ b/e2e/vue-start/basic/src/routes/specialChars/malformed/$param.tsx @@ -1,20 +1,15 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' -const RouteComponent = defineComponent({ - setup() { - const params = Route.useParams() - return () => ( -
- Hello "/specialChars/malformed/$param":{' '} - - {params.value.param} - -
- ) - }, -}) - export const Route = createFileRoute('/specialChars/malformed/$param')({ component: RouteComponent, }) + +function RouteComponent() { + const params = Route.useParams() + return ( +
+ Hello "/specialChars/malformed/$param":{' '} + {params.value.param} +
+ ) +} diff --git a/e2e/vue-start/basic/src/routes/specialChars/malformed/search.tsx b/e2e/vue-start/basic/src/routes/specialChars/malformed/search.tsx index 8d6ad5b1dd..2438604954 100644 --- a/e2e/vue-start/basic/src/routes/specialChars/malformed/search.tsx +++ b/e2e/vue-start/basic/src/routes/specialChars/malformed/search.tsx @@ -1,24 +1,22 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import z from 'zod' -const RouteComponent = defineComponent({ - setup() { - const search = Route.useSearch() - return () => ( -
- Hello "/specialChars/malformed/search"! - - {search.value.searchParam} - -
- ) - }, -}) - export const Route = createFileRoute('/specialChars/malformed/search')({ validateSearch: z.object({ searchParam: z.string(), }), component: RouteComponent, }) + +function RouteComponent() { + const search = Route.useSearch() + + return ( +
+ Hello "/specialChars/malformed/search"! + + {search.value.searchParam} + +
+ ) +} diff --git a/e2e/vue-start/basic/src/routes/specialChars/search.tsx b/e2e/vue-start/basic/src/routes/specialChars/search.tsx index b4e022639d..5ba858e747 100644 --- a/e2e/vue-start/basic/src/routes/specialChars/search.tsx +++ b/e2e/vue-start/basic/src/routes/specialChars/search.tsx @@ -1,24 +1,22 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import z from 'zod' -const RouteComponent = defineComponent({ - setup() { - const search = Route.useSearch() - return () => ( -
- Hello "/specialChars/search"! - - {search.value.searchParam} - -
- ) - }, -}) - export const Route = createFileRoute('/specialChars/search')({ validateSearch: z.object({ searchParam: z.string(), }), component: RouteComponent, }) + +function RouteComponent() { + const search = Route.useSearch() + + return ( +
+ Hello "/specialChars/search"! + + {search.value.searchParam} + +
+ ) +} diff --git a/e2e/vue-start/basic/src/routes/users.$userId.tsx b/e2e/vue-start/basic/src/routes/users.$userId.tsx index 76340cf9fb..420b7e4a50 100644 --- a/e2e/vue-start/basic/src/routes/users.$userId.tsx +++ b/e2e/vue-start/basic/src/routes/users.$userId.tsx @@ -1,4 +1,3 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import axios from 'redaxios' @@ -7,18 +6,6 @@ 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() @@ -35,3 +22,14 @@ 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 3d8ef31598..1e0b297dd2 100644 --- a/e2e/vue-start/basic/src/routes/users.tsx +++ b/e2e/vue-start/basic/src/routes/users.tsx @@ -1,41 +1,9 @@ -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() @@ -48,3 +16,33 @@ export const Route = createFileRoute('/users')({ }, component: UsersComponent, }) + +function UsersComponent() { + const users = Route.useLoaderData() + + return ( +
+
    + {[ + ...users.value, + { id: 'i-do-not-exist', name: 'Non-existent User', email: '' }, + ].map((user) => ( +
  • + +
    {user.name}
    + +
  • + ))} +
+
+ +
+ ) +} diff --git a/e2e/vue-start/basic/src/utils/posts.tsx b/e2e/vue-start/basic/src/utils/posts.tsx index d8e2dc7450..a193bbc7af 100644 --- a/e2e/vue-start/basic/src/utils/posts.tsx +++ b/e2e/vue-start/basic/src/utils/posts.tsx @@ -8,12 +8,18 @@ export type PostType = { body: string } +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} + export const fetchPost = createServerFn({ method: 'GET' }) - .validator((postId: string) => postId) + .inputValidator((postId: string) => postId) .handler(async ({ data: postId }) => { console.info(`Fetching post with id ${postId}...`) const post = await axios - .get(`https://jsonplaceholder.typicode.com/posts/${postId}`) + .get(`${queryURL}/posts/${postId}`) .then((r) => r.data) .catch((err) => { console.error(err) @@ -30,7 +36,7 @@ export const fetchPosts = createServerFn({ method: 'GET' }).handler( async () => { console.info('Fetching posts...') return axios - .get>('https://jsonplaceholder.typicode.com/posts') + .get>(`${queryURL}/posts`) .then((r) => r.data.slice(0, 10)) }, ) diff --git a/e2e/vue-start/basic/src/utils/users.tsx b/e2e/vue-start/basic/src/utils/users.tsx index 7ba645b383..46be4b1580 100644 --- a/e2e/vue-start/basic/src/utils/users.tsx +++ b/e2e/vue-start/basic/src/utils/users.tsx @@ -3,3 +3,7 @@ export type User = { name: string email: string } + +const PORT = process.env.VITE_SERVER_PORT || 3000 + +export const DEPLOY_URL = `http://localhost:${PORT}` diff --git a/e2e/vue-start/basic/src/vite-env.d.ts b/e2e/vue-start/basic/src/vite-env.d.ts index 4da6234c8a..e8259b1e33 100644 --- a/e2e/vue-start/basic/src/vite-env.d.ts +++ b/e2e/vue-start/basic/src/vite-env.d.ts @@ -2,6 +2,7 @@ interface ImportMetaEnv { readonly VITE_NODE_ENV: string + readonly VITE_EXTERNAL_PORT: string readonly VITE_SERVER_PORT: string } diff --git a/e2e/vue-start/basic/tests/fixture-api.spec.ts b/e2e/vue-start/basic/tests/fixture-api.spec.ts deleted file mode 100644 index 6c9b26dc4c..0000000000 --- a/e2e/vue-start/basic/tests/fixture-api.spec.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { expect, test } from '@playwright/test' - -test('server API receives canned users without a fixture listener', async ({ - request, -}) => { - const response = await request.get('/api/users') - expect(response.ok()).toBe(true) - const users = await response.json() - expect(users).toHaveLength(10) - expect(users[0]).toMatchObject({ id: 1, name: 'Leanne Graham' }) -}) diff --git a/e2e/vue-start/basic/tests/not-found.spec.ts b/e2e/vue-start/basic/tests/not-found.spec.ts index cfc60fe5e4..100f4aa393 100644 --- a/e2e/vue-start/basic/tests/not-found.spec.ts +++ b/e2e/vue-start/basic/tests/not-found.spec.ts @@ -1,7 +1,7 @@ import { expect } from '@playwright/test' import combinateImport from 'combinate' import { test } from '@tanstack/router-e2e-utils' -import { isSpaMode } from './utils/isSpaMode' +import { isSpaMode } from '../tests/utils/isSpaMode' // somehow playwright does not correctly import default exports const combinate = (combinateImport as any).default as typeof combinateImport diff --git a/e2e/vue-start/basic/tests/prerendering.spec.ts b/e2e/vue-start/basic/tests/prerendering.spec.ts index ddcf720a4c..8506ff9b06 100644 --- a/e2e/vue-start/basic/tests/prerendering.spec.ts +++ b/e2e/vue-start/basic/tests/prerendering.spec.ts @@ -4,17 +4,13 @@ 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) @@ -38,6 +34,7 @@ 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 8e6ceba5b9..b52ce026af 100644 --- a/e2e/vue-start/basic/tests/redirect.spec.ts +++ b/e2e/vue-start/basic/tests/redirect.spec.ts @@ -1,27 +1,22 @@ import queryString from 'node:querystring' import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' import combinateImport from 'combinate' -import type { Page } from '@playwright/test' +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' // somehow playwright does not correctly import default exports const combinate = (combinateImport as any).default as typeof combinateImport -const PORT = Number(process.env.E2E_APP_PORT ?? 0) -const EXTERNAL_ORIGIN = `http://127.0.0.1:${PORT}` -const 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() -} +const PORT = await getTestServerPort( + `${packageJson.name}${isSpaMode ? '_spa' : ''}${isPreview ? '_preview' : ''}`, +) +const EXTERNAL_HOST_PORT = await getDummyServerPort(packageJson.name) test.describe('redirects', () => { const internalNavigationTestMatrix = combinate({ @@ -42,7 +37,7 @@ test.describe('redirects', () => { `via-${thrower}${reloadDocument ? '-reloadDocument' : ''}`, ) - await waitForRouterIdle(page) + await page.waitForLoadState('networkidle') let requestHappened = false const requestPromise = new Promise((resolve) => { @@ -70,7 +65,11 @@ test.describe('redirects', () => { await link.click() - await waitForPostsIndex(page) + const url = `http://localhost:${PORT}/posts` + + await page.waitForURL(url) + expect(page.url()).toBe(url) + await expect(page.getByTestId('PostsIndexComponent')).toBeInViewport() expect(fullPageLoad).toBe(reloadDocument) }) }, @@ -87,7 +86,12 @@ test.describe('redirects', () => { }) => { await page.goto(`/redirect/internal/via-${thrower}`) - await waitForPostsIndex(page) + 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() }) }) @@ -101,12 +105,12 @@ test.describe('redirects', () => { page, }) => { const q = queryString.stringify({ - externalHost: `${EXTERNAL_ORIGIN}/`, + externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, }) if (scenario === 'navigate') { await page.goto(`/redirect/external?${q}`) - await waitForRouterIdle(page) + await page.waitForLoadState('networkidle') const link = page.getByTestId(`via-${thrower}`) await link.focus() await link.click() @@ -114,7 +118,7 @@ test.describe('redirects', () => { await page.goto(`/redirect/external/via-${thrower}?${q}`) } - const url = `${EXTERNAL_ORIGIN}/` + const url = `http://localhost:${EXTERNAL_HOST_PORT}/` await page.waitForURL(url) expect(page.url()).toBe(url) @@ -135,13 +139,13 @@ test.describe('redirects', () => { }) => { let fullPageLoad = false const q = queryString.stringify({ - externalHost: `${EXTERNAL_ORIGIN}/`, + externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, reloadDocument, }) if (scenario === 'navigate') { await page.goto(`/redirect/${target}/serverFn?${q}`) - await waitForRouterIdle(page) + await page.waitForLoadState('networkidle') const link = page.getByTestId( `via-${thrower}${reloadDocument ? '-reloadDocument' : ''}`, ) @@ -154,11 +158,13 @@ test.describe('redirects', () => { await page.goto(`/redirect/${target}/serverFn/via-${thrower}?${q}`) } - const url = target === 'internal' ? POSTS_URL : `${EXTERNAL_ORIGIN}/` + const url = + target === 'internal' + ? `http://localhost:${PORT}/posts` + : `http://localhost:${EXTERNAL_HOST_PORT}/` 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) } @@ -176,13 +182,13 @@ test.describe('redirects', () => { page, }) => { const q = queryString.stringify({ - externalHost: `${EXTERNAL_ORIGIN}/`, + externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, reloadDocument, }) await page.goto(`/redirect/${target}/serverFn/via-useServerFn?${q}`) - await waitForRouterIdle(page) + await page.waitForLoadState('networkidle') const button = page.getByTestId('redirect-on-click') @@ -193,11 +199,13 @@ test.describe('redirects', () => { await button.click() - const url = target === 'internal' ? POSTS_URL : `${EXTERNAL_ORIGIN}/` + const url = + target === 'internal' + ? `http://localhost:${PORT}/posts` + : `http://localhost:${EXTERNAL_HOST_PORT}/` 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 cdf5a21b4a..74c1aa54dc 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 './utils/isSpaMode' +import { isSpaMode } from 'tests/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 new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-start/basic/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-start/basic/tests/setup/global.teardown.ts b/e2e/vue-start/basic/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-start/basic/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-start/basic/tests/special-characters.spec.ts b/e2e/vue-start/basic/tests/special-characters.spec.ts index 284097d72b..6bbb240a84 100644 --- a/e2e/vue-start/basic/tests/special-characters.spec.ts +++ b/e2e/vue-start/basic/tests/special-characters.spec.ts @@ -175,12 +175,6 @@ test.describe('Unicode route rendering', () => { }) 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', @@ -188,22 +182,24 @@ test.describe('Unicode route rendering', () => { ], }) - 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) + test('un-matched malformed paths should return not found on direct navigation', async ({ + page, + }) => { + const res = await page.goto('/specialChars/malformed/%E0%A4') - await page.waitForLoadState(`load`) + 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) - } - }) - } + // in spa mode this is caught and handled at server level + if (!isSpaMode) { + expect(res!.status()).toBe(404) + + await expect( + page.getByTestId('default-not-found-component'), + ).toBeInViewport() + } else { + expect(res!.status()).toBe(400) + } + }) test('malformed path params should return not found on router link', async ({ page, diff --git a/e2e/vue-start/basic/tests/utils/getPackageName.ts b/e2e/vue-start/basic/tests/utils/getPackageName.ts deleted file mode 100644 index 6bd2e0499e..0000000000 --- a/e2e/vue-start/basic/tests/utils/getPackageName.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 1b2ac7b943..6d933a5b2c 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 6fe8d5d194..e638e37f36 100644 --- a/e2e/vue-start/basic/vite.config.ts +++ b/e2e/vue-start/basic/vite.config.ts @@ -30,13 +30,8 @@ const prerenderConfiguration = { maxRedirects: 100, } -const outDir = process.env.E2E_DIST_DIR ?? 'dist' - export default defineConfig({ resolve: { tsconfigPaths: true }, - build: { - outDir, - }, server: { port: 3000, }, diff --git a/e2e/vue-start/css-modules/package.json b/e2e/vue-start/css-modules/package.json index 3671774644..c280bcc97f 100644 --- a/e2e/vue-start/css-modules/package.json +++ b/e2e/vue-start/css-modules/package.json @@ -11,7 +11,7 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js", "test:e2e:dev": "MODE=dev playwright test --project=chromium", "test:e2e:prod": "playwright test --project=chromium", - "test:e2e": "pnpm run test:e2e:dev" + "test:e2e": "rm -rf port*.txt; pnpm run test:e2e:dev" }, "dependencies": { "@tanstack/vue-router": "workspace:*", @@ -19,14 +19,13 @@ "vue": "^3.5.16" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@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" + "srvx": "^0.11.9", + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/e2e/vue-start/css-modules/playwright.config.ts b/e2e/vue-start/css-modules/playwright.config.ts index a50ac5ae63..0b810d5372 100644 --- a/e2e/vue-start/css-modules/playwright.config.ts +++ b/e2e/vue-start/css-modules/playwright.config.ts @@ -1,9 +1,10 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } const mode = process.env.MODE ?? 'prod' const isDev = mode === 'dev' -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -12,17 +13,16 @@ export default defineConfig({ reporter: [['line']], globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', use: { baseURL, }, webServer: { - command: isDev - ? `pnpm dev:e2e --port 0` - : `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + command: isDev ? `pnpm dev:e2e` : `pnpm build && PORT=${PORT} pnpm start`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { VITE_NODE_ENV: 'test', diff --git a/e2e/vue-start/css-modules/tests/setup/global.setup.ts b/e2e/vue-start/css-modules/tests/setup/global.setup.ts index 17be637f77..2d3a1db946 100644 --- a/e2e/vue-start/css-modules/tests/setup/global.setup.ts +++ b/e2e/vue-start/css-modules/tests/setup/global.setup.ts @@ -1,9 +1,17 @@ -import { preOptimizeDevServer, waitForServer } from '@tanstack/router-e2e-utils' +import { + e2eStartDummyServer, + getTestServerPort, + preOptimizeDevServer, + waitForServer, +} from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } export default async function setup() { + await e2eStartDummyServer(packageJson.name) + if (process.env.MODE !== 'dev') return - const port = Number(process.env.E2E_APP_PORT ?? 0) + const port = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${port}` await waitForServer(baseURL) diff --git a/e2e/vue-start/css-modules/tests/setup/global.teardown.ts b/e2e/vue-start/css-modules/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-start/css-modules/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-start/css-modules/tsconfig.json b/e2e/vue-start/css-modules/tsconfig.json index 572d840872..8bf3d33789 100644 --- a/e2e/vue-start/css-modules/tsconfig.json +++ b/e2e/vue-start/css-modules/tsconfig.json @@ -14,6 +14,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/vue-start/custom-basepath/express-server.ts b/e2e/vue-start/custom-basepath/express-server.ts index b9bf393466..87dcfb50da 100644 --- a/e2e/vue-start/custom-basepath/express-server.ts +++ b/e2e/vue-start/custom-basepath/express-server.ts @@ -1,6 +1,5 @@ import express from 'express' import { toNodeHandler } from 'srvx/node' -import type { AddressInfo } from 'node:net' import type { NodeHttp1Handler } from 'srvx' const DEVELOPMENT = process.env.NODE_ENV === 'development' @@ -41,11 +40,6 @@ if (DEVELOPMENT) { }) } -const httpServer = app.listen(PORT, (error) => { - if (error) { - throw error - } - console.log( - `E2E app: http://localhost:${(httpServer.address() as AddressInfo).port}`, - ) +app.listen(PORT, () => { + console.log(`Server is running on http://localhost:${PORT}`) }) diff --git a/e2e/vue-start/custom-basepath/package.json b/e2e/vue-start/custom-basepath/package.json index c1032ea88b..6a6970d1ce 100644 --- a/e2e/vue-start/custom-basepath/package.json +++ b/e2e/vue-start/custom-basepath/package.json @@ -8,29 +8,28 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "tsx express-server.ts", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-start": "workspace:^", - "express": "^5.2.1", - "redaxios": "catalog:", + "express": "^5.1.0", + "redaxios": "^0.5.1", "vue": "^3.5.25" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", - "@types/express": "^5.0.6", + "@types/express": "^5.0.3", "@types/node": "^22.10.2", "cross-env": "^10.0.0", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "tsx": "^4.20.3", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", + "typescript": "^5.7.2", + "vite": "^8.0.0", "@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 e113ce64ad..5095425f47 100644 --- a/e2e/vue-start/custom-basepath/playwright.config.ts +++ b/e2e/vue-start/custom-basepath/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}/custom/basepath` /** @@ -13,19 +18,19 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', - env: { - NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, - }, }, projects: [ diff --git a/e2e/vue-start/custom-basepath/src/components/DefaultCatchBoundary.tsx b/e2e/vue-start/custom-basepath/src/components/DefaultCatchBoundary.tsx index 77c03c5afa..b1f818dd74 100644 --- a/e2e/vue-start/custom-basepath/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/custom-basepath/src/components/DefaultCatchBoundary.tsx @@ -1,61 +1,53 @@ -import { defineComponent } from 'vue' -import type { PropType } from 'vue' import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, useRouter, } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' -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 - - )} -
-
- ) - } - }, -}) +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 + + )} +
+
+ ) +} diff --git a/e2e/vue-start/custom-basepath/src/routeTree.gen.ts b/e2e/vue-start/custom-basepath/src/routeTree.gen.ts index 605193fbec..ea7e127d8e 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 IndexRouteImport } from './routes/index' -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 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 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 ApiUsersUserIdRouteImport } from './routes/api/users.$userId' +import { Route as RedirectThrowItRouteImport } from './routes/redirect.throw-it' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as ApiUsersRouteImport } from './routes/api/users' import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' +import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const DeferredRoute = DeferredRouteImport.update({ - id: '/deferred', - path: '/deferred', - getParentRoute: () => rootRouteImport, -} as any) -const LogoutRoute = LogoutRouteImport.update({ - id: '/logout', - path: '/logout', +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', getParentRoute: () => rootRouteImport, } as any) const PostsRoute = PostsRouteImport.update({ @@ -44,34 +34,19 @@ const PostsRoute = PostsRouteImport.update({ path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const LogoutRoute = LogoutRouteImport.update({ + id: '/logout', + path: '/logout', getParentRoute: () => rootRouteImport, } as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', +const DeferredRoute = DeferredRouteImport.update({ + id: '/deferred', + path: '/deferred', getParentRoute: () => rootRouteImport, } as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ +const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', - getParentRoute: () => PostsRoute, -} as any) -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 UsersIndexRoute = UsersIndexRouteImport.update({ @@ -79,21 +54,46 @@ const UsersIndexRoute = UsersIndexRouteImport.update({ path: '/', getParentRoute: () => UsersRoute, } as any) +const RedirectIndexRoute = RedirectIndexRouteImport.update({ + id: '/redirect/', + path: '/redirect/', + getParentRoute: () => rootRouteImport, +} as any) +const PostsIndexRoute = PostsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PostsRoute, +} as any) const UsersUserIdRoute = UsersUserIdRouteImport.update({ id: '/$userId', path: '/$userId', getParentRoute: () => UsersRoute, } as any) -const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => ApiUsersRoute, +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, +} 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, } as any) +const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => ApiUsersRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -205,25 +205,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport - parentRoute: typeof rootRouteImport - } - '/logout': { - id: '/logout' - path: '/logout' - fullPath: '/logout' - preLoaderRoute: typeof LogoutRouteImport + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport parentRoute: typeof rootRouteImport } '/posts': { @@ -233,46 +219,25 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport + '/logout': { + id: '/logout' + path: '/logout' + fullPath: '/logout' + preLoaderRoute: typeof LogoutRouteImport parentRoute: typeof rootRouteImport } - '/api/users': { - id: '/api/users' - path: '/api/users' - fullPath: '/api/users' - preLoaderRoute: typeof ApiUsersRouteImport + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport parentRoute: typeof rootRouteImport } - '/posts/': { - id: '/posts/' + '/': { + id: '/' 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 - } - '/redirect/': { - id: '/redirect/' - path: '/redirect' - fullPath: '/redirect/' - preLoaderRoute: typeof RedirectIndexRouteImport - parentRoute: typeof rootRouteImport - } - '/redirect/throw-it': { - id: '/redirect/throw-it' - path: '/redirect/throw-it' - fullPath: '/redirect/throw-it' - preLoaderRoute: typeof RedirectThrowItRouteImport + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/users/': { @@ -282,6 +247,20 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof UsersIndexRouteImport parentRoute: typeof UsersRoute } + '/redirect/': { + id: '/redirect/' + path: '/redirect' + fullPath: '/redirect/' + preLoaderRoute: typeof RedirectIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRoute + } '/users/$userId': { id: '/users/$userId' path: '/$userId' @@ -289,12 +268,26 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof UsersUserIdRouteImport parentRoute: typeof UsersRoute } - '/api/users/$userId': { - id: '/api/users/$userId' - path: '/$userId' - fullPath: '/api/users/$userId' - preLoaderRoute: typeof ApiUsersUserIdRouteImport - parentRoute: typeof ApiUsersRoute + '/redirect/throw-it': { + id: '/redirect/throw-it' + path: '/redirect/throw-it' + fullPath: '/redirect/throw-it' + preLoaderRoute: typeof RedirectThrowItRouteImport + parentRoute: typeof rootRouteImport + } + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRoute + } + '/api/users': { + id: '/api/users' + path: '/api/users' + fullPath: '/api/users' + preLoaderRoute: typeof ApiUsersRouteImport + parentRoute: typeof rootRouteImport } '/posts_/$postId/deep': { id: '/posts_/$postId/deep' @@ -303,6 +296,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsPostIdDeepRouteImport parentRoute: typeof rootRouteImport } + '/api/users/$userId': { + id: '/api/users/$userId' + path: '/$userId' + fullPath: '/api/users/$userId' + preLoaderRoute: typeof ApiUsersUserIdRouteImport + parentRoute: typeof ApiUsersRoute + } } } diff --git a/e2e/vue-start/custom-basepath/src/routes/__root.tsx b/e2e/vue-start/custom-basepath/src/routes/__root.tsx index c6d1eb197c..8bc947b03a 100644 --- a/e2e/vue-start/custom-basepath/src/routes/__root.tsx +++ b/e2e/vue-start/custom-basepath/src/routes/__root.tsx @@ -49,11 +49,7 @@ export const Route = createRootRoute({ { rel: 'icon', href: '/favicon.ico' }, ], }), - errorComponent: (props) => ( -

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

- ), + errorComponent: (props) =>

{props.error.stack}

, 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 7e3f528d68..50b9ca995a 100644 --- a/e2e/vue-start/custom-basepath/src/routes/api/users.$userId.ts +++ b/e2e/vue-start/custom-basepath/src/routes/api/users.$userId.ts @@ -1,7 +1,11 @@ import { createFileRoute } from '@tanstack/vue-router' import type { User } from '~/utils/users' -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const Route = createFileRoute('/api/users/$userId')({ server: { diff --git a/e2e/vue-start/custom-basepath/src/routes/api/users.ts b/e2e/vue-start/custom-basepath/src/routes/api/users.ts index dfdb5cd844..97989b93ca 100644 --- a/e2e/vue-start/custom-basepath/src/routes/api/users.ts +++ b/e2e/vue-start/custom-basepath/src/routes/api/users.ts @@ -38,7 +38,11 @@ const testMiddleware = createMiddleware() return result }) -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const Route = createFileRoute('/api/users')({ server: { diff --git a/e2e/vue-start/custom-basepath/src/routes/deferred.tsx b/e2e/vue-start/custom-basepath/src/routes/deferred.tsx index 8db75401e9..7dbd50b030 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' }) - .validator((data: { name: string }) => data) + .inputValidator((data: { name: string }) => data) .handler(({ data }) => { return { name: data.name, randomNumber: Math.floor(Math.random() * 100) } }) const slowServerFn = createServerFn({ method: 'GET' }) - .validator((data: { name: string }) => data) + .inputValidator((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 599e0f046e..b4e5a8a6a2 100644 --- a/e2e/vue-start/custom-basepath/src/routes/posts.$postId.tsx +++ b/e2e/vue-start/custom-basepath/src/routes/posts.$postId.tsx @@ -1,32 +1,9 @@ -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, @@ -35,3 +12,24 @@ 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 64d4754f2f..1a9d58a31d 100644 --- a/e2e/vue-start/custom-basepath/src/routes/posts.tsx +++ b/e2e/vue-start/custom-basepath/src/routes/posts.tsx @@ -1,36 +1,7 @@ -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: [ @@ -42,3 +13,30 @@ 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 f77ae7d3ab..a52c6f32f7 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,26 +1,24 @@ -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 4effec0d5b..fb7fce5f4c 100644 --- a/e2e/vue-start/custom-basepath/src/routes/users.$userId.tsx +++ b/e2e/vue-start/custom-basepath/src/routes/users.$userId.tsx @@ -1,4 +1,3 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import axios from 'redaxios' @@ -7,18 +6,6 @@ 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 @@ -34,3 +21,14 @@ 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 fe926d0a44..1432e50451 100644 --- a/e2e/vue-start/custom-basepath/src/routes/users.tsx +++ b/e2e/vue-start/custom-basepath/src/routes/users.tsx @@ -1,40 +1,8 @@ -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 @@ -46,3 +14,33 @@ export const Route = createFileRoute('/users')({ }, component: UsersComponent, }) + +function UsersComponent() { + const users = Route.useLoaderData() + + return ( +
+
    + {[ + ...users.value, + { id: 'i-do-not-exist', name: 'Non-existent User', email: '' }, + ].map((user) => ( +
  • + +
    {user.name}
    + +
  • + ))} +
+
+ +
+ ) +} diff --git a/e2e/vue-start/custom-basepath/src/utils/posts.tsx b/e2e/vue-start/custom-basepath/src/utils/posts.tsx index 11d80d08b5..a193bbc7af 100644 --- a/e2e/vue-start/custom-basepath/src/utils/posts.tsx +++ b/e2e/vue-start/custom-basepath/src/utils/posts.tsx @@ -8,10 +8,14 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPost = createServerFn({ method: 'GET' }) - .validator((postId: string) => postId) + .inputValidator((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 7ba645b383..46be4b1580 100644 --- a/e2e/vue-start/custom-basepath/src/utils/users.tsx +++ b/e2e/vue-start/custom-basepath/src/utils/users.tsx @@ -3,3 +3,7 @@ export type User = { name: string email: string } + +const PORT = process.env.VITE_SERVER_PORT || 3000 + +export const DEPLOY_URL = `http://localhost:${PORT}` diff --git a/e2e/vue-start/custom-basepath/src/vite-env.d.ts b/e2e/vue-start/custom-basepath/src/vite-env.d.ts index d0b512cd80..0b2af560d6 100644 --- a/e2e/vue-start/custom-basepath/src/vite-env.d.ts +++ b/e2e/vue-start/custom-basepath/src/vite-env.d.ts @@ -1,5 +1,3 @@ -/// - declare module '*?url' { const url: string export default url diff --git a/e2e/vue-start/custom-basepath/tests/setup/global.setup.ts b/e2e/vue-start/custom-basepath/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-start/custom-basepath/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-start/custom-basepath/tests/setup/global.teardown.ts b/e2e/vue-start/custom-basepath/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-start/custom-basepath/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-start/custom-basepath/tsconfig.json b/e2e/vue-start/custom-basepath/tsconfig.json index 6f99c0f49a..6d933a5b2c 100644 --- a/e2e/vue-start/custom-basepath/tsconfig.json +++ b/e2e/vue-start/custom-basepath/tsconfig.json @@ -14,6 +14,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/vue-start/dev-ssr-styles/.gitignore b/e2e/vue-start/dev-ssr-styles/.gitignore deleted file mode 100644 index 950326609c..0000000000 --- a/e2e/vue-start/dev-ssr-styles/.gitignore +++ /dev/null @@ -1,7 +0,0 @@ -node_modules -dist -.routeTree.gen.ts -src/routeTree.gen.ts -test-results -playwright-report -port*.txt diff --git a/e2e/vue-start/dev-ssr-styles/package.json b/e2e/vue-start/dev-ssr-styles/package.json deleted file mode 100644 index 0033a0a5cc..0000000000 --- a/e2e/vue-start/dev-ssr-styles/package.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "name": "tanstack-vue-start-e2e-dev-ssr-styles", - "private": true, - "sideEffects": false, - "type": "module", - "scripts": { - "dev": "vite dev --port 3000", - "dev:e2e": "vite dev --port 0", - "build": "vite build && tsc --noEmit", - "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e:dev": "MODE=dev playwright test --project=chromium", - "test:e2e": "pnpm run test:e2e:dev && pnpm run test:e2e:dev:bundled-dev", - "test:e2e:dev:bundled-dev": "MODE=dev E2E_VITE_BUNDLED_DEV=true playwright test --project=chromium" - }, - "dependencies": { - "@tanstack/vue-router": "workspace:*", - "@tanstack/vue-start": "workspace:*", - "vue": "^3.5.16" - }, - "devDependencies": { - "@playwright/test": "^1.61.0", - "@tanstack/router-core": "workspace:*", - "@tanstack/router-e2e-utils": "workspace:*", - "@types/node": "^22.10.2", - "@vitejs/plugin-vue": "^6.0.5", - "@vitejs/plugin-vue-jsx": "^5.1.5", - "srvx": "^1.0.0", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", - "@typescript/native": "npm:typescript@^7.0.2" - } -} diff --git a/e2e/vue-start/dev-ssr-styles/playwright.config.ts b/e2e/vue-start/dev-ssr-styles/playwright.config.ts deleted file mode 100644 index 723cd32789..0000000000 --- a/e2e/vue-start/dev-ssr-styles/playwright.config.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' - -const PORT = Number(process.env.E2E_APP_PORT ?? 0) -const baseURL = `http://localhost:${PORT}` - -export default defineConfig({ - testDir: './tests', - workers: 1, - reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - use: { baseURL }, - webServer: { - command: 'pnpm dev:e2e', - wait: appServerReady, - reuseExistingServer: false, - stdout: 'pipe', - env: { - VITE_NODE_ENV: 'test', - }, - }, - projects: [ - { - name: 'chromium', - use: { ...devices['Desktop Chrome'] }, - }, - ], -}) diff --git a/e2e/vue-start/dev-ssr-styles/src/components/SfcStyledBox.vue b/e2e/vue-start/dev-ssr-styles/src/components/SfcStyledBox.vue deleted file mode 100644 index bd92215136..0000000000 --- a/e2e/vue-start/dev-ssr-styles/src/components/SfcStyledBox.vue +++ /dev/null @@ -1,14 +0,0 @@ - - - diff --git a/e2e/vue-start/dev-ssr-styles/src/router.tsx b/e2e/vue-start/dev-ssr-styles/src/router.tsx deleted file mode 100644 index c0d7f2b200..0000000000 --- a/e2e/vue-start/dev-ssr-styles/src/router.tsx +++ /dev/null @@ -1,10 +0,0 @@ -import { createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - scrollRestoration: true, - defaultPreload: false, - }) -} diff --git a/e2e/vue-start/dev-ssr-styles/src/routes/__root.tsx b/e2e/vue-start/dev-ssr-styles/src/routes/__root.tsx deleted file mode 100644 index 0dec479a07..0000000000 --- a/e2e/vue-start/dev-ssr-styles/src/routes/__root.tsx +++ /dev/null @@ -1,27 +0,0 @@ -import { - Body, - HeadContent, - Html, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/vue-router' -import '~/styles/app.css' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/e2e/vue-start/dev-ssr-styles/src/routes/index.tsx b/e2e/vue-start/dev-ssr-styles/src/routes/index.tsx deleted file mode 100644 index 733bc1d559..0000000000 --- a/e2e/vue-start/dev-ssr-styles/src/routes/index.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' -import SfcStyledBox from '../components/SfcStyledBox.vue' - -export const Route = createFileRoute('/')({ - component: Home, -}) - -function Home() { - return ( -
-

Vue Dev SSR Styles Test

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

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

- ) + return

{props.error.stack}

}, notFoundComponent: () => , component: RootComponent, diff --git a/e2e/vue-start/scroll-restoration/src/utils/posts.tsx b/e2e/vue-start/scroll-restoration/src/utils/posts.tsx index c4a2d0dcca..e45ef52969 100644 --- a/e2e/vue-start/scroll-restoration/src/utils/posts.tsx +++ b/e2e/vue-start/scroll-restoration/src/utils/posts.tsx @@ -10,7 +10,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export class PostNotFoundError extends Error {} diff --git a/e2e/vue-start/scroll-restoration/src/utils/users.tsx b/e2e/vue-start/scroll-restoration/src/utils/users.tsx index 7ba645b383..46be4b1580 100644 --- a/e2e/vue-start/scroll-restoration/src/utils/users.tsx +++ b/e2e/vue-start/scroll-restoration/src/utils/users.tsx @@ -3,3 +3,7 @@ export type User = { name: string email: string } + +const PORT = process.env.VITE_SERVER_PORT || 3000 + +export const DEPLOY_URL = `http://localhost:${PORT}` diff --git a/e2e/vue-start/scroll-restoration/src/vite-env.d.ts b/e2e/vue-start/scroll-restoration/src/vite-env.d.ts index d0b512cd80..0b2af560d6 100644 --- a/e2e/vue-start/scroll-restoration/src/vite-env.d.ts +++ b/e2e/vue-start/scroll-restoration/src/vite-env.d.ts @@ -1,5 +1,3 @@ -/// - 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 deleted file mode 100644 index df75cba73c..0000000000 --- a/e2e/vue-start/scroll-restoration/tests/scroll-restoration-lifecycle.spec.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { test } from '@tanstack/router-e2e-utils' -import { scrollRestorationLifecycleTests } from '../../../scroll-restoration-lifecycle' - -scrollRestorationLifecycleTests(test) diff --git a/e2e/vue-start/scroll-restoration/tests/setup/global.setup.ts b/e2e/vue-start/scroll-restoration/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-start/scroll-restoration/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-start/scroll-restoration/tests/setup/global.teardown.ts b/e2e/vue-start/scroll-restoration/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-start/scroll-restoration/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-start/scroll-restoration/tsconfig.json b/e2e/vue-start/scroll-restoration/tsconfig.json index 6f99c0f49a..6d933a5b2c 100644 --- a/e2e/vue-start/scroll-restoration/tsconfig.json +++ b/e2e/vue-start/scroll-restoration/tsconfig.json @@ -14,6 +14,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/vue-start/selective-ssr/package.json b/e2e/vue-start/selective-ssr/package.json index b555a01c26..4d51af2864 100644 --- a/e2e/vue-start/selective-ssr/package.json +++ b/e2e/vue-start/selective-ssr/package.json @@ -9,24 +9,23 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", "@tanstack/vue-start": "workspace:^", "vue": "^3.5.25", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", + "srvx": "^0.11.9", + "tailwindcss": "^4.2.2", + "typescript": "^5.7.2", + "vite": "^8.0.0", "@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" + "vue-tsc": "^3.1.8" } } diff --git a/e2e/vue-start/selective-ssr/playwright.config.ts b/e2e/vue-start/selective-ssr/playwright.config.ts index 630989e41f..badd6db0eb 100644 --- a/e2e/vue-start/selective-ssr/playwright.config.ts +++ b/e2e/vue-start/selective-ssr/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && NODE_ENV=production PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-start/selective-ssr/src/routeTree.gen.ts b/e2e/vue-start/selective-ssr/src/routeTree.gen.ts index 0d44b648ee..474705b7e7 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 IndexRouteImport } from './routes/index' import { Route as PostsRouteImport } from './routes/posts' +import { Route as IndexRouteImport } from './routes/index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const PostsRoute = PostsRouteImport.update({ id: '/posts', path: '/posts', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + 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 { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/posts': { id: '/posts' path: '/posts' @@ -74,6 +67,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } '/posts/$postId': { id: '/posts/$postId' path: '/$postId' diff --git a/e2e/vue-start/selective-ssr/src/routes/__root.tsx b/e2e/vue-start/selective-ssr/src/routes/__root.tsx index 9319a0982a..a952abd4e0 100644 --- a/e2e/vue-start/selective-ssr/src/routes/__root.tsx +++ b/e2e/vue-start/selective-ssr/src/routes/__root.tsx @@ -1,5 +1,4 @@ /// -import { defineComponent } from 'vue' import { Body, ClientOnly, @@ -15,93 +14,6 @@ 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: [ @@ -162,5 +74,84 @@ export const Route = createRootRoute({ return { root: typeof window === 'undefined' ? 'server' : 'client' } }, shellComponent: RootDocument, - component: RouteComponent, + 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} +
+
+ +
+ ) + }, }) + +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 522b5e9b8e..4e7065cc48 100644 --- a/e2e/vue-start/selective-ssr/src/routes/posts.$postId.tsx +++ b/e2e/vue-start/selective-ssr/src/routes/posts.$postId.tsx @@ -1,47 +1,7 @@ -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 }) => { @@ -86,5 +46,37 @@ export const Route = createFileRoute('/posts/$postId')({ } return { postId: typeof window === 'undefined' ? 'server' : 'client' } }, - component: RouteComponent, + 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} +
+
+ ) + }, }) diff --git a/e2e/vue-start/selective-ssr/src/routes/posts.tsx b/e2e/vue-start/selective-ssr/src/routes/posts.tsx index 514628b229..6c4e490dde 100644 --- a/e2e/vue-start/selective-ssr/src/routes/posts.tsx +++ b/e2e/vue-start/selective-ssr/src/routes/posts.tsx @@ -1,48 +1,7 @@ -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 }) => { @@ -87,5 +46,39 @@ export const Route = createFileRoute('/posts')({ } return { posts: typeof window === 'undefined' ? 'server' : 'client' } }, - component: RouteComponent, + 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} +
+
+ +
+ ) + }, }) diff --git a/e2e/vue-start/selective-ssr/tsconfig.json b/e2e/vue-start/selective-ssr/tsconfig.json index 390dad84c0..f9f5aab3da 100644 --- a/e2e/vue-start/selective-ssr/tsconfig.json +++ b/e2e/vue-start/selective-ssr/tsconfig.json @@ -14,6 +14,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/vue-start/serialization-adapters/package.json b/e2e/vue-start/serialization-adapters/package.json index a056e21da3..94e2d015f4 100644 --- a/e2e/vue-start/serialization-adapters/package.json +++ b/e2e/vue-start/serialization-adapters/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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-start": "workspace:^", "vue": "^3.5.25", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", + "srvx": "^0.11.9", + "tailwindcss": "^4.2.2", + "typescript": "^5.7.2", + "vite": "^8.0.0", "@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" + "vue-tsc": "^3.1.8" } } diff --git a/e2e/vue-start/serialization-adapters/playwright.config.ts b/e2e/vue-start/serialization-adapters/playwright.config.ts index 630989e41f..badd6db0eb 100644 --- a/e2e/vue-start/serialization-adapters/playwright.config.ts +++ b/e2e/vue-start/serialization-adapters/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && NODE_ENV=production PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-start/serialization-adapters/src/routeTree.gen.ts b/e2e/vue-start/serialization-adapters/src/routeTree.gen.ts index c684bbc82c..79b17ac82b 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 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' +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' 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 } - '/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': { - id: '/server-function/nested' - path: '/server-function/nested' - fullPath: '/server-function/nested' - preLoaderRoute: typeof ServerFunctionNestedRouteImport - parentRoute: typeof rootRouteImport - } - '/ssr/data-only': { - id: '/ssr/data-only' - path: '/ssr/data-only' - fullPath: '/ssr/data-only' - preLoaderRoute: typeof SsrDataOnlyRouteImport + '/ssr/stream': { + id: '/ssr/stream' + path: '/ssr/stream' + fullPath: '/ssr/stream' + preLoaderRoute: typeof SsrStreamRouteImport parentRoute: typeof rootRouteImport } '/ssr/nested': { @@ -146,11 +132,25 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof SsrNestedRouteImport parentRoute: typeof rootRouteImport } - '/ssr/stream': { - id: '/ssr/stream' - path: '/ssr/stream' - fullPath: '/ssr/stream' - preLoaderRoute: typeof SsrStreamRouteImport + '/ssr/data-only': { + id: '/ssr/data-only' + path: '/ssr/data-only' + fullPath: '/ssr/data-only' + preLoaderRoute: typeof SsrDataOnlyRouteImport + parentRoute: typeof rootRouteImport + } + '/server-function/nested': { + id: '/server-function/nested' + path: '/server-function/nested' + fullPath: '/server-function/nested' + 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 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 3ea36c7d46..96911d2500 100644 --- a/e2e/vue-start/serialization-adapters/src/routes/__root.tsx +++ b/e2e/vue-start/serialization-adapters/src/routes/__root.tsx @@ -1,5 +1,4 @@ /// -import { defineComponent } from 'vue' import { Body, ClientOnly, @@ -13,51 +12,6 @@ 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: [ @@ -77,3 +31,46 @@ 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 d6bacefdc0..2d90e4b073 100644 --- a/e2e/vue-start/serialization-adapters/src/routes/index.tsx +++ b/e2e/vue-start/serialization-adapters/src/routes/index.tsx @@ -2,9 +2,7 @@ import { Link, createFileRoute } from '@tanstack/vue-router' export const Route = createFileRoute('/')({ component: Home, - errorComponent: (e) => ( -
{e.error instanceof Error ? e.error.message : String(e.error)}
- ), + errorComponent: (e) =>
{e.error.message}
, }) 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 d1cbdf6353..6bca8563d3 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() - .validator(schema) + .inputValidator(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 e71906f03e..ecb35d0a55 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,47 +1,6 @@ -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: () => { @@ -50,6 +9,43 @@ export const Route = createFileRoute('/ssr/data-only')({ loader: ({ context }) => { return context }, - component: RouteComponent, + 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)} +
+
+
+
+ +
+ ) + }, 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 b4f7fd8f23..bbc240b96d 100644 --- a/e2e/vue-start/serialization-adapters/src/routes/ssr/nested.tsx +++ b/e2e/vue-start/serialization-adapters/src/routes/ssr/nested.tsx @@ -1,14 +1,6 @@ -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() } @@ -16,5 +8,8 @@ export const Route = createFileRoute('/ssr/nested')({ loader: ({ context }) => { return context }, - component: RouteComponent, + component: () => { + const loaderData = Route.useLoaderData() + return + }, }) 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 f6056699af..4fce3271f8 100644 --- a/e2e/vue-start/serialization-adapters/src/routes/ssr/stream.tsx +++ b/e2e/vue-start/serialization-adapters/src/routes/ssr/stream.tsx @@ -1,32 +1,7 @@ import { Await, createFileRoute } from '@tanstack/vue-router' -import { defineComponent, Suspense } from 'vue' +import { 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) => @@ -38,8 +13,29 @@ export const Route = createFileRoute('/ssr/stream')({ } }, - errorComponent: (e) => ( -
{e.error instanceof Error ? e.error.message : String(e.error)}
- ), + errorComponent: (e) =>
{e.error.message}
, component: RouteComponent, }) + +function RouteComponent() { + const loaderData = Route.useLoaderData() + return ( +
+

Stream

+
{loaderData.value.someString}
+ + {{ + default: () => ( + ) => ( + + )} + /> + ), + fallback: () =>
Loading...
, + }} +
+
+ ) +} diff --git a/e2e/vue-start/serialization-adapters/tsconfig.json b/e2e/vue-start/serialization-adapters/tsconfig.json index 390dad84c0..f9f5aab3da 100644 --- a/e2e/vue-start/serialization-adapters/tsconfig.json +++ b/e2e/vue-start/serialization-adapters/tsconfig.json @@ -14,6 +14,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/vue-start/server-functions/package.json b/e2e/vue-start/server-functions/package.json index dd1a7a9c6b..a021b5d447 100644 --- a/e2e/vue-start/server-functions/package.json +++ b/e2e/vue-start/server-functions/package.json @@ -9,7 +9,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-query": "^5.90.9", @@ -18,24 +18,23 @@ "@tanstack/vue-router-ssr-query": "workspace:^", "@tanstack/vue-start": "workspace:^", "js-cookie": "^3.0.5", - "redaxios": "catalog:", - "tailwind-merge": "^3.6.0", + "redaxios": "^0.5.1", + "tailwind-merge": "^2.6.0", + "vite": "^8.0.0", "vue": "^3.5.25", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@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", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "typescript": "^5.7.2", + "@vitejs/plugin-vue": "^6.0.5", + "@vitejs/plugin-vue-jsx": "^5.1.5" } } diff --git a/e2e/vue-start/server-functions/playwright.config.ts b/e2e/vue-start/server-functions/playwright.config.ts index 48e14683f4..cb1da03b94 100644 --- a/e2e/vue-start/server-functions/playwright.config.ts +++ b/e2e/vue-start/server-functions/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -export const PORT = Number(process.env.E2E_APP_PORT ?? 0) +export const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -20,8 +21,8 @@ export default defineConfig({ webServer: { command: `pnpm build && VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-start/server-functions/src/components/DefaultCatchBoundary.tsx b/e2e/vue-start/server-functions/src/components/DefaultCatchBoundary.tsx index 77c03c5afa..b1f818dd74 100644 --- a/e2e/vue-start/server-functions/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/server-functions/src/components/DefaultCatchBoundary.tsx @@ -1,61 +1,53 @@ -import { defineComponent } from 'vue' -import type { PropType } from 'vue' import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, useRouter, } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' -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 - - )} -
-
- ) - } - }, -}) +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 + + )} +
+
+ ) +} diff --git a/e2e/vue-start/server-functions/src/routeTree.gen.ts b/e2e/vue-start/server-functions/src/routeTree.gen.ts index 96e5b7ba29..43a6eb4ae6 100644 --- a/e2e/vue-start/server-functions/src/routeTree.gen.ts +++ b/e2e/vue-start/server-functions/src/routeTree.gen.ts @@ -9,89 +9,39 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/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 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 StatusRouteImport } from './routes/status' +import { Route as SerializeFormDataRouteImport } from './routes/serialize-form-data' +import { Route as ReturnNullRouteImport } from './routes/return-null' +import { Route as RawResponseRouteImport } from './routes/raw-response' +import { Route as MultipartRouteImport } from './routes/multipart' +import { Route as IsomorphicFnsRouteImport } from './routes/isomorphic-fns' +import { Route as HeadersRouteImport } from './routes/headers' +import { Route as EnvOnlyRouteImport } from './routes/env-only' +import { Route as DeadCodePreserveRouteImport } from './routes/dead-code-preserve' +import { Route as ConsistentRouteImport } from './routes/consistent' +import { Route as AbortSignalRouteImport } from './routes/abort-signal' +import { Route as IndexRouteImport } from './routes/index' import { Route as RedirectTestIndexRouteImport } from './routes/redirect-test/index' +import { Route as RedirectTestSsrIndexRouteImport } from './routes/redirect-test-ssr/index' +import { Route as PrimitivesIndexRouteImport } from './routes/primitives/index' +import { Route as MiddlewareIndexRouteImport } from './routes/middleware/index' +import { Route as FunctionMethodIndexRouteImport } from './routes/function-method/index' +import { Route as FunctionMetadataIndexRouteImport } from './routes/function-metadata/index' +import { Route as FormdataRedirectIndexRouteImport } from './routes/formdata-redirect/index' +import { Route as FactoryIndexRouteImport } from './routes/factory/index' +import { Route as 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 FormdataRedirectTargetNameRouteImport } from './routes/formdata-redirect/target.$name' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const AbortSignalRoute = AbortSignalRouteImport.update({ - id: '/abort-signal', - path: '/abort-signal', - getParentRoute: () => rootRouteImport, -} as any) -const ConsistentRoute = ConsistentRouteImport.update({ - id: '/consistent', - path: '/consistent', - getParentRoute: () => rootRouteImport, -} as any) -const DeadCodePreserveRoute = DeadCodePreserveRouteImport.update({ - id: '/dead-code-preserve', - path: '/dead-code-preserve', - getParentRoute: () => rootRouteImport, -} as any) -const EnvOnlyRoute = EnvOnlyRouteImport.update({ - id: '/env-only', - path: '/env-only', - getParentRoute: () => rootRouteImport, -} as any) -const HeadersRoute = HeadersRouteImport.update({ - id: '/headers', - path: '/headers', - getParentRoute: () => rootRouteImport, -} as any) -const IsomorphicFnsRoute = IsomorphicFnsRouteImport.update({ - id: '/isomorphic-fns', - path: '/isomorphic-fns', - getParentRoute: () => rootRouteImport, -} as any) -const MultipartRoute = MultipartRouteImport.update({ - id: '/multipart', - path: '/multipart', - getParentRoute: () => rootRouteImport, -} as any) -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', +const SubmitPostFormdataRoute = SubmitPostFormdataRouteImport.update({ + id: '/submit-post-formdata', + path: '/submit-post-formdata', getParentRoute: () => rootRouteImport, } as any) const StatusRoute = StatusRouteImport.update({ @@ -99,76 +49,59 @@ const StatusRoute = StatusRouteImport.update({ path: '/status', getParentRoute: () => rootRouteImport, } as any) -const SubmitPostFormdataRoute = SubmitPostFormdataRouteImport.update({ - id: '/submit-post-formdata', - path: '/submit-post-formdata', +const SerializeFormDataRoute = SerializeFormDataRouteImport.update({ + id: '/serialize-form-data', + path: '/serialize-form-data', getParentRoute: () => rootRouteImport, } as any) -const CookiesIndexRoute = CookiesIndexRouteImport.update({ - id: '/cookies/', - path: '/cookies/', +const ReturnNullRoute = ReturnNullRouteImport.update({ + id: '/return-null', + path: '/return-null', getParentRoute: () => rootRouteImport, } as any) -const CookiesSetRoute = CookiesSetRouteImport.update({ - id: '/cookies/set', - path: '/cookies/set', +const RawResponseRoute = RawResponseRouteImport.update({ + id: '/raw-response', + path: '/raw-response', getParentRoute: () => rootRouteImport, } as any) -const FactoryIndexRoute = FactoryIndexRouteImport.update({ - id: '/factory/', - path: '/factory/', +const MultipartRoute = MultipartRouteImport.update({ + id: '/multipart', + path: '/multipart', getParentRoute: () => rootRouteImport, } as any) -const FormdataRedirectIndexRoute = FormdataRedirectIndexRouteImport.update({ - id: '/formdata-redirect/', - path: '/formdata-redirect/', +const IsomorphicFnsRoute = IsomorphicFnsRouteImport.update({ + id: '/isomorphic-fns', + path: '/isomorphic-fns', getParentRoute: () => rootRouteImport, } as any) -const FunctionMetadataIndexRoute = FunctionMetadataIndexRouteImport.update({ - id: '/function-metadata/', - path: '/function-metadata/', +const HeadersRoute = HeadersRouteImport.update({ + id: '/headers', + path: '/headers', getParentRoute: () => rootRouteImport, } as any) -const FunctionMethodIndexRoute = FunctionMethodIndexRouteImport.update({ - id: '/function-method/', - path: '/function-method/', +const EnvOnlyRoute = EnvOnlyRouteImport.update({ + id: '/env-only', + path: '/env-only', getParentRoute: () => rootRouteImport, } as any) -const MiddlewareIndexRoute = MiddlewareIndexRouteImport.update({ - id: '/middleware/', - path: '/middleware/', +const DeadCodePreserveRoute = DeadCodePreserveRouteImport.update({ + id: '/dead-code-preserve', + path: '/dead-code-preserve', 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', +const ConsistentRoute = ConsistentRouteImport.update({ + id: '/consistent', + path: '/consistent', getParentRoute: () => rootRouteImport, } as any) -const PrimitivesIndexRoute = PrimitivesIndexRouteImport.update({ - id: '/primitives/', - path: '/primitives/', +const AbortSignalRoute = AbortSignalRouteImport.update({ + id: '/abort-signal', + path: '/abort-signal', getParentRoute: () => rootRouteImport, } as any) -const RedirectTestSsrIndexRoute = RedirectTestSsrIndexRouteImport.update({ - id: '/redirect-test-ssr/', - path: '/redirect-test-ssr/', - getParentRoute: () => rootRouteImport, -} as any) -const RedirectTestSsrTargetRoute = RedirectTestSsrTargetRouteImport.update({ - id: '/redirect-test-ssr/target', - path: '/redirect-test-ssr/target', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const RedirectTestIndexRoute = RedirectTestIndexRouteImport.update({ @@ -176,11 +109,78 @@ const RedirectTestIndexRoute = RedirectTestIndexRouteImport.update({ path: '/redirect-test/', getParentRoute: () => rootRouteImport, } as any) +const RedirectTestSsrIndexRoute = RedirectTestSsrIndexRouteImport.update({ + id: '/redirect-test-ssr/', + path: '/redirect-test-ssr/', + getParentRoute: () => rootRouteImport, +} as any) +const PrimitivesIndexRoute = PrimitivesIndexRouteImport.update({ + id: '/primitives/', + path: '/primitives/', + getParentRoute: () => rootRouteImport, +} as any) +const MiddlewareIndexRoute = MiddlewareIndexRouteImport.update({ + id: '/middleware/', + path: '/middleware/', + getParentRoute: () => rootRouteImport, +} as any) +const FunctionMethodIndexRoute = FunctionMethodIndexRouteImport.update({ + id: '/function-method/', + path: '/function-method/', + getParentRoute: () => rootRouteImport, +} as any) +const FunctionMetadataIndexRoute = FunctionMetadataIndexRouteImport.update({ + id: '/function-metadata/', + path: '/function-metadata/', + getParentRoute: () => rootRouteImport, +} as any) +const FormdataRedirectIndexRoute = FormdataRedirectIndexRouteImport.update({ + id: '/formdata-redirect/', + path: '/formdata-redirect/', + getParentRoute: () => rootRouteImport, +} as any) +const FactoryIndexRoute = FactoryIndexRouteImport.update({ + id: '/factory/', + path: '/factory/', + getParentRoute: () => rootRouteImport, +} as any) +const CookiesIndexRoute = CookiesIndexRouteImport.update({ + id: '/cookies/', + path: '/cookies/', + getParentRoute: () => rootRouteImport, +} as any) const RedirectTestTargetRoute = RedirectTestTargetRouteImport.update({ id: '/redirect-test/target', path: '/redirect-test/target', getParentRoute: () => rootRouteImport, } as any) +const RedirectTestSsrTargetRoute = RedirectTestSsrTargetRouteImport.update({ + id: '/redirect-test-ssr/target', + path: '/redirect-test-ssr/target', + getParentRoute: () => rootRouteImport, +} as any) +const MiddlewareSendServerFnRoute = MiddlewareSendServerFnRouteImport.update({ + id: '/middleware/send-serverFn', + path: '/middleware/send-serverFn', + 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', + getParentRoute: () => rootRouteImport, +} as any) const FormdataRedirectTargetNameRoute = FormdataRedirectTargetNameRouteImport.update({ id: '/formdata-redirect/target/$name', @@ -412,81 +412,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/abort-signal': { - id: '/abort-signal' - path: '/abort-signal' - fullPath: '/abort-signal' - preLoaderRoute: typeof AbortSignalRouteImport - parentRoute: typeof rootRouteImport - } - '/consistent': { - id: '/consistent' - path: '/consistent' - fullPath: '/consistent' - preLoaderRoute: typeof ConsistentRouteImport - parentRoute: typeof rootRouteImport - } - '/dead-code-preserve': { - id: '/dead-code-preserve' - path: '/dead-code-preserve' - fullPath: '/dead-code-preserve' - preLoaderRoute: typeof DeadCodePreserveRouteImport - parentRoute: typeof rootRouteImport - } - '/env-only': { - id: '/env-only' - path: '/env-only' - fullPath: '/env-only' - preLoaderRoute: typeof EnvOnlyRouteImport - parentRoute: typeof rootRouteImport - } - '/headers': { - id: '/headers' - path: '/headers' - fullPath: '/headers' - preLoaderRoute: typeof HeadersRouteImport - parentRoute: typeof rootRouteImport - } - '/isomorphic-fns': { - id: '/isomorphic-fns' - path: '/isomorphic-fns' - fullPath: '/isomorphic-fns' - preLoaderRoute: typeof IsomorphicFnsRouteImport - parentRoute: typeof rootRouteImport - } - '/multipart': { - id: '/multipart' - path: '/multipart' - fullPath: '/multipart' - preLoaderRoute: typeof MultipartRouteImport - parentRoute: typeof rootRouteImport - } - '/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 + '/submit-post-formdata': { + id: '/submit-post-formdata' + path: '/submit-post-formdata' + fullPath: '/submit-post-formdata' + preLoaderRoute: typeof SubmitPostFormdataRouteImport parentRoute: typeof rootRouteImport } '/status': { @@ -496,102 +426,81 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof StatusRouteImport parentRoute: typeof rootRouteImport } - '/submit-post-formdata': { - id: '/submit-post-formdata' - path: '/submit-post-formdata' - fullPath: '/submit-post-formdata' - preLoaderRoute: typeof SubmitPostFormdataRouteImport + '/serialize-form-data': { + id: '/serialize-form-data' + path: '/serialize-form-data' + fullPath: '/serialize-form-data' + preLoaderRoute: typeof SerializeFormDataRouteImport parentRoute: typeof rootRouteImport } - '/cookies/': { - id: '/cookies/' - path: '/cookies' - fullPath: '/cookies/' - preLoaderRoute: typeof CookiesIndexRouteImport + '/return-null': { + id: '/return-null' + path: '/return-null' + fullPath: '/return-null' + preLoaderRoute: typeof ReturnNullRouteImport parentRoute: typeof rootRouteImport } - '/cookies/set': { - id: '/cookies/set' - path: '/cookies/set' - fullPath: '/cookies/set' - preLoaderRoute: typeof CookiesSetRouteImport + '/raw-response': { + id: '/raw-response' + path: '/raw-response' + fullPath: '/raw-response' + preLoaderRoute: typeof RawResponseRouteImport parentRoute: typeof rootRouteImport } - '/factory/': { - id: '/factory/' - path: '/factory' - fullPath: '/factory/' - preLoaderRoute: typeof FactoryIndexRouteImport + '/multipart': { + id: '/multipart' + path: '/multipart' + fullPath: '/multipart' + preLoaderRoute: typeof MultipartRouteImport parentRoute: typeof rootRouteImport } - '/formdata-redirect/': { - id: '/formdata-redirect/' - path: '/formdata-redirect' - fullPath: '/formdata-redirect/' - preLoaderRoute: typeof FormdataRedirectIndexRouteImport + '/isomorphic-fns': { + id: '/isomorphic-fns' + path: '/isomorphic-fns' + fullPath: '/isomorphic-fns' + preLoaderRoute: typeof IsomorphicFnsRouteImport parentRoute: typeof rootRouteImport } - '/function-metadata/': { - id: '/function-metadata/' - path: '/function-metadata' - fullPath: '/function-metadata/' - preLoaderRoute: typeof FunctionMetadataIndexRouteImport + '/headers': { + id: '/headers' + path: '/headers' + fullPath: '/headers' + preLoaderRoute: typeof HeadersRouteImport parentRoute: typeof rootRouteImport } - '/function-method/': { - id: '/function-method/' - path: '/function-method' - fullPath: '/function-method/' - preLoaderRoute: typeof FunctionMethodIndexRouteImport + '/env-only': { + id: '/env-only' + path: '/env-only' + fullPath: '/env-only' + preLoaderRoute: typeof EnvOnlyRouteImport parentRoute: typeof rootRouteImport } - '/middleware/': { - id: '/middleware/' - path: '/middleware' - fullPath: '/middleware/' - preLoaderRoute: typeof MiddlewareIndexRouteImport + '/dead-code-preserve': { + id: '/dead-code-preserve' + path: '/dead-code-preserve' + fullPath: '/dead-code-preserve' + preLoaderRoute: typeof DeadCodePreserveRouteImport parentRoute: typeof rootRouteImport } - '/middleware/client-middleware-router': { - id: '/middleware/client-middleware-router' - path: '/middleware/client-middleware-router' - fullPath: '/middleware/client-middleware-router' - preLoaderRoute: typeof MiddlewareClientMiddlewareRouterRouteImport + '/consistent': { + id: '/consistent' + path: '/consistent' + fullPath: '/consistent' + preLoaderRoute: typeof ConsistentRouteImport parentRoute: typeof rootRouteImport } - '/middleware/request-middleware': { - id: '/middleware/request-middleware' - path: '/middleware/request-middleware' - fullPath: '/middleware/request-middleware' - preLoaderRoute: typeof MiddlewareRequestMiddlewareRouteImport + '/abort-signal': { + id: '/abort-signal' + path: '/abort-signal' + fullPath: '/abort-signal' + preLoaderRoute: typeof AbortSignalRouteImport 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 + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/redirect-test/': { @@ -601,6 +510,62 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof RedirectTestIndexRouteImport parentRoute: typeof rootRouteImport } + '/redirect-test-ssr/': { + id: '/redirect-test-ssr/' + path: '/redirect-test-ssr' + fullPath: '/redirect-test-ssr/' + preLoaderRoute: typeof RedirectTestSsrIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/primitives/': { + id: '/primitives/' + path: '/primitives' + fullPath: '/primitives/' + preLoaderRoute: typeof PrimitivesIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/middleware/': { + id: '/middleware/' + path: '/middleware' + fullPath: '/middleware/' + preLoaderRoute: typeof MiddlewareIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/function-method/': { + id: '/function-method/' + path: '/function-method' + fullPath: '/function-method/' + preLoaderRoute: typeof FunctionMethodIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/function-metadata/': { + id: '/function-metadata/' + path: '/function-metadata' + fullPath: '/function-metadata/' + preLoaderRoute: typeof FunctionMetadataIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/formdata-redirect/': { + id: '/formdata-redirect/' + path: '/formdata-redirect' + fullPath: '/formdata-redirect/' + preLoaderRoute: typeof FormdataRedirectIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/factory/': { + id: '/factory/' + path: '/factory' + fullPath: '/factory/' + preLoaderRoute: typeof FactoryIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/cookies/': { + id: '/cookies/' + path: '/cookies' + fullPath: '/cookies/' + preLoaderRoute: typeof CookiesIndexRouteImport + parentRoute: typeof rootRouteImport + } '/redirect-test/target': { id: '/redirect-test/target' path: '/redirect-test/target' @@ -608,6 +573,41 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof RedirectTestTargetRouteImport 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 + } + '/middleware/send-serverFn': { + id: '/middleware/send-serverFn' + path: '/middleware/send-serverFn' + fullPath: '/middleware/send-serverFn' + preLoaderRoute: typeof MiddlewareSendServerFnRouteImport + parentRoute: typeof rootRouteImport + } + '/middleware/request-middleware': { + id: '/middleware/request-middleware' + path: '/middleware/request-middleware' + fullPath: '/middleware/request-middleware' + preLoaderRoute: typeof MiddlewareRequestMiddlewareRouteImport + parentRoute: typeof rootRouteImport + } + '/middleware/client-middleware-router': { + id: '/middleware/client-middleware-router' + path: '/middleware/client-middleware-router' + fullPath: '/middleware/client-middleware-router' + preLoaderRoute: typeof MiddlewareClientMiddlewareRouterRouteImport + parentRoute: typeof rootRouteImport + } + '/cookies/set': { + id: '/cookies/set' + path: '/cookies/set' + fullPath: '/cookies/set' + preLoaderRoute: typeof CookiesSetRouteImport + parentRoute: typeof rootRouteImport + } '/formdata-redirect/target/$name': { id: '/formdata-redirect/target/$name' path: '/formdata-redirect/target/$name' diff --git a/e2e/vue-start/server-functions/src/routes/__root.tsx b/e2e/vue-start/server-functions/src/routes/__root.tsx index a52b12deae..342f7a79b3 100644 --- a/e2e/vue-start/server-functions/src/routes/__root.tsx +++ b/e2e/vue-start/server-functions/src/routes/__root.tsx @@ -25,11 +25,7 @@ export const Route = createRootRoute({ links: [{ rel: 'stylesheet', href: appCss }], }), errorComponent: (props) => { - return ( -

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

- ) + return

{props.error.stack}

}, notFoundComponent: () => , component: RootComponent, diff --git a/e2e/vue-start/server-functions/src/routes/consistent.tsx b/e2e/vue-start/server-functions/src/routes/consistent.tsx index 046f15f339..5e6b0a7e08 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() - .validator((d: { username: string }) => d) + .inputValidator((d: { username: string }) => d) .handler(({ data }) => { return { payload: data } }) const cons_serverGetFn1 = createServerFn() - .validator((d: { username: string }) => d) + .inputValidator((d: { username: string }) => d) .handler(async ({ data }) => { return cons_getFn1({ data }) }) const cons_postFn1 = createServerFn({ method: 'POST' }) - .validator((d: { username: string }) => d) + .inputValidator((d: { username: string }) => d) .handler(({ data }) => { return { payload: data } }) const cons_serverPostFn1 = createServerFn({ method: 'POST' }) - .validator((d: { username: string }) => d) + .inputValidator((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 90dddad0af..5da8860ac6 100644 --- a/e2e/vue-start/server-functions/src/routes/cookies/index.tsx +++ b/e2e/vue-start/server-functions/src/routes/cookies/index.tsx @@ -1,28 +1,24 @@ -import { defineComponent } from 'vue' import { Link, createFileRoute } from '@tanstack/vue-router' import { z } from 'zod' const cookieSchema = z - .object({ value: z.string().default(() => `CLIENT-${Date.now()}`) }) - .prefault({}) + .object({ value: z.string() }) .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 bcdad36ab9..39fd00b74e 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() - .validator(cookieSchema) + .inputValidator(cookieSchema) .handler(({ data }) => { setCookie(`cookie-1-${data.value}`, data.value) setCookie(`cookie-2-${data.value}`, data.value) }) export const setCookieServerFn2 = createServerFn() - .validator(cookieSchema) + .inputValidator(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/formdata-redirect/index.tsx b/e2e/vue-start/server-functions/src/routes/formdata-redirect/index.tsx index 8bfcc55ca3..d23eb342b3 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,51 +1,7 @@ -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({ @@ -58,7 +14,7 @@ const testValues = { } export const greetUser = createServerFn({ method: 'POST' }) - .validator((data: FormData) => { + .inputValidator((data: FormData) => { if (!(data instanceof FormData)) { throw new Error('Invalid! FormData is required') } @@ -75,3 +31,44 @@ 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 099a8665bf..958aeaf617 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,21 +1,18 @@ -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/isomorphic-fns.tsx b/e2e/vue-start/server-functions/src/routes/isomorphic-fns.tsx index 8764b558a2..6d0679e34d 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() - .validator((input: string) => input) + .inputValidator((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 2157ed3922..c41fd8e4e5 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' }) - .validator((x: unknown) => { + .inputValidator((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 2f856bb7f3..561f7646eb 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' }) - .validator(z.string()) + .inputValidator(z.string()) .handler((ctx) => ctx.data) const $stringGet = createServerFn({ method: 'GET' }) - .validator(z.string()) + .inputValidator(z.string()) .handler((ctx) => ctx.data) const $undefinedPost = createServerFn({ method: 'POST' }) - .validator(z.undefined()) + .inputValidator(z.undefined()) .handler((ctx) => ctx.data) const $undefinedGet = createServerFn({ method: 'GET' }) - .validator(z.undefined()) + .inputValidator(z.undefined()) .handler((ctx) => ctx.data) const $nullPost = createServerFn({ method: 'POST' }) - .validator(z.null()) + .inputValidator(z.null()) .handler((ctx) => ctx.data) const $nullGet = createServerFn({ method: 'GET' }) - .validator(z.null()) + .inputValidator(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 4aaf8eec60..e2b117a9ad 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' }) - .validator((data: FormData) => { + .inputValidator((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 3bbc85a163..35e083326d 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' }) - .validator((data: FormData) => { + .inputValidator((data: FormData) => { if (!(data instanceof FormData)) { throw new Error('Invalid! FormData is required') } 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 d0b512cd80..0b2af560d6 100644 --- a/e2e/vue-start/server-functions/src/vite-env.d.ts +++ b/e2e/vue-start/server-functions/src/vite-env.d.ts @@ -1,5 +1,3 @@ -/// - declare module '*?url' { const url: string export default url diff --git a/e2e/vue-start/server-functions/tsconfig.json b/e2e/vue-start/server-functions/tsconfig.json index d5b41741d2..a5ae5ae7e4 100644 --- a/e2e/vue-start/server-functions/tsconfig.json +++ b/e2e/vue-start/server-functions/tsconfig.json @@ -14,6 +14,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/vue-start/server-routes/package.json b/e2e/vue-start/server-routes/package.json index 6a8e1babed..b611852c71 100644 --- a/e2e/vue-start/server-routes/package.json +++ b/e2e/vue-start/server-routes/package.json @@ -18,24 +18,23 @@ "@tanstack/vue-router-ssr-query": "workspace:^", "@tanstack/vue-start": "workspace:^", "js-cookie": "^3.0.5", - "redaxios": "catalog:", - "tailwind-merge": "^3.6.0", + "redaxios": "^0.5.1", + "tailwind-merge": "^2.6.0", + "vite": "^8.0.0", "vue": "^3.5.25", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@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", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "typescript": "^5.7.2", + "@vitejs/plugin-vue": "^6.0.5", + "@vitejs/plugin-vue-jsx": "^5.1.5" } } diff --git a/e2e/vue-start/server-routes/playwright.config.ts b/e2e/vue-start/server-routes/playwright.config.ts index 48e14683f4..cb1da03b94 100644 --- a/e2e/vue-start/server-routes/playwright.config.ts +++ b/e2e/vue-start/server-routes/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -export const PORT = Number(process.env.E2E_APP_PORT ?? 0) +export const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -20,8 +21,8 @@ export default defineConfig({ webServer: { command: `pnpm build && VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-start/server-routes/src/components/DefaultCatchBoundary.tsx b/e2e/vue-start/server-routes/src/components/DefaultCatchBoundary.tsx index 77c03c5afa..b1f818dd74 100644 --- a/e2e/vue-start/server-routes/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/server-routes/src/components/DefaultCatchBoundary.tsx @@ -1,61 +1,53 @@ -import { defineComponent } from 'vue' -import type { PropType } from 'vue' import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, useRouter, } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' -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 - - )} -
-
- ) - } - }, -}) +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 + + )} +
+
+ ) +} diff --git a/e2e/vue-start/server-routes/src/routeTree.gen.ts b/e2e/vue-start/server-routes/src/routeTree.gen.ts index 603560da2a..7d9d463772 100644 --- a/e2e/vue-start/server-routes/src/routeTree.gen.ts +++ b/e2e/vue-start/server-routes/src/routeTree.gen.ts @@ -9,21 +9,16 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' import { Route as MergeMiddlewareContextRouteImport } from './routes/merge-middleware-context' import { Route as MethodsRouteRouteImport } from './routes/methods/route' -import { Route as ApiMiddlewareContextRouteImport } from './routes/api/middleware-context' -import { Route as ApiOnlyAnyRouteImport } from './routes/api/only-any' +import { Route as IndexRouteImport } from './routes/index' 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', @@ -34,14 +29,9 @@ const MethodsRouteRoute = MethodsRouteRouteImport.update({ path: '/methods', getParentRoute: () => rootRouteImport, } as any) -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', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const MethodsIndexRoute = MethodsIndexRouteImport.update({ @@ -54,6 +44,16 @@ 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,13 +144,6 @@ 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' @@ -165,18 +158,11 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof MethodsRouteRouteImport 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/only-any': { - id: '/api/only-any' - path: '/api/only-any' - fullPath: '/api/only-any' - preLoaderRoute: typeof ApiOnlyAnyRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/methods/': { @@ -193,6 +179,20 @@ 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 aa4b1f31fa..999d80fff1 100644 --- a/e2e/vue-start/server-routes/src/routes/__root.tsx +++ b/e2e/vue-start/server-routes/src/routes/__root.tsx @@ -25,11 +25,7 @@ export const Route = createRootRoute({ links: [{ rel: 'stylesheet', href: appCss }], }), errorComponent: (props) => { - return ( -

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

- ) + return

{props.error.stack}

}, notFoundComponent: () => , component: RootComponent, 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 d0b512cd80..0b2af560d6 100644 --- a/e2e/vue-start/server-routes/src/vite-env.d.ts +++ b/e2e/vue-start/server-routes/src/vite-env.d.ts @@ -1,5 +1,3 @@ -/// - 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 d5b41741d2..a5ae5ae7e4 100644 --- a/e2e/vue-start/server-routes/tsconfig.json +++ b/e2e/vue-start/server-routes/tsconfig.json @@ -14,6 +14,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/vue-start/spa-mode/package.json b/e2e/vue-start/spa-mode/package.json index c4270cfccd..3c2d215ec9 100644 --- a/e2e/vue-start/spa-mode/package.json +++ b/e2e/vue-start/spa-mode/package.json @@ -9,23 +9,22 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "npx serve dist/client", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-start": "workspace:^", "vue": "^3.5.25", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", - "@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" + "typescript": "^5.7.2", + "vite": "^8.0.0", + "@vitejs/plugin-vue": "^6.0.5", + "@vitejs/plugin-vue-jsx": "^5.1.5" } } diff --git a/e2e/vue-start/spa-mode/playwright.config.ts b/e2e/vue-start/spa-mode/playwright.config.ts index 630989e41f..badd6db0eb 100644 --- a/e2e/vue-start/spa-mode/playwright.config.ts +++ b/e2e/vue-start/spa-mode/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && NODE_ENV=production PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-start/spa-mode/src/routeTree.gen.ts b/e2e/vue-start/spa-mode/src/routeTree.gen.ts index 0d44b648ee..474705b7e7 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 IndexRouteImport } from './routes/index' import { Route as PostsRouteImport } from './routes/posts' +import { Route as IndexRouteImport } from './routes/index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const PostsRoute = PostsRouteImport.update({ id: '/posts', path: '/posts', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + 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 { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/posts': { id: '/posts' path: '/posts' @@ -74,6 +67,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } '/posts/$postId': { id: '/posts/$postId' path: '/$postId' diff --git a/e2e/vue-start/spa-mode/src/routes/__root.tsx b/e2e/vue-start/spa-mode/src/routes/__root.tsx index 45aee73c06..1e38664739 100644 --- a/e2e/vue-start/spa-mode/src/routes/__root.tsx +++ b/e2e/vue-start/spa-mode/src/routes/__root.tsx @@ -1,5 +1,4 @@ /// -import { defineComponent } from 'vue' import { Body, ClientOnly, @@ -14,71 +13,6 @@ 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: [ @@ -110,6 +44,65 @@ export const Route = createRootRoute({ return { root: typeof window === 'undefined' ? 'server' : 'client' } }, shellComponent: RootDocument, - component: RouteComponent, + component: () => { + const loaderData = Route.useLoaderData() + const context = Route.useRouteContext() + return ( +
+

root

+
+ loader: {loaderData.value.root} +
+
+ context: {context.value.root} +
+
+ +
+ ) + }, 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 9c25cbad25..6733ef7436 100644 --- a/e2e/vue-start/spa-mode/src/routes/posts.$postId.tsx +++ b/e2e/vue-start/spa-mode/src/routes/posts.$postId.tsx @@ -1,24 +1,5 @@ -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( @@ -34,6 +15,20 @@ export const Route = createFileRoute('/posts/$postId')({ ) return { postId: typeof window === 'undefined' ? 'server' : 'client' } }, - component: RouteComponent, + component: () => { + const loaderData = Route.useLoaderData() + const context = Route.useRouteContext() + return ( +
+

postId

+
+ loader: {loaderData.value.postId} +
+
+ context: {context.value.postId} +
+
+ ) + }, 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 44c536adc4..e69ae1ea86 100644 --- a/e2e/vue-start/spa-mode/src/routes/posts.tsx +++ b/e2e/vue-start/spa-mode/src/routes/posts.tsx @@ -1,26 +1,5 @@ -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( @@ -37,6 +16,22 @@ export const Route = createFileRoute('/posts')({ return { posts: typeof window === 'undefined' ? 'server' : 'client' } }, - component: RouteComponent, + component: () => { + const loaderData = Route.useLoaderData() + const context = Route.useRouteContext() + return ( +
+

posts

+
+ loader: {loaderData.value.posts} +
+
+ context: {context.value.posts} +
+
+ +
+ ) + }, pendingComponent: () =>
posts Loading...
, }) diff --git a/e2e/vue-start/spa-mode/tsconfig.json b/e2e/vue-start/spa-mode/tsconfig.json index 390dad84c0..f9f5aab3da 100644 --- a/e2e/vue-start/spa-mode/tsconfig.json +++ b/e2e/vue-start/spa-mode/tsconfig.json @@ -14,6 +14,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/vue-start/start-manifest/package.json b/e2e/vue-start/start-manifest/package.json deleted file mode 100644 index ae682f7a9d..0000000000 --- a/e2e/vue-start/start-manifest/package.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "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 deleted file mode 100644 index 653e08253f..0000000000 --- a/e2e/vue-start/start-manifest/playwright.config.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' - -const PORT = Number(process.env.E2E_APP_PORT ?? 0) -const baseURL = `http://localhost:${PORT}` - -export default defineConfig({ - testDir: './tests', - workers: 1, - reporter: [['line']], - - 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 deleted file mode 100644 index 0d57b2d0e3..0000000000 --- a/e2e/vue-start/start-manifest/src/components/AppShell.tsx +++ /dev/null @@ -1,38 +0,0 @@ -/// -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 deleted file mode 100644 index c82b2b0ea5..0000000000 --- a/e2e/vue-start/start-manifest/src/components/SharedCard.tsx +++ /dev/null @@ -1,10 +0,0 @@ -/// -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 deleted file mode 100644 index 9c1f63f2f9..0000000000 --- a/e2e/vue-start/start-manifest/src/components/SharedNestedLayout.tsx +++ /dev/null @@ -1,34 +0,0 @@ -/// -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 deleted file mode 100644 index 9074d5b2b0..0000000000 --- a/e2e/vue-start/start-manifest/src/components/SharedWidget.tsx +++ /dev/null @@ -1,15 +0,0 @@ -/// -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 deleted file mode 100644 index 5f1f6410a5..0000000000 --- a/e2e/vue-start/start-manifest/src/components/SharedWidgetLazy.tsx +++ /dev/null @@ -1,5 +0,0 @@ -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 deleted file mode 100644 index fc42a1e404..0000000000 --- a/e2e/vue-start/start-manifest/src/routeTree.gen.ts +++ /dev/null @@ -1,345 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index d7cd8e8284..0000000000 --- a/e2e/vue-start/start-manifest/src/router.tsx +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index b62d37c0f0..0000000000 --- a/e2e/vue-start/start-manifest/src/routes/__root.tsx +++ /dev/null @@ -1,35 +0,0 @@ -/// -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 deleted file mode 100644 index e53399273d..0000000000 --- a/e2e/vue-start/start-manifest/src/routes/a.tsx +++ /dev/null @@ -1,18 +0,0 @@ -/// -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 deleted file mode 100644 index cb989a257f..0000000000 --- a/e2e/vue-start/start-manifest/src/routes/b.tsx +++ /dev/null @@ -1,18 +0,0 @@ -/// -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 deleted file mode 100644 index 728cc55e88..0000000000 --- a/e2e/vue-start/start-manifest/src/routes/index.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 0db0845425..0000000000 --- a/e2e/vue-start/start-manifest/src/routes/lazy-css-lazy.tsx +++ /dev/null @@ -1,31 +0,0 @@ -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 deleted file mode 100644 index 2a8352e67e..0000000000 --- a/e2e/vue-start/start-manifest/src/routes/lazy-css-static.tsx +++ /dev/null @@ -1,24 +0,0 @@ -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 deleted file mode 100644 index b35bec54e3..0000000000 --- a/e2e/vue-start/start-manifest/src/routes/r1.tsx +++ /dev/null @@ -1,18 +0,0 @@ -/// -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 deleted file mode 100644 index eadd952f98..0000000000 --- a/e2e/vue-start/start-manifest/src/routes/r2.tsx +++ /dev/null @@ -1,18 +0,0 @@ -/// -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 deleted file mode 100644 index a5a486cfaa..0000000000 --- a/e2e/vue-start/start-manifest/src/routes/r3.tsx +++ /dev/null @@ -1,5 +0,0 @@ -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 deleted file mode 100644 index 9739966d02..0000000000 --- a/e2e/vue-start/start-manifest/src/routes/r4.tsx +++ /dev/null @@ -1,5 +0,0 @@ -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 deleted file mode 100644 index 7c081e29a6..0000000000 --- a/e2e/vue-start/start-manifest/src/routes/r5.tsx +++ /dev/null @@ -1,5 +0,0 @@ -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 deleted file mode 100644 index c56c2afda3..0000000000 --- a/e2e/vue-start/start-manifest/src/routes/r6.tsx +++ /dev/null @@ -1,5 +0,0 @@ -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 deleted file mode 100644 index e7253a94ac..0000000000 --- a/e2e/vue-start/start-manifest/src/routes/shared-a.tsx +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index ed02b3429b..0000000000 --- a/e2e/vue-start/start-manifest/src/routes/shared-b.tsx +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index e395b33ed5..0000000000 --- a/e2e/vue-start/start-manifest/src/routes/shared-c.tsx +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 7ed4301097..0000000000 --- a/e2e/vue-start/start-manifest/src/styles/page-a.module.css +++ /dev/null @@ -1,10 +0,0 @@ -.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 deleted file mode 100644 index 93d1d39a01..0000000000 --- a/e2e/vue-start/start-manifest/src/styles/page-b.module.css +++ /dev/null @@ -1,10 +0,0 @@ -.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 deleted file mode 100644 index e7bece8664..0000000000 --- a/e2e/vue-start/start-manifest/src/styles/root-shell.module.css +++ /dev/null @@ -1,37 +0,0 @@ -.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 deleted file mode 100644 index 623d03e6a3..0000000000 --- a/e2e/vue-start/start-manifest/src/styles/route-one.module.css +++ /dev/null @@ -1,7 +0,0 @@ -.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 deleted file mode 100644 index 66ed355711..0000000000 --- a/e2e/vue-start/start-manifest/src/styles/route-two.module.css +++ /dev/null @@ -1,7 +0,0 @@ -.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 deleted file mode 100644 index 2aa5a6ac17..0000000000 --- a/e2e/vue-start/start-manifest/src/styles/shared-card.module.css +++ /dev/null @@ -1,8 +0,0 @@ -.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 deleted file mode 100644 index 6025a1da06..0000000000 --- a/e2e/vue-start/start-manifest/src/styles/shared-layout.module.css +++ /dev/null @@ -1,16 +0,0 @@ -.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 deleted file mode 100644 index ed197cddb0..0000000000 --- a/e2e/vue-start/start-manifest/src/styles/shared-widget.module.css +++ /dev/null @@ -1,17 +0,0 @@ -.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 deleted file mode 100644 index 4d5bea0a33..0000000000 --- a/e2e/vue-start/start-manifest/tests/start-manifest.spec.ts +++ /dev/null @@ -1,449 +0,0 @@ -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 deleted file mode 100644 index 44a68ebf56..0000000000 --- a/e2e/vue-start/start-manifest/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "include": ["**/*.ts", "**/*.tsx"], - "compilerOptions": { - "strict": true, - "esModuleInterop": true, - "jsx": "preserve", - "jsxImportSource": "vue", - "module": "ESNext", - "moduleResolution": "Bundler", - "lib": ["DOM", "DOM.Iterable", "ES2022"], - "isolatedModules": true, - "resolveJsonModule": true, - "skipLibCheck": true, - "target": "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 deleted file mode 100644 index f1102cffab..0000000000 --- a/e2e/vue-start/start-manifest/vite.config.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { defineConfig } from 'vite' -import { tanstackStart } from '@tanstack/vue-start/plugin/vite' -import vueJsx from '@vitejs/plugin-vue-jsx' - -export default defineConfig({ - server: { - port: 3000, - }, - 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 deleted file mode 100644 index 382120860a..0000000000 --- a/e2e/vue-start/streaming-ssr/package.json +++ /dev/null @@ -1,59 +0,0 @@ -{ - "name": "tanstack-vue-start-e2e-streaming-ssr", - "private": true, - "sideEffects": false, - "type": "module", - "scripts": { - "dev": "vite dev --port 3000", - "dev:e2e": "vite dev", - "build": "vite build && tsc --noEmit", - "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "preview": "vite preview", - "test:e2e": "playwright test --project=chromium", - "test:e2e:preview": "MODE=preview playwright test preview-streaming.spec.ts --project=chromium" - }, - "dependencies": { - "@tanstack/vue-query": "^5.90.0", - "@tanstack/vue-router": "workspace:^", - "@tanstack/vue-router-ssr-query": "workspace:^", - "@tanstack/vue-start": "workspace:^", - "vue": "^3.5.16" - }, - "devDependencies": { - "@playwright/test": "^1.61.0", - "@tanstack/router-e2e-utils": "workspace:^", - "@types/node": "^22.10.2", - "@vitejs/plugin-vue-jsx": "^5.1.5", - "srvx": "^1.0.0", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" - }, - "nx": { - "targets": { - "build": { - "inputs": [ - "buildProduction", - "^buildProduction", - "dependentTaskOutputs", - "streamingSsrTests" - ] - }, - "test:e2e": { - "inputs": [ - "default", - "^production", - "dependentTaskOutputs", - "streamingSsrTests" - ] - }, - "test:e2e:preview": { - "inputs": [ - "default", - "^production", - "streamingSsrTests" - ] - } - } - } -} diff --git a/e2e/vue-start/streaming-ssr/playwright.config.ts b/e2e/vue-start/streaming-ssr/playwright.config.ts deleted file mode 100644 index c2f3b67a0c..0000000000 --- a/e2e/vue-start/streaming-ssr/playwright.config.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' - -const isPreview = process.env.MODE === 'preview' - -const PORT = Number(process.env.E2E_APP_PORT ?? 0) -const baseURL = `http://localhost:${PORT}` - -const ssrCommand = `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start` -const previewCommand = `VITE_SERVER_PORT=${PORT} pnpm build && pnpm preview --port ${PORT}` - -/** - * See https://playwright.dev/docs/test-configuration. - */ -export default defineConfig({ - testDir: './tests', - workers: 1, - - reporter: [['line']], - - use: { - /* Base URL to use in actions like `await page.goto('/')`. */ - baseURL, - }, - - webServer: { - command: isPreview ? previewCommand : ssrCommand, - wait: appServerReady, - reuseExistingServer: false, - stdout: 'pipe', - }, - - projects: [ - { - name: 'chromium', - use: { ...devices['Desktop Chrome'] }, - }, - ], -}) diff --git a/e2e/vue-start/streaming-ssr/src/routeTree.gen.ts b/e2e/vue-start/streaming-ssr/src/routeTree.gen.ts deleted file mode 100644 index ac4c9ab156..0000000000 --- a/e2e/vue-start/streaming-ssr/src/routeTree.gen.ts +++ /dev/null @@ -1,282 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as ConcurrentRouteImport } from './routes/concurrent' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as DeferredRejectionRouteImport } from './routes/deferred-rejection' -import { Route as FastSerialRouteImport } from './routes/fast-serial' -import { Route as ManyPromisesRouteImport } from './routes/many-promises' -import { Route as NestedDeferredRouteImport } from './routes/nested-deferred' -import { Route as QueryHeavyRouteImport } from './routes/query-heavy' -import { Route as SlowRenderRouteImport } from './routes/slow-render' -import { Route as StreamRouteImport } from './routes/stream' -import { Route as SyncOnlyRouteImport } from './routes/sync-only' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const ConcurrentRoute = ConcurrentRouteImport.update({ - id: '/concurrent', - path: '/concurrent', - getParentRoute: () => rootRouteImport, -} as any) -const DeferredRoute = DeferredRouteImport.update({ - id: '/deferred', - path: '/deferred', - getParentRoute: () => rootRouteImport, -} as any) -const DeferredRejectionRoute = DeferredRejectionRouteImport.update({ - id: '/deferred-rejection', - path: '/deferred-rejection', - getParentRoute: () => rootRouteImport, -} as any) -const FastSerialRoute = FastSerialRouteImport.update({ - id: '/fast-serial', - path: '/fast-serial', - getParentRoute: () => rootRouteImport, -} as any) -const ManyPromisesRoute = ManyPromisesRouteImport.update({ - id: '/many-promises', - path: '/many-promises', - getParentRoute: () => rootRouteImport, -} as any) -const NestedDeferredRoute = NestedDeferredRouteImport.update({ - id: '/nested-deferred', - path: '/nested-deferred', - getParentRoute: () => rootRouteImport, -} as any) -const QueryHeavyRoute = QueryHeavyRouteImport.update({ - id: '/query-heavy', - path: '/query-heavy', - getParentRoute: () => rootRouteImport, -} as any) -const SlowRenderRoute = SlowRenderRouteImport.update({ - id: '/slow-render', - path: '/slow-render', - getParentRoute: () => rootRouteImport, -} as any) -const StreamRoute = StreamRouteImport.update({ - id: '/stream', - path: '/stream', - getParentRoute: () => rootRouteImport, -} as any) -const SyncOnlyRoute = SyncOnlyRouteImport.update({ - id: '/sync-only', - path: '/sync-only', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/concurrent': typeof ConcurrentRoute - '/deferred': typeof DeferredRoute - '/deferred-rejection': typeof DeferredRejectionRoute - '/fast-serial': typeof FastSerialRoute - '/many-promises': typeof ManyPromisesRoute - '/nested-deferred': typeof NestedDeferredRoute - '/query-heavy': typeof QueryHeavyRoute - '/slow-render': typeof SlowRenderRoute - '/stream': typeof StreamRoute - '/sync-only': typeof SyncOnlyRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/concurrent': typeof ConcurrentRoute - '/deferred': typeof DeferredRoute - '/deferred-rejection': typeof DeferredRejectionRoute - '/fast-serial': typeof FastSerialRoute - '/many-promises': typeof ManyPromisesRoute - '/nested-deferred': typeof NestedDeferredRoute - '/query-heavy': typeof QueryHeavyRoute - '/slow-render': typeof SlowRenderRoute - '/stream': typeof StreamRoute - '/sync-only': typeof SyncOnlyRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/concurrent': typeof ConcurrentRoute - '/deferred': typeof DeferredRoute - '/deferred-rejection': typeof DeferredRejectionRoute - '/fast-serial': typeof FastSerialRoute - '/many-promises': typeof ManyPromisesRoute - '/nested-deferred': typeof NestedDeferredRoute - '/query-heavy': typeof QueryHeavyRoute - '/slow-render': typeof SlowRenderRoute - '/stream': typeof StreamRoute - '/sync-only': typeof SyncOnlyRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/concurrent' - | '/deferred' - | '/deferred-rejection' - | '/fast-serial' - | '/many-promises' - | '/nested-deferred' - | '/query-heavy' - | '/slow-render' - | '/stream' - | '/sync-only' - fileRoutesByTo: FileRoutesByTo - to: - | '/' - | '/concurrent' - | '/deferred' - | '/deferred-rejection' - | '/fast-serial' - | '/many-promises' - | '/nested-deferred' - | '/query-heavy' - | '/slow-render' - | '/stream' - | '/sync-only' - id: - | '__root__' - | '/' - | '/concurrent' - | '/deferred' - | '/deferred-rejection' - | '/fast-serial' - | '/many-promises' - | '/nested-deferred' - | '/query-heavy' - | '/slow-render' - | '/stream' - | '/sync-only' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - ConcurrentRoute: typeof ConcurrentRoute - DeferredRoute: typeof DeferredRoute - DeferredRejectionRoute: typeof DeferredRejectionRoute - FastSerialRoute: typeof FastSerialRoute - ManyPromisesRoute: typeof ManyPromisesRoute - NestedDeferredRoute: typeof NestedDeferredRoute - QueryHeavyRoute: typeof QueryHeavyRoute - SlowRenderRoute: typeof SlowRenderRoute - StreamRoute: typeof StreamRoute - SyncOnlyRoute: typeof SyncOnlyRoute -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/concurrent': { - id: '/concurrent' - path: '/concurrent' - fullPath: '/concurrent' - preLoaderRoute: typeof ConcurrentRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred-rejection': { - id: '/deferred-rejection' - path: '/deferred-rejection' - fullPath: '/deferred-rejection' - preLoaderRoute: typeof DeferredRejectionRouteImport - parentRoute: typeof rootRouteImport - } - '/fast-serial': { - id: '/fast-serial' - path: '/fast-serial' - fullPath: '/fast-serial' - preLoaderRoute: typeof FastSerialRouteImport - parentRoute: typeof rootRouteImport - } - '/many-promises': { - id: '/many-promises' - path: '/many-promises' - fullPath: '/many-promises' - preLoaderRoute: typeof ManyPromisesRouteImport - parentRoute: typeof rootRouteImport - } - '/nested-deferred': { - id: '/nested-deferred' - path: '/nested-deferred' - fullPath: '/nested-deferred' - preLoaderRoute: typeof NestedDeferredRouteImport - parentRoute: typeof rootRouteImport - } - '/query-heavy': { - id: '/query-heavy' - path: '/query-heavy' - fullPath: '/query-heavy' - preLoaderRoute: typeof QueryHeavyRouteImport - parentRoute: typeof rootRouteImport - } - '/slow-render': { - id: '/slow-render' - path: '/slow-render' - fullPath: '/slow-render' - preLoaderRoute: typeof SlowRenderRouteImport - parentRoute: typeof rootRouteImport - } - '/stream': { - id: '/stream' - path: '/stream' - fullPath: '/stream' - preLoaderRoute: typeof StreamRouteImport - parentRoute: typeof rootRouteImport - } - '/sync-only': { - id: '/sync-only' - path: '/sync-only' - fullPath: '/sync-only' - preLoaderRoute: typeof SyncOnlyRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - ConcurrentRoute: ConcurrentRoute, - DeferredRoute: DeferredRoute, - DeferredRejectionRoute: DeferredRejectionRoute, - FastSerialRoute: FastSerialRoute, - ManyPromisesRoute: ManyPromisesRoute, - NestedDeferredRoute: NestedDeferredRoute, - QueryHeavyRoute: QueryHeavyRoute, - SlowRenderRoute: SlowRenderRoute, - StreamRoute: StreamRoute, - SyncOnlyRoute: SyncOnlyRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() - -import type { getRouter } from './router.tsx' -import type { createStart } from '@tanstack/vue-start' -declare module '@tanstack/vue-start' { - interface Register { - ssr: true - router: Awaited> - } -} diff --git a/e2e/vue-start/streaming-ssr/src/router.tsx b/e2e/vue-start/streaming-ssr/src/router.tsx deleted file mode 100644 index 257eb8dac9..0000000000 --- a/e2e/vue-start/streaming-ssr/src/router.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import { QueryClient } from '@tanstack/vue-query' -import { createRouter } from '@tanstack/vue-router' -import { setupRouterSsrQueryIntegration } from '@tanstack/vue-router-ssr-query' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - const queryClient = new QueryClient() - const router = createRouter({ - routeTree, - context: { queryClient }, - scrollRestoration: true, - }) - setupRouterSsrQueryIntegration({ - router, - queryClient, - }) - return router -} diff --git a/e2e/vue-start/streaming-ssr/src/routes/__root.tsx b/e2e/vue-start/streaming-ssr/src/routes/__root.tsx deleted file mode 100644 index d3b3339720..0000000000 --- a/e2e/vue-start/streaming-ssr/src/routes/__root.tsx +++ /dev/null @@ -1,103 +0,0 @@ -import { - Body, - HeadContent, - Html, - Link, - Outlet, - Scripts, - createRootRouteWithContext, -} from '@tanstack/vue-router' -import { defineComponent, ref } from 'vue' -import type { QueryClient } from '@tanstack/vue-query' - -export const Route = createRootRouteWithContext<{ - queryClient: QueryClient -}>()({ - head: () => ({ - meta: [ - { charSet: 'utf-8' }, - { name: 'viewport', content: 'width=device-width, initial-scale=1' }, - { title: 'Streaming SSR Tests' }, - ], - }), - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - - - ) -} - -const HydrationCheck = defineComponent({ - setup() { - const status = ref<'pending' | 'hydrated'>('pending') - - return () => ( -
- - - {status.value} - -
- ) - }, -}) diff --git a/e2e/vue-start/streaming-ssr/src/routes/concurrent.tsx b/e2e/vue-start/streaming-ssr/src/routes/concurrent.tsx deleted file mode 100644 index 5fed8ab517..0000000000 --- a/e2e/vue-start/streaming-ssr/src/routes/concurrent.tsx +++ /dev/null @@ -1,54 +0,0 @@ -import { Await, createFileRoute } from '@tanstack/vue-router' -import { Suspense } from 'vue' -import { createConcurrentLoaderData } from '../../../../streaming-ssr-fixtures' - -export const Route = createFileRoute('/concurrent')({ - loader: async () => createConcurrentLoaderData(), - component: Concurrent, -}) - -function PromiseItem(props: { promise: Promise; testId: string }) { - return ( - - {{ - default: () => ( - ( -
{value}
- )} - /> - ), - fallback: () => ( -
Loading...
- ), - }} -
- ) -} - -function Concurrent() { - const data = Route.useLoaderData() - - return ( -
-

Concurrent Resolution Test (15 promises in 3 batches)

-

Tests multiple promises resolving at the exact same instant.

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

Deferred Rejection Test

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

Deferred Data Test

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

Fast Serialization Test

-

This route tests when serialization completes before render.

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

Streaming SSR Test Scenarios

-

This e2e project tests various SSR streaming scenarios:

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

Many Promises Test (15 deferred)

-

Tests streaming with many concurrent deferred promises.

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

Nested Deferred Test

-

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

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

Query Heavy Test (9 useQuery calls)

-

Tests multiple useQuery with mixed sync/async queryFn.

-

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

- -
-
-

Sync Queries (immediate)

- - - -
- -
-

Fast Async Queries (50-100ms)

- - - -
- -
-

Slow Async Queries (200-400ms)

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

Slow Render Test

-

Tests when render takes longer than serialization.

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

ReadableStream Test

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

Stream chunks:

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

Synchronous Serialization Test

-

{data.value.message}

-

Loaded at: {data.value.timestamp}

-

Source: {data.value.source}

-
    - {data.value.items.map((item: string) => ( -
  • {item}
  • - ))} -
-
- ) -} diff --git a/e2e/vue-start/streaming-ssr/tests/client-navigation.spec.ts b/e2e/vue-start/streaming-ssr/tests/client-navigation.spec.ts deleted file mode 100644 index 8b9b3a8dcc..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/client-navigation.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/client-navigation' diff --git a/e2e/vue-start/streaming-ssr/tests/concurrent.spec.ts b/e2e/vue-start/streaming-ssr/tests/concurrent.spec.ts deleted file mode 100644 index 8625473a58..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/concurrent.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/concurrent' diff --git a/e2e/vue-start/streaming-ssr/tests/deferred-rejection.spec.ts b/e2e/vue-start/streaming-ssr/tests/deferred-rejection.spec.ts deleted file mode 100644 index 355b5019bc..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/deferred-rejection.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/deferred-rejection' diff --git a/e2e/vue-start/streaming-ssr/tests/deferred.spec.ts b/e2e/vue-start/streaming-ssr/tests/deferred.spec.ts deleted file mode 100644 index 3145897d7b..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/deferred.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/deferred' diff --git a/e2e/vue-start/streaming-ssr/tests/fast-serial.spec.ts b/e2e/vue-start/streaming-ssr/tests/fast-serial.spec.ts deleted file mode 100644 index 95df0555e2..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/fast-serial.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/fast-serial' diff --git a/e2e/vue-start/streaming-ssr/tests/home.spec.ts b/e2e/vue-start/streaming-ssr/tests/home.spec.ts deleted file mode 100644 index 5d49d34a56..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/home.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/home' diff --git a/e2e/vue-start/streaming-ssr/tests/many-promises.spec.ts b/e2e/vue-start/streaming-ssr/tests/many-promises.spec.ts deleted file mode 100644 index b747bd7d0a..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/many-promises.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/many-promises' diff --git a/e2e/vue-start/streaming-ssr/tests/nested-deferred.spec.ts b/e2e/vue-start/streaming-ssr/tests/nested-deferred.spec.ts deleted file mode 100644 index 8df20a8a95..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/nested-deferred.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/nested-deferred' diff --git a/e2e/vue-start/streaming-ssr/tests/preview-streaming.spec.ts b/e2e/vue-start/streaming-ssr/tests/preview-streaming.spec.ts deleted file mode 100644 index 34241cfbaa..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/preview-streaming.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/preview-streaming' diff --git a/e2e/vue-start/streaming-ssr/tests/query-heavy.spec.ts b/e2e/vue-start/streaming-ssr/tests/query-heavy.spec.ts deleted file mode 100644 index d15c092f6e..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/query-heavy.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/query-heavy' diff --git a/e2e/vue-start/streaming-ssr/tests/slow-render.spec.ts b/e2e/vue-start/streaming-ssr/tests/slow-render.spec.ts deleted file mode 100644 index 0d5a87363f..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/slow-render.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/slow-render' diff --git a/e2e/vue-start/streaming-ssr/tests/stream.spec.ts b/e2e/vue-start/streaming-ssr/tests/stream.spec.ts deleted file mode 100644 index 9dfc6820ad..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/stream.spec.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { expect, testWithHydration } from '../../../streaming-ssr-assertions' -import '../../../streaming-ssr-specs/stream' - -testWithHydration( - 'reads a replacement stream after an active read', - async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - await page.getByRole('link', { name: 'Stream' }).first().click() - await expect(page.getByTestId('stream-chunk-0')).toHaveText('chunk-0') - await expect(page.getByTestId('stream-complete')).toHaveCount(0) - - await page.getByTestId('refresh-stream').click() - - const streamData = page.getByTestId('stream-data') - await expect(streamData).toHaveAttribute('data-read-count', '2') - await expect(page.getByTestId('stream-complete')).toBeVisible() - await expect( - streamData.locator('[data-testid^="stream-chunk-"]'), - ).toHaveText(['chunk-0', 'chunk-1', 'chunk-2', 'chunk-3', 'chunk-4']) - }, -) diff --git a/e2e/vue-start/streaming-ssr/tests/sync-only.spec.ts b/e2e/vue-start/streaming-ssr/tests/sync-only.spec.ts deleted file mode 100644 index b25572f615..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/sync-only.spec.ts +++ /dev/null @@ -1,7 +0,0 @@ -import '../../../streaming-ssr-specs/sync-only' -import { expect, test } from '../../../streaming-ssr-assertions' - -test('Vue renders an unwrapped document root', async ({ request }) => { - const response = await request.get('/sync-only') - expect(await response.text()).toMatch(/^)/) -}) diff --git a/e2e/vue-start/streaming-ssr/tsconfig.json b/e2e/vue-start/streaming-ssr/tsconfig.json deleted file mode 100644 index 390dad84c0..0000000000 --- a/e2e/vue-start/streaming-ssr/tsconfig.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "include": ["**/*.ts", "**/*.tsx"], - "compilerOptions": { - "strict": true, - "esModuleInterop": true, - "jsx": "preserve", - "jsxImportSource": "vue", - "module": "ESNext", - "moduleResolution": "Bundler", - "lib": ["DOM", "DOM.Iterable", "ES2022"], - "isolatedModules": true, - "resolveJsonModule": true, - "skipLibCheck": true, - "target": "ES2022", - "allowJs": true, - "forceConsistentCasingInFileNames": true, - "paths": { - "~/*": ["./src/*"] - }, - "noEmit": true - } -} diff --git a/e2e/vue-start/streaming-ssr/vite.config.ts b/e2e/vue-start/streaming-ssr/vite.config.ts deleted file mode 100644 index 6519ec54c8..0000000000 --- a/e2e/vue-start/streaming-ssr/vite.config.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { defineConfig } from 'vite' -import { tanstackStart } from '@tanstack/vue-start/plugin/vite' -import vueJsx from '@vitejs/plugin-vue-jsx' - -export default defineConfig({ - server: { - port: 3000, - }, - plugins: [tanstackStart(), vueJsx()], -}) diff --git a/e2e/vue-start/virtual-routes/package.json b/e2e/vue-start/virtual-routes/package.json index 90f09ce911..4bec2251e0 100644 --- a/e2e/vue-start/virtual-routes/package.json +++ b/e2e/vue-start/virtual-routes/package.json @@ -9,30 +9,29 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { - "@tanstack/virtual-file-routes": "workspace:^", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-start": "workspace:^", - "redaxios": "catalog:", - "tailwind-merge": "^3.6.0", + "@tanstack/virtual-file-routes": "workspace:^", + "redaxios": "^0.5.1", + "tailwind-merge": "^2.6.0", + "vite": "^8.0.0", "vue": "^3.5.25", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", - "@vitejs/plugin-vue": "^6.0.5", - "@vitejs/plugin-vue-jsx": "^5.1.5", "combinate": "^1.1.11", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "typescript": "^5.7.2", + "@vitejs/plugin-vue": "^6.0.5", + "@vitejs/plugin-vue-jsx": "^5.1.5" } } diff --git a/e2e/vue-start/virtual-routes/playwright.config.ts b/e2e/vue-start/virtual-routes/playwright.config.ts index 1862174905..b0c365f8bd 100644 --- a/e2e/vue-start/virtual-routes/playwright.config.ts +++ b/e2e/vue-start/virtual-routes/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -13,19 +18,19 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', - env: { - NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, - }, }, projects: [ diff --git a/e2e/vue-start/virtual-routes/src/posts.tsx b/e2e/vue-start/virtual-routes/src/posts.tsx index f7a1941605..1b4c92b41d 100644 --- a/e2e/vue-start/virtual-routes/src/posts.tsx +++ b/e2e/vue-start/virtual-routes/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/vue-start/virtual-routes/src/routeTree.gen.ts b/e2e/vue-start/virtual-routes/src/routeTree.gen.ts index 1a1bc2d27b..94664b2e5b 100644 --- a/e2e/vue-start/virtual-routes/src/routeTree.gen.ts +++ b/e2e/vue-start/virtual-routes/src/routeTree.gen.ts @@ -9,27 +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 homeRouteImport } from './routes/home' -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 ClassicHelloRouteRouteImport } from './routes/file-based-subtree/hello/route' -import { Route as postsPostsHomeRouteImport } from './routes/posts/posts-home' +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 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 ClassicHelloUniverseRouteImport } from './routes/file-based-subtree/hello/universe' import { Route as ClassicHelloWorldRouteImport } from './routes/file-based-subtree/hello/world' -import { Route as aRouteImport } from './routes/a' +import { Route as ClassicHelloUniverseRouteImport } from './routes/file-based-subtree/hello/universe' import { Route as bRouteImport } from './routes/b' +import { Route as aRouteImport } from './routes/a' -const homeRoute = homeRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const layoutFirstLayoutRoute = layoutFirstLayoutRouteImport.update({ - id: '/_first', +const pipeRoute = pipeRouteImport.update({ + id: '/special|pipe', + path: '/special|pipe', getParentRoute: () => rootRouteImport, } as any) const postsPostsRoute = postsPostsRouteImport.update({ @@ -37,55 +33,59 @@ const postsPostsRoute = postsPostsRouteImport.update({ path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const pipeRoute = pipeRouteImport.update({ - id: '/special|pipe', - path: '/special|pipe', +const layoutFirstLayoutRoute = layoutFirstLayoutRouteImport.update({ + id: '/_first', getParentRoute: () => rootRouteImport, } as any) -const layoutSecondLayoutRoute = layoutSecondLayoutRouteImport.update({ - id: '/_second-layout', - getParentRoute: () => layoutFirstLayoutRoute, -} as any) -const ClassicHelloRouteRoute = ClassicHelloRouteRouteImport.update({ - id: '/classic/hello', - path: '/classic/hello', - getParentRoute: () => rootRouteImport, -} as any) -const postsPostsHomeRoute = postsPostsHomeRouteImport.update({ +const homeRoute = homeRouteImport.update({ id: '/', path: '/', - getParentRoute: () => postsPostsRoute, + 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 ClassicHelloIndexRoute = ClassicHelloIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => ClassicHelloRouteRoute, } as any) -const ClassicHelloUniverseRoute = ClassicHelloUniverseRouteImport.update({ - id: '/universe', - path: '/universe', - getParentRoute: () => ClassicHelloRouteRoute, -} as any) 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, +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, } as any) +const aRoute = aRouteImport.update({ + id: '/route-without-file/layout-a', + path: '/route-without-file/layout-a', + getParentRoute: () => layoutSecondLayoutRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof homeRoute @@ -179,18 +179,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof homeRouteImport - parentRoute: typeof rootRouteImport - } - '/_first': { - id: '/_first' - path: '' - fullPath: '/' - preLoaderRoute: typeof layoutFirstLayoutRouteImport + '/special|pipe': { + id: '/special|pipe' + path: '/special|pipe' + fullPath: '/special|pipe' + preLoaderRoute: typeof pipeRouteImport parentRoute: typeof rootRouteImport } '/posts': { @@ -200,33 +193,19 @@ declare module '@tanstack/vue-router' { 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' + '/_first': { + id: '/_first' path: '' fullPath: '/' - preLoaderRoute: typeof layoutSecondLayoutRouteImport - parentRoute: typeof layoutFirstLayoutRoute - } - '/classic/hello': { - id: '/classic/hello' - path: '/classic/hello' - fullPath: '/classic/hello' - preLoaderRoute: typeof ClassicHelloRouteRouteImport + preLoaderRoute: typeof layoutFirstLayoutRouteImport parentRoute: typeof rootRouteImport } - '/posts/': { - id: '/posts/' + '/': { + id: '/' path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof postsPostsHomeRouteImport - parentRoute: typeof postsPostsRoute + fullPath: '/' + preLoaderRoute: typeof homeRouteImport + parentRoute: typeof rootRouteImport } '/posts/$postId': { id: '/posts/$postId' @@ -235,6 +214,27 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof postsPostsDetailRouteImport parentRoute: typeof postsPostsRoute } + '/_first/_second-layout': { + id: '/_first/_second-layout' + path: '' + 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' + fullPath: '/classic/hello' + preLoaderRoute: typeof ClassicHelloRouteRouteImport + parentRoute: typeof rootRouteImport + } '/classic/hello/': { id: '/classic/hello/' path: '/' @@ -242,13 +242,6 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof ClassicHelloIndexRouteImport parentRoute: typeof ClassicHelloRouteRoute } - '/classic/hello/universe': { - id: '/classic/hello/universe' - path: '/universe' - fullPath: '/classic/hello/universe' - preLoaderRoute: typeof ClassicHelloUniverseRouteImport - parentRoute: typeof ClassicHelloRouteRoute - } '/classic/hello/world': { id: '/classic/hello/world' path: '/world' @@ -256,12 +249,12 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof ClassicHelloWorldRouteImport parentRoute: typeof ClassicHelloRouteRoute } - '/_first/_second-layout/route-without-file/layout-a': { - id: '/_first/_second-layout/route-without-file/layout-a' - path: '/route-without-file/layout-a' - fullPath: '/route-without-file/layout-a' - preLoaderRoute: typeof aRouteImport - parentRoute: typeof layoutSecondLayoutRoute + '/classic/hello/universe': { + id: '/classic/hello/universe' + path: '/universe' + fullPath: '/classic/hello/universe' + preLoaderRoute: typeof ClassicHelloUniverseRouteImport + parentRoute: typeof ClassicHelloRouteRoute } '/_first/_second-layout/route-without-file/layout-b': { id: '/_first/_second-layout/route-without-file/layout-b' @@ -270,6 +263,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof bRouteImport parentRoute: typeof layoutSecondLayoutRoute } + '/_first/_second-layout/route-without-file/layout-a': { + id: '/_first/_second-layout/route-without-file/layout-a' + path: '/route-without-file/layout-a' + fullPath: '/route-without-file/layout-a' + preLoaderRoute: typeof aRouteImport + parentRoute: typeof layoutSecondLayoutRoute + } } } diff --git a/e2e/vue-start/virtual-routes/src/routes/posts/posts-detail.tsx b/e2e/vue-start/virtual-routes/src/routes/posts/posts-detail.tsx index 4bc3824f62..5086e3ad88 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,20 +1,7 @@ -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, @@ -27,3 +14,14 @@ 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 dd380aa353..f56d6550a6 100644 --- a/e2e/vue-start/virtual-routes/src/routes/posts/posts.tsx +++ b/e2e/vue-start/virtual-routes/src/routes/posts/posts.tsx @@ -1,39 +1,37 @@ -import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '../../posts' -const PostsComponent = defineComponent({ - setup() { - const posts = Route.useLoaderData() - return () => ( -
-
    - {[ - ...posts.value, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ))} -
-
- -
- ) - }, -}) - export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsComponent, }) + +function PostsComponent() { + const posts = Route.useLoaderData() + + return ( +
+
    + {[ + ...posts.value, + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ))} +
+
+ +
+ ) +} diff --git a/e2e/vue-start/virtual-routes/src/utils/posts.tsx b/e2e/vue-start/virtual-routes/src/utils/posts.tsx index 11d80d08b5..a193bbc7af 100644 --- a/e2e/vue-start/virtual-routes/src/utils/posts.tsx +++ b/e2e/vue-start/virtual-routes/src/utils/posts.tsx @@ -8,10 +8,14 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPost = createServerFn({ method: 'GET' }) - .validator((postId: string) => postId) + .inputValidator((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 7ba645b383..46be4b1580 100644 --- a/e2e/vue-start/virtual-routes/src/utils/users.tsx +++ b/e2e/vue-start/virtual-routes/src/utils/users.tsx @@ -3,3 +3,7 @@ export type User = { name: string email: string } + +const PORT = process.env.VITE_SERVER_PORT || 3000 + +export const DEPLOY_URL = `http://localhost:${PORT}` diff --git a/e2e/vue-start/virtual-routes/tests/app.spec.ts b/e2e/vue-start/virtual-routes/tests/app.spec.ts index e9db98e3f3..3182febfa0 100644 --- a/e2e/vue-start/virtual-routes/tests/app.spec.ts +++ b/e2e/vue-start/virtual-routes/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-start/virtual-routes/tests/setup/global.setup.ts b/e2e/vue-start/virtual-routes/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-start/virtual-routes/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-start/virtual-routes/tests/setup/global.teardown.ts b/e2e/vue-start/virtual-routes/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-start/virtual-routes/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-start/virtual-routes/tsconfig.json b/e2e/vue-start/virtual-routes/tsconfig.json index 6f99c0f49a..6d933a5b2c 100644 --- a/e2e/vue-start/virtual-routes/tsconfig.json +++ b/e2e/vue-start/virtual-routes/tsconfig.json @@ -14,6 +14,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/vue-start/website/package.json b/e2e/vue-start/website/package.json index 6c30b1500f..35fb913ed8 100644 --- a/e2e/vue-start/website/package.json +++ b/e2e/vue-start/website/package.json @@ -9,28 +9,27 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-start": "workspace:^", - "redaxios": "catalog:", - "tailwind-merge": "^3.6.0", + "redaxios": "^0.5.1", + "tailwind-merge": "^2.6.0", + "vite": "^8.0.0", "vue": "^3.5.25", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", - "@vitejs/plugin-vue": "^6.0.5", - "@vitejs/plugin-vue-jsx": "^5.1.5", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "typescript": "^5.7.2", + "@vitejs/plugin-vue": "^6.0.5", + "@vitejs/plugin-vue-jsx": "^5.1.5" } } diff --git a/e2e/vue-start/website/playwright.config.ts b/e2e/vue-start/website/playwright.config.ts index e6b92ce385..f6dd61ba6c 100644 --- a/e2e/vue-start/website/playwright.config.ts +++ b/e2e/vue-start/website/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -20,8 +21,8 @@ export default defineConfig({ webServer: { command: `pnpm build && VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-start/website/src/components/DefaultCatchBoundary.tsx b/e2e/vue-start/website/src/components/DefaultCatchBoundary.tsx index 77c03c5afa..b1f818dd74 100644 --- a/e2e/vue-start/website/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/website/src/components/DefaultCatchBoundary.tsx @@ -1,61 +1,53 @@ -import { defineComponent } from 'vue' -import type { PropType } from 'vue' import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, useRouter, } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' -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 - - )} -
-
- ) - } - }, -}) +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 + + )} +
+
+ ) +} diff --git a/e2e/vue-start/website/src/routeTree.gen.ts b/e2e/vue-start/website/src/routeTree.gen.ts index 0909725a4b..e7b58aae2a 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 ProjectIndexRouteImport } from './routes/$project.index' import { Route as LibraryIndexRouteImport } from './routes/_library.index' +import { Route as ProjectIndexRouteImport } from './routes/$project.index' import { Route as LibraryProjectRouteImport } from './routes/_library.$project' -import { Route as ProjectVersionDocsIndexRouteImport } from './routes/$project.$version.docs.index' import { Route as LibraryProjectVersionIndexRouteImport } from './routes/_library.$project.$version.index' +import { Route as ProjectVersionDocsIndexRouteImport } from './routes/$project.$version.docs.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 ProjectIndexRoute = ProjectIndexRouteImport.update({ - id: '/$project/', - path: '/$project/', - 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 LibraryProjectRoute = LibraryProjectRouteImport.update({ id: '/$project', path: '/$project', getParentRoute: () => LibraryRoute, } as any) -const ProjectVersionDocsIndexRoute = ProjectVersionDocsIndexRouteImport.update({ - id: '/$project/$version/docs/', - path: '/$project/$version/docs/', - getParentRoute: () => rootRouteImport, -} as any) const LibraryProjectVersionIndexRoute = LibraryProjectVersionIndexRouteImport.update({ id: '/$version/', path: '/$version/', getParentRoute: () => LibraryProjectRoute, } as any) +const ProjectVersionDocsIndexRoute = ProjectVersionDocsIndexRouteImport.update({ + id: '/$project/$version/docs/', + path: '/$project/$version/docs/', + getParentRoute: () => rootRouteImport, +} as any) const ProjectVersionDocsFrameworkFrameworkRoute = ProjectVersionDocsFrameworkFrameworkRouteImport.update({ id: '/$project/$version/docs/framework/$framework', @@ -159,13 +159,6 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof LibraryRouteImport parentRoute: typeof rootRouteImport } - '/$project/': { - id: '/$project/' - path: '/$project' - fullPath: '/$project/' - preLoaderRoute: typeof ProjectIndexRouteImport - parentRoute: typeof rootRouteImport - } '/_library/': { id: '/_library/' path: '/' @@ -173,6 +166,13 @@ 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' @@ -180,13 +180,6 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof LibraryProjectRouteImport parentRoute: typeof LibraryRoute } - '/$project/$version/docs/': { - id: '/$project/$version/docs/' - path: '/$project/$version/docs' - fullPath: '/$project/$version/docs/' - preLoaderRoute: typeof ProjectVersionDocsIndexRouteImport - parentRoute: typeof rootRouteImport - } '/_library/$project/$version/': { id: '/_library/$project/$version/' path: '/$version' @@ -194,6 +187,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof LibraryProjectVersionIndexRouteImport parentRoute: typeof LibraryProjectRoute } + '/$project/$version/docs/': { + id: '/$project/$version/docs/' + path: '/$project/$version/docs' + fullPath: '/$project/$version/docs/' + preLoaderRoute: typeof ProjectVersionDocsIndexRouteImport + parentRoute: typeof rootRouteImport + } '/$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 1d9173f200..f56c911b88 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,27 +1,9 @@ -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/$', )({ @@ -44,3 +26,19 @@ 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 1ca9e97cbe..97f8fdd49a 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,24 +1,7 @@ -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/$', )({ @@ -32,3 +15,18 @@ 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 e1c57491aa..1b422b2ea0 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,4 +1,3 @@ -import { defineComponent } from 'vue' import { Link, Outlet, @@ -8,108 +7,6 @@ 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', )({ @@ -123,3 +20,104 @@ export const Route = createFileRoute( }, component: Page, }) + +function Page() { + const project = Route.useLoaderData({ select: (s) => s.library }) + const documents = Route.useLoaderData({ select: (s) => s.documents }) + const pathname = useLocation({ select: (s) => s.pathname }) + + return ( +
+ +
+

+ {pathname.value} +

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

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

- ) + return

{props.error.stack}

}, 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 d6c9b00671..ed8e4d0bb4 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,31 +1,23 @@ -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 b52198950d..fcbeaa35d0 100644 --- a/e2e/vue-start/website/src/routes/_library.tsx +++ b/e2e/vue-start/website/src/routes/_library.tsx @@ -1,4 +1,3 @@ -import { defineComponent } from 'vue' import { Link, Outlet, @@ -7,53 +6,6 @@ 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() @@ -63,3 +15,48 @@ 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 883efbed80..6623a50a5c 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' }) - .validator((id: string) => id) + .inputValidator((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 4ca98c754f..c97604a199 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' }) - .validator((project: string) => project) + .inputValidator((project: string) => project) .handler(async (ctx) => { await new Promise((resolve) => setTimeout(resolve, 200)) diff --git a/e2e/vue-start/website/tsconfig.json b/e2e/vue-start/website/tsconfig.json index 390dad84c0..f9f5aab3da 100644 --- a/e2e/vue-start/website/tsconfig.json +++ b/e2e/vue-start/website/tsconfig.json @@ -14,6 +14,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/AGENTS.md b/examples/AGENTS.md deleted file mode 100644 index eb47fbd925..0000000000 --- a/examples/AGENTS.md +++ /dev/null @@ -1,4 +0,0 @@ -# Examples - -- Versioned dependencies on this repository's packages resolve locally through `pnpm-workspace.yaml` overrides. Keep published version ranges in example manifests; do not replace them with `workspace:*` as a linking fix. -- Root `pnpm dev` watches package builds. To run an example app, use its own `dev` script after building its workspace dependencies. diff --git a/examples/react/authenticated-routes-firebase/package.json b/examples/react/authenticated-routes-firebase/package.json index 1efa172047..fef9c81195 100644 --- a/examples/react/authenticated-routes-firebase/package.json +++ b/examples/react/authenticated-routes-firebase/package.json @@ -10,23 +10,22 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", + "@tanstack/router-plugin": "^1.167.2", "firebase": "^11.4.0", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", "simple-icons": "^14.9.0", "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { "@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" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/react/authenticated-routes-firebase/src/routeTree.gen.ts b/examples/react/authenticated-routes-firebase/src/routeTree.gen.ts index bcc454ab03..0e81c27c1c 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 IndexRouteImport } from './routes/index' -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 AuthRouteImport } from './routes/_auth' +import { Route as IndexRouteImport } from './routes/index' import { Route as AuthInvoicesRouteImport } from './routes/_auth.invoices' +import { Route as AuthDashboardRouteImport } from './routes/_auth.dashboard' import { Route as AuthInvoicesIndexRouteImport } from './routes/_auth.invoices.index' import { Route as AuthInvoicesInvoiceIdRouteImport } from './routes/_auth.invoices.$invoiceId' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const LoginRoute = LoginRouteImport.update({ + id: '/login', + path: '/login', getParentRoute: () => rootRouteImport, } as any) const AuthRoute = AuthRouteImport.update({ id: '/_auth', getParentRoute: () => rootRouteImport, } as any) -const LoginRoute = LoginRouteImport.update({ - id: '/login', - path: '/login', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } 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 AuthDashboardRoute = AuthDashboardRouteImport.update({ + id: '/dashboard', + path: '/dashboard', + getParentRoute: () => AuthRoute, +} as any) const AuthInvoicesIndexRoute = AuthInvoicesIndexRouteImport.update({ id: '/', path: '/', @@ -107,11 +107,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/login': { + id: '/login' + path: '/login' + fullPath: '/login' + preLoaderRoute: typeof LoginRouteImport parentRoute: typeof rootRouteImport } '/_auth': { @@ -121,20 +121,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthRouteImport parentRoute: typeof rootRouteImport } - '/login': { - id: '/login' - path: '/login' - fullPath: '/login' - preLoaderRoute: typeof LoginRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/_auth/dashboard': { - id: '/_auth/dashboard' - path: '/dashboard' - fullPath: '/dashboard' - preLoaderRoute: typeof AuthDashboardRouteImport - parentRoute: typeof AuthRoute - } '/_auth/invoices': { id: '/_auth/invoices' path: '/invoices' @@ -142,6 +135,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthInvoicesRouteImport parentRoute: typeof AuthRoute } + '/_auth/dashboard': { + id: '/_auth/dashboard' + path: '/dashboard' + fullPath: '/dashboard' + preLoaderRoute: typeof AuthDashboardRouteImport + parentRoute: typeof AuthRoute + } '/_auth/invoices/': { id: '/_auth/invoices/' path: '/' diff --git a/examples/react/authenticated-routes/package.json b/examples/react/authenticated-routes/package.json index 6af48f1d34..0a8df4069f 100644 --- a/examples/react/authenticated-routes/package.json +++ b/examples/react/authenticated-routes/package.json @@ -10,21 +10,20 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", + "@tanstack/router-plugin": "^1.167.2", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { "@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" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/react/authenticated-routes/src/routeTree.gen.ts b/examples/react/authenticated-routes/src/routeTree.gen.ts index bcc454ab03..0e81c27c1c 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 IndexRouteImport } from './routes/index' -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 AuthRouteImport } from './routes/_auth' +import { Route as IndexRouteImport } from './routes/index' import { Route as AuthInvoicesRouteImport } from './routes/_auth.invoices' +import { Route as AuthDashboardRouteImport } from './routes/_auth.dashboard' import { Route as AuthInvoicesIndexRouteImport } from './routes/_auth.invoices.index' import { Route as AuthInvoicesInvoiceIdRouteImport } from './routes/_auth.invoices.$invoiceId' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const LoginRoute = LoginRouteImport.update({ + id: '/login', + path: '/login', getParentRoute: () => rootRouteImport, } as any) const AuthRoute = AuthRouteImport.update({ id: '/_auth', getParentRoute: () => rootRouteImport, } as any) -const LoginRoute = LoginRouteImport.update({ - id: '/login', - path: '/login', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } 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 AuthDashboardRoute = AuthDashboardRouteImport.update({ + id: '/dashboard', + path: '/dashboard', + getParentRoute: () => AuthRoute, +} as any) const AuthInvoicesIndexRoute = AuthInvoicesIndexRouteImport.update({ id: '/', path: '/', @@ -107,11 +107,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/login': { + id: '/login' + path: '/login' + fullPath: '/login' + preLoaderRoute: typeof LoginRouteImport parentRoute: typeof rootRouteImport } '/_auth': { @@ -121,20 +121,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthRouteImport parentRoute: typeof rootRouteImport } - '/login': { - id: '/login' - path: '/login' - fullPath: '/login' - preLoaderRoute: typeof LoginRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/_auth/dashboard': { - id: '/_auth/dashboard' - path: '/dashboard' - fullPath: '/dashboard' - preLoaderRoute: typeof AuthDashboardRouteImport - parentRoute: typeof AuthRoute - } '/_auth/invoices': { id: '/_auth/invoices' path: '/invoices' @@ -142,6 +135,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthInvoicesRouteImport parentRoute: typeof AuthRoute } + '/_auth/dashboard': { + id: '/_auth/dashboard' + path: '/dashboard' + fullPath: '/dashboard' + preLoaderRoute: typeof AuthDashboardRouteImport + parentRoute: typeof AuthRoute + } '/_auth/invoices/': { id: '/_auth/invoices/' path: '/' diff --git a/examples/react/authenticated-routes/src/vite-env.d.ts b/examples/react/authenticated-routes/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/authenticated-routes/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/basic-default-search-params/package.json b/examples/react/basic-default-search-params/package.json index 96c68fecd4..900eff120a 100644 --- a/examples/react/basic-default-search-params/package.json +++ b/examples/react/basic-default-search-params/package.json @@ -10,21 +10,20 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.102.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-query": "^5.90.0", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { "@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" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } 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 deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/basic-default-search-params/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/basic-devtools-panel/package.json b/examples/react/basic-devtools-panel/package.json index ccae95d73f..b7813326aa 100644 --- a/examples/react/basic-devtools-panel/package.json +++ b/examples/react/basic-devtools-panel/package.json @@ -10,10 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.102.0", "@tanstack/react-query-devtools": "^5.67.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -23,8 +22,7 @@ "@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" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/react/basic-devtools-panel/src/vite-env.d.ts b/examples/react/basic-devtools-panel/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/basic-devtools-panel/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/basic-file-based/package.json b/examples/react/basic-file-based/package.json index 9c3cacada1..952051010b 100644 --- a/examples/react/basic-file-based/package.json +++ b/examples/react/basic-file-based/package.json @@ -10,21 +10,20 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", + "@tanstack/router-plugin": "^1.167.2", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { "@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" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/react/basic-file-based/src/routeTree.gen.ts b/examples/react/basic-file-based/src/routeTree.gen.ts index f370ad5d03..9d28e9a236 100644 --- a/examples/react/basic-file-based/src/routeTree.gen.ts +++ b/examples/react/basic-file-based/src/routeTree.gen.ts @@ -9,40 +9,35 @@ // Additionally, you should also exclude this file 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 AnchorRouteImport } from './routes/anchor' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as PostsRouteRouteImport } from './routes/posts.route' -import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-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 PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +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' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const AnchorRoute = AnchorRouteImport.update({ + id: '/anchor', + path: '/anchor', 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 PathlessLayoutNestedLayoutRoute = - PathlessLayoutNestedLayoutRouteImport.update({ - id: '/_nested-layout', - getParentRoute: () => PathlessLayoutRoute, - } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -53,11 +48,10 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ path: '/$postId', getParentRoute: () => PostsRouteRoute, } as any) -const PathlessLayoutNestedLayoutRouteARoute = - PathlessLayoutNestedLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, +const PathlessLayoutNestedLayoutRoute = + PathlessLayoutNestedLayoutRouteImport.update({ + id: '/_nested-layout', + getParentRoute: () => PathlessLayoutRoute, } as any) const PathlessLayoutNestedLayoutRouteBRoute = PathlessLayoutNestedLayoutRouteBRouteImport.update({ @@ -65,6 +59,12 @@ const PathlessLayoutNestedLayoutRouteBRoute = path: '/route-b', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) +const PathlessLayoutNestedLayoutRouteARoute = + PathlessLayoutNestedLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + } as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -129,11 +129,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/anchor': { + id: '/anchor' + path: '/anchor' + fullPath: '/anchor' + preLoaderRoute: typeof AnchorRouteImport parentRoute: typeof rootRouteImport } '/_pathlessLayout': { @@ -143,13 +143,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PathlessLayoutRouteImport parentRoute: typeof rootRouteImport } - '/anchor': { - id: '/anchor' - path: '/anchor' - fullPath: '/anchor' - preLoaderRoute: typeof AnchorRouteImport - parentRoute: typeof rootRouteImport - } '/posts': { id: '/posts' path: '/posts' @@ -157,12 +150,12 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' - path: '' + '/': { + id: '/' + path: '/' fullPath: '/' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport } '/posts/': { id: '/posts/' @@ -178,12 +171,12 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRouteRoute } - '/_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': { + id: '/_pathlessLayout/_nested-layout' + path: '' + fullPath: '/' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -192,6 +185,13 @@ 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/vite-env.d.ts b/examples/react/basic-file-based/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/basic-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/basic-non-nested-devtools/package.json b/examples/react/basic-non-nested-devtools/package.json index 32e856ebcf..4db0deae86 100644 --- a/examples/react/basic-non-nested-devtools/package.json +++ b/examples/react/basic-non-nested-devtools/package.json @@ -10,8 +10,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -21,8 +21,7 @@ "@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" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } 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 deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/basic-non-nested-devtools/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/basic-react-query-file-based/package.json b/examples/react/basic-react-query-file-based/package.json index d01a02872e..f65e12e528 100644 --- a/examples/react/basic-react-query-file-based/package.json +++ b/examples/react/basic-react-query-file-based/package.json @@ -10,23 +10,22 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.102.0", + "@tanstack/react-query": "^5.90.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", + "@tanstack/router-plugin": "^1.167.2", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { "@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" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } 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 9676858c7c..28cfbec8ed 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,20 +9,15 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as PostsRouteRouteImport } from './routes/posts.route' -import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-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 PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +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' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, @@ -32,11 +27,11 @@ const PostsRouteRoute = PostsRouteRouteImport.update({ path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const PathlessLayoutNestedLayoutRoute = - PathlessLayoutNestedLayoutRouteImport.update({ - id: '/_nested-layout', - getParentRoute: () => PathlessLayoutRoute, - } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -47,11 +42,10 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ path: '/$postId', getParentRoute: () => PostsRouteRoute, } as any) -const PathlessLayoutNestedLayoutRouteARoute = - PathlessLayoutNestedLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, +const PathlessLayoutNestedLayoutRoute = + PathlessLayoutNestedLayoutRouteImport.update({ + id: '/_nested-layout', + getParentRoute: () => PathlessLayoutRoute, } as any) const PathlessLayoutNestedLayoutRouteBRoute = PathlessLayoutNestedLayoutRouteBRouteImport.update({ @@ -59,6 +53,12 @@ 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,13 +117,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/_pathlessLayout': { id: '/_pathlessLayout' path: '' @@ -138,12 +131,12 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' - path: '' + '/': { + id: '/' + path: '/' fullPath: '/' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport } '/posts/': { id: '/posts/' @@ -159,12 +152,12 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRouteRoute } - '/_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': { + id: '/_pathlessLayout/_nested-layout' + path: '' + fullPath: '/' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -173,6 +166,13 @@ 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/vite-env.d.ts b/examples/react/basic-react-query-file-based/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/basic-react-query-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/basic-react-query/package.json b/examples/react/basic-react-query/package.json index edab96afac..73d80a9297 100644 --- a/examples/react/basic-react-query/package.json +++ b/examples/react/basic-react-query/package.json @@ -10,10 +10,10 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.102.0", + "@tanstack/react-query": "^5.90.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -23,8 +23,7 @@ "@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" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/react/basic-react-query/src/vite-env.d.ts b/examples/react/basic-react-query/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/basic-react-query/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/basic-ssr-file-based/package.json b/examples/react/basic-ssr-file-based/package.json index 3222c33e19..1cf253b817 100644 --- a/examples/react/basic-ssr-file-based/package.json +++ b/examples/react/basic-ssr-file-based/package.json @@ -11,23 +11,22 @@ "debug": "node --inspect-brk server" }, "dependencies": { - "@tanstack/react-router": "^1.170.46", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.168.1", + "@tanstack/router-plugin": "^1.167.2", "compression": "^1.8.0", - "express": "^5.2.1", + "express": "^4.21.2", "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.167.3", - "@types/express": "^5.0.6", + "@tanstack/react-router-devtools": "^1.166.10", + "@types/express": "^4.17.23", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.1", "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "typescript": "^5.8.3", + "vite": "^8.0.0" } } diff --git a/examples/react/basic-ssr-file-based/server.js b/examples/react/basic-ssr-file-based/server.js index 6d060a19f0..5686edc048 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('/{*splat}', async (req, res) => { + app.use('*', async (req, res) => { try { const url = req.originalUrl @@ -97,8 +97,7 @@ export async function createServer( if (!isTest) { createServer().then(async ({ app }) => - app.listen(await getPort({ port: portNumbers(3000, 3100) }), (error) => { - if (error) throw error + app.listen(await getPort({ port: portNumbers(3000, 3100) }), () => { 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 6f9f3f0f5e..4e61620e43 100644 --- a/examples/react/basic-ssr-file-based/src/routeTree.gen.ts +++ b/examples/react/basic-ssr-file-based/src/routeTree.gen.ts @@ -9,17 +9,12 @@ // Additionally, you should also exclude this file 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', @@ -30,6 +25,11 @@ 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,13 +78,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/error': { id: '/error' path: '/error' @@ -99,6 +92,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } '/posts/': { id: '/posts/' path: '/' diff --git a/examples/react/basic-ssr-streaming-file-based/package.json b/examples/react/basic-ssr-streaming-file-based/package.json index c3c87c8d88..cccd3e9554 100644 --- a/examples/react/basic-ssr-streaming-file-based/package.json +++ b/examples/react/basic-ssr-streaming-file-based/package.json @@ -11,23 +11,22 @@ "debug": "node --inspect-brk server" }, "dependencies": { - "@tanstack/react-router": "^1.170.46", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.168.1", + "@tanstack/router-plugin": "^1.167.2", "compression": "^1.8.0", - "express": "^5.2.1", + "express": "^4.21.2", "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.167.3", - "@types/express": "^5.0.6", + "@tanstack/react-router-devtools": "^1.166.10", + "@types/express": "^4.17.23", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.1", "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/react/basic-ssr-streaming-file-based/server.js b/examples/react/basic-ssr-streaming-file-based/server.js index 6d060a19f0..5686edc048 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('/{*splat}', async (req, res) => { + app.use('*', async (req, res) => { try { const url = req.originalUrl @@ -97,8 +97,7 @@ export async function createServer( if (!isTest) { createServer().then(async ({ app }) => - app.listen(await getPort({ port: portNumbers(3000, 3100) }), (error) => { - if (error) throw error + app.listen(await getPort({ port: portNumbers(3000, 3100) }), () => { 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 6f9f3f0f5e..4e61620e43 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,17 +9,12 @@ // Additionally, you should also exclude this file 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', @@ -30,6 +25,11 @@ 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,13 +78,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/error': { id: '/error' path: '/error' @@ -99,6 +92,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } '/posts/': { id: '/posts/' path: '/' diff --git a/examples/react/basic-virtual-file-based/package.json b/examples/react/basic-virtual-file-based/package.json index 84d326435c..23e69661ca 100644 --- a/examples/react/basic-virtual-file-based/package.json +++ b/examples/react/basic-virtual-file-based/package.json @@ -10,22 +10,21 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", - "@tanstack/virtual-file-routes": "^1.162.0", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", + "@tanstack/router-plugin": "^1.167.2", + "@tanstack/virtual-file-routes": "^1.161.7", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { "@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" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } 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 6745e373aa..48b85c05e5 100644 --- a/examples/react/basic-virtual-file-based/src/routeTree.gen.ts +++ b/examples/react/basic-virtual-file-based/src/routeTree.gen.ts @@ -8,78 +8,80 @@ // 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 homeRouteImport } from './routes/home' -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 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 ClassicHelloUniverseRouteImport } from './routes/file-based-subtree/hello/universe' -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' +import type { CreateFileRoute, FileRoutesByPath } from '@tanstack/react-router' -const homeRoute = homeRouteImport.update({ - id: '/', - path: '/', +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 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 aRouteImport } from './routes/a' + +const postsPostsRoute = postsPostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) const layoutFirstLayoutRoute = layoutFirstLayoutRouteImport.update({ id: '/_first', getParentRoute: () => rootRouteImport, } as any) -const postsPostsRoute = postsPostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) -const layoutSecondLayoutRoute = layoutSecondLayoutRouteImport.update({ - id: '/_second-layout', - getParentRoute: () => layoutFirstLayoutRoute, -} as any) -const ClassicHelloRouteRoute = ClassicHelloRouteRouteImport.update({ - id: '/classic/hello', - path: '/classic/hello', - getParentRoute: () => rootRouteImport, -} as any) -const postsPostsHomeRoute = postsPostsHomeRouteImport.update({ +const homeRoute = homeRouteImport.update({ id: '/', path: '/', - getParentRoute: () => postsPostsRoute, + 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 ClassicHelloIndexRoute = ClassicHelloIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => ClassicHelloRouteRoute, } as any) -const ClassicHelloUniverseRoute = ClassicHelloUniverseRouteImport.update({ - id: '/universe', - path: '/universe', - getParentRoute: () => ClassicHelloRouteRoute, -} as any) 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, +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, } as any) +const aRoute = aRouteImport.update({ + id: '/route-without-file/layout-a', + path: '/route-without-file/layout-a', + getParentRoute: () => layoutSecondLayoutRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof homeRoute @@ -166,11 +168,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof homeRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof postsPostsRouteImport parentRoute: typeof rootRouteImport } '/_first': { @@ -180,33 +182,12 @@ declare module '@tanstack/react-router' { 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: '/' - preLoaderRoute: typeof layoutSecondLayoutRouteImport - parentRoute: typeof layoutFirstLayoutRoute - } - '/classic/hello': { - id: '/classic/hello' - path: '/classic/hello' - fullPath: '/classic/hello' - preLoaderRoute: typeof ClassicHelloRouteRouteImport - parentRoute: typeof rootRouteImport - } - '/posts/': { - id: '/posts/' + '/': { + id: '/' path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof postsPostsHomeRouteImport - parentRoute: typeof postsPostsRoute + fullPath: '/' + preLoaderRoute: typeof homeRouteImport + parentRoute: typeof rootRouteImport } '/posts/$postId': { id: '/posts/$postId' @@ -215,6 +196,27 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof postsPostsDetailRouteImport parentRoute: typeof postsPostsRoute } + '/_first/_second-layout': { + id: '/_first/_second-layout' + path: '' + 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' + fullPath: '/classic/hello' + preLoaderRoute: typeof ClassicHelloRouteRouteImport + parentRoute: typeof rootRouteImport + } '/classic/hello/': { id: '/classic/hello/' path: '/' @@ -222,13 +224,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ClassicHelloIndexRouteImport parentRoute: typeof ClassicHelloRouteRoute } - '/classic/hello/universe': { - id: '/classic/hello/universe' - path: '/universe' - fullPath: '/classic/hello/universe' - preLoaderRoute: typeof ClassicHelloUniverseRouteImport - parentRoute: typeof ClassicHelloRouteRoute - } '/classic/hello/world': { id: '/classic/hello/world' path: '/world' @@ -236,12 +231,12 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ClassicHelloWorldRouteImport parentRoute: typeof ClassicHelloRouteRoute } - '/_first/_second-layout/route-without-file/layout-a': { - id: '/_first/_second-layout/route-without-file/layout-a' - path: '/route-without-file/layout-a' - fullPath: '/route-without-file/layout-a' - preLoaderRoute: typeof aRouteImport - parentRoute: typeof layoutSecondLayoutRoute + '/classic/hello/universe': { + id: '/classic/hello/universe' + path: '/universe' + fullPath: '/classic/hello/universe' + preLoaderRoute: typeof ClassicHelloUniverseRouteImport + parentRoute: typeof ClassicHelloRouteRoute } '/_first/_second-layout/route-without-file/layout-b': { id: '/_first/_second-layout/route-without-file/layout-b' @@ -250,9 +245,125 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof bRouteImport parentRoute: typeof layoutSecondLayoutRoute } + '/_first/_second-layout/route-without-file/layout-a': { + id: '/_first/_second-layout/route-without-file/layout-a' + path: '/route-without-file/layout-a' + fullPath: '/route-without-file/layout-a' + preLoaderRoute: typeof aRouteImport + 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 74d17276d9..a190b24202 100644 --- a/examples/react/basic-virtual-file-based/src/routes/a.tsx +++ b/examples/react/basic-virtual-file-based/src/routes/a.tsx @@ -1,7 +1,4 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute( - '/_first/_second-layout/route-without-file/layout-a', -)({ +export const Route = createFileRoute({ 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 d9b95f23b4..505f8f6fbf 100644 --- a/examples/react/basic-virtual-file-based/src/routes/b.tsx +++ b/examples/react/basic-virtual-file-based/src/routes/b.tsx @@ -1,7 +1,4 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute( - '/_first/_second-layout/route-without-file/layout-b', -)({ +export const Route = createFileRoute({ 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 0cc76f4a69..f86335e291 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,4 +1,3 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/classic/hello/')({ +export const Route = createFileRoute({ 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 566efc8777..620dd2b76b 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, createFileRoute } from '@tanstack/react-router' +import { Link, Outlet } from '@tanstack/react-router' -export const Route = createFileRoute('/classic/hello')({ +export const Route = createFileRoute({ 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 5aaa7d4fa0..20b07c41cc 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,4 +1,3 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/classic/hello/universe')({ +export const Route = createFileRoute({ 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 790d33a838..4af11357a2 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,4 +1,3 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/classic/hello/world')({ +export const Route = createFileRoute({ 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 0a5b7572ba..b23956ae17 100644 --- a/examples/react/basic-virtual-file-based/src/routes/home.tsx +++ b/examples/react/basic-virtual-file-based/src/routes/home.tsx @@ -1,7 +1,6 @@ -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 d39e206f2d..5c4a461d8d 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, createFileRoute } from '@tanstack/react-router' +import { Outlet } from '@tanstack/react-router' -export const Route = createFileRoute('/_first')({ +export const Route = createFileRoute({ 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 2f56647492..478d9afbec 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, createFileRoute } from '@tanstack/react-router' +import { Link, Outlet } from '@tanstack/react-router' -export const Route = createFileRoute('/_first/_second-layout')({ +export const Route = createFileRoute({ 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 948d52d6d6..654f3cfd18 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, createFileRoute } from '@tanstack/react-router' +import { ErrorComponent } from '@tanstack/react-router' import { fetchPost } from '../../posts' import type { ErrorComponentProps } from '@tanstack/react-router' -export const Route = createFileRoute('/posts/$postId')({ +export const Route = createFileRoute({ 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 c6b65f1892..fdbe5865e5 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,7 +1,6 @@ -import { createFileRoute } from '@tanstack/react-router' import * as React from 'react' -export const Route = createFileRoute('/posts/')({ +export const Route = createFileRoute({ 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 a2ab1ee388..f92c37f537 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, createFileRoute } from '@tanstack/react-router' +import { Link, Outlet } from '@tanstack/react-router' import { fetchPosts } from '../../posts' -export const Route = createFileRoute('/posts')({ +export const Route = createFileRoute({ loader: fetchPosts, component: PostsComponent, }) 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 deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/basic-virtual-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/basic-virtual-file-based/vite.config.ts b/examples/react/basic-virtual-file-based/vite.config.ts index dd4f00f500..c3c3510479 100644 --- a/examples/react/basic-virtual-file-based/vite.config.ts +++ b/examples/react/basic-virtual-file-based/vite.config.ts @@ -10,6 +10,7 @@ export default defineConfig({ tanstackRouter({ target: 'react', autoCodeSplitting: true, + verboseFileRoutes: false, virtualRouteConfig: './routes.ts', }), react(), diff --git a/examples/react/basic-virtual-inside-file-based/package.json b/examples/react/basic-virtual-inside-file-based/package.json index c04cb6012e..e4eb3bfe8c 100644 --- a/examples/react/basic-virtual-inside-file-based/package.json +++ b/examples/react/basic-virtual-inside-file-based/package.json @@ -10,22 +10,21 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", - "@tanstack/virtual-file-routes": "^1.162.0", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", + "@tanstack/router-plugin": "^1.167.2", + "@tanstack/virtual-file-routes": "^1.161.7", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { "@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" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } 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 cda1f85f15..258899f178 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,62 +8,64 @@ // 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 PostsRouteImport } from './routes/posts' -import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' -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 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' +import type { CreateFileRoute, FileRoutesByPath } from '@tanstack/react-router' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +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 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 LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' +import { Route as postsLetsGoDeeperHomeRouteImport } from './routes/posts/lets-go/deeper/home' + +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) const LayoutRoute = LayoutRouteImport.update({ id: '/_layout', getParentRoute: () => rootRouteImport, } as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', 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 PostsDetailsRoute = PostsDetailsRouteImport.update({ - id: '/$postId', - path: '/$postId', +const postsLetsGoIndexRoute = postsLetsGoIndexRouteImport.update({ + id: '/inception/', + path: '/inception/', getParentRoute: () => PostsRoute, } as any) -const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => LayoutLayout2Route, -} as any) const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ id: '/layout-b', path: '/layout-b', getParentRoute: () => LayoutLayout2Route, } as any) -const PostsLetsGoIndexRoute = PostsLetsGoIndexRouteImport.update({ - id: '/inception/', - path: '/inception/', - getParentRoute: () => PostsRoute, +const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => LayoutLayout2Route, } as any) -const PostsLetsGoDeeperHomeRoute = PostsLetsGoDeeperHomeRouteImport.update({ +const postsLetsGoDeeperHomeRoute = postsLetsGoDeeperHomeRouteImport.update({ id: '/inception/deeper/', path: '/inception/deeper/', getParentRoute: () => PostsRoute, @@ -72,34 +74,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 @@ -143,11 +145,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } '/_layout': { @@ -157,13 +159,20 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof LayoutRouteImport parentRoute: typeof rootRouteImport } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof postsDetailsRouteImport + parentRoute: typeof PostsRoute + } '/_layout/_layout-2': { id: '/_layout/_layout-2' path: '' @@ -175,23 +184,16 @@ declare module '@tanstack/react-router' { id: '/posts/' path: '/' fullPath: '/posts/' - preLoaderRoute: typeof PostsHomeRouteImport + preLoaderRoute: typeof postsHomeRouteImport parentRoute: typeof PostsRoute } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsDetailsRouteImport + '/posts/inception/': { + id: '/posts/inception/' + path: '/inception' + fullPath: '/posts/inception/' + preLoaderRoute: typeof postsLetsGoIndexRouteImport parentRoute: typeof PostsRoute } - '/_layout/_layout-2/layout-a': { - id: '/_layout/_layout-2/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof LayoutLayout2LayoutARouteImport - parentRoute: typeof LayoutLayout2Route - } '/_layout/_layout-2/layout-b': { id: '/_layout/_layout-2/layout-b' path: '/layout-b' @@ -199,23 +201,114 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport parentRoute: typeof LayoutLayout2Route } - '/posts/inception/': { - id: '/posts/inception/' - path: '/inception' - fullPath: '/posts/inception/' - preLoaderRoute: typeof PostsLetsGoIndexRouteImport - parentRoute: typeof PostsRoute + '/_layout/_layout-2/layout-a': { + id: '/_layout/_layout-2/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof LayoutLayout2LayoutARouteImport + parentRoute: typeof LayoutLayout2Route } '/posts/inception/deeper/': { id: '/posts/inception/deeper/' path: '/inception/deeper' fullPath: '/posts/inception/deeper/' - preLoaderRoute: typeof PostsLetsGoDeeperHomeRouteImport + 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 @@ -242,17 +335,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 02ddbb1cd9..5c4a461d8d 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, createFileRoute } from '@tanstack/react-router' +import { Outlet } from '@tanstack/react-router' -export const Route = createFileRoute('/_layout')({ +export const Route = createFileRoute({ 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 3b7dbf2903..483b910862 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, createFileRoute } from '@tanstack/react-router' +import { Link, Outlet } from '@tanstack/react-router' -export const Route = createFileRoute('/_layout/_layout-2')({ +export const Route = createFileRoute({ 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 ed2dea8800..a190b24202 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,5 +1,4 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/_layout/_layout-2/layout-a')({ +export const Route = createFileRoute({ 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 4799d403e9..505f8f6fbf 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,5 +1,4 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/_layout/_layout-2/layout-b')({ +export const Route = createFileRoute({ 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 0a5b7572ba..b23956ae17 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,7 +1,6 @@ -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 c7a09ed7f8..4469b2216a 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, createFileRoute } from '@tanstack/react-router' +import { Link, Outlet } from '@tanstack/react-router' import { fetchPosts } from '../posts' -export const Route = createFileRoute('/posts')({ +export const Route = createFileRoute({ 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 6479bdf803..fc10978507 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, createFileRoute } from '@tanstack/react-router' +import { ErrorComponent } from '@tanstack/react-router' import { fetchPost } from '../../posts' import type { ErrorComponentProps } from '@tanstack/react-router' -export const Route = createFileRoute('/posts/$postId')({ +export const Route = createFileRoute({ 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 c6b65f1892..fdbe5865e5 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,7 +1,6 @@ -import { createFileRoute } from '@tanstack/react-router' import * as React from 'react' -export const Route = createFileRoute('/posts/')({ +export const Route = createFileRoute({ 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 d2e95051f6..f8bc76644a 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,4 +1,3 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/posts/inception/deeper/')({ +export const Route = createFileRoute({ 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 1a7358f044..1c7ea68931 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,4 +1,3 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/posts/inception/')({ +export const Route = createFileRoute({ component: () =>
Hello /posts/inception/!
, }) 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 deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/basic-virtual-inside-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// 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 e6a8f48b5f..9630396b91 100644 --- a/examples/react/basic-virtual-inside-file-based/vite.config.ts +++ b/examples/react/basic-virtual-inside-file-based/vite.config.ts @@ -10,6 +10,7 @@ export default defineConfig({ tanstackRouter({ target: 'react', autoCodeSplitting: true, + verboseFileRoutes: false, }), react(), ], diff --git a/examples/react/basic/package.json b/examples/react/basic/package.json index 2c09a3dfdf..fde1186eea 100644 --- a/examples/react/basic/package.json +++ b/examples/react/basic/package.json @@ -10,8 +10,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -21,8 +21,7 @@ "@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" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/react/basic/src/vite-env.d.ts b/examples/react/basic/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/basic/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/deferred-data/package.json b/examples/react/deferred-data/package.json index 99afb661ee..727ea3b0c7 100644 --- a/examples/react/deferred-data/package.json +++ b/examples/react/deferred-data/package.json @@ -10,20 +10,19 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { "@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" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/react/deferred-data/src/vite-env.d.ts b/examples/react/deferred-data/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/deferred-data/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/i18n-paraglide/package.json b/examples/react/i18n-paraglide/package.json index 88140e8911..0df8e3f9e2 100644 --- a/examples/react/i18n-paraglide/package.json +++ b/examples/react/i18n-paraglide/package.json @@ -11,8 +11,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.168.1", + "@tanstack/router-plugin": "^1.167.2", "react": "^19.1.1", "react-dom": "^19.1.1", "tailwindcss": "^4.2.2" @@ -22,20 +22,8 @@ "@types/react": "^19.1.13", "@types/react-dom": "^19.1.9", "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", + "typescript": "^5.9.2", + "vite": "^8.0.0", "@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 12bc916ae4..59499d9fbf 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 IndexRouteImport } from './routes/index' import { Route as AboutRouteImport } from './routes/about' +import { Route as IndexRouteImport } from './routes/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const AboutRoute = AboutRouteImport.update({ id: '/about', path: '/about', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/about': { id: '/about' path: '/about' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AboutRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/react/i18n-paraglide/src/vite-env.d.ts b/examples/react/i18n-paraglide/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/i18n-paraglide/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/i18n-paraglide/tsconfig.json b/examples/react/i18n-paraglide/tsconfig.json index c26f8f774e..fded1fca18 100644 --- a/examples/react/i18n-paraglide/tsconfig.json +++ b/examples/react/i18n-paraglide/tsconfig.json @@ -21,6 +21,7 @@ "noUnusedParameters": true, "noFallthroughCasesInSwitch": true, "noUncheckedSideEffectImports": true, + "baseUrl": ".", "paths": { "@/*": ["./src/*"] } diff --git a/examples/react/kitchen-sink-file-based/package.json b/examples/react/kitchen-sink-file-based/package.json index e02defb3ce..8e2bfebc35 100644 --- a/examples/react/kitchen-sink-file-based/package.json +++ b/examples/react/kitchen-sink-file-based/package.json @@ -10,22 +10,21 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", + "@tanstack/router-plugin": "^1.167.2", "immer": "^10.1.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { "@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" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } 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 03af4e1e58..f3accfa48e 100644 --- a/examples/react/kitchen-sink-file-based/src/routeTree.gen.ts +++ b/examples/react/kitchen-sink-file-based/src/routeTree.gen.ts @@ -8,224 +8,132 @@ // 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 AuthRouteImport } from './routes/_auth' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' -import { Route as DashboardRouteRouteImport } from './routes/dashboard.route' +// Import Routes + +import { Route as rootRoute } from './routes/__root' 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 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 DashboardUsersRouteRouteImport } from './routes/dashboard.users.route' +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 DashboardInvoicesIndexRouteImport } from './routes/dashboard.invoices.index' -import { Route as DashboardInvoicesInvoiceIdRouteImport } from './routes/dashboard.invoices.$invoiceId' +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 thisFolderIsNotInTheUrlRouteGroupRouteImport } from './routes/(this-folder-is-not-in-the-url)/route-group' +import { Route as DashboardUsersRouteRouteImport } from './routes/dashboard.users.route' +import { Route as DashboardInvoicesRouteRouteImport } from './routes/dashboard.invoices.route' import { Route as DashboardUsersIndexRouteImport } from './routes/dashboard.users.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) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', - getParentRoute: () => rootRouteImport, + getParentRoute: () => rootRoute, } 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 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 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, + +const ExpensiveIndexRoute = ExpensiveIndexRouteImport.update({ + id: '/expensive/', + path: '/expensive/', + getParentRoute: () => rootRoute, } as any) + const DashboardIndexRoute = DashboardIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => DashboardRouteRoute, } as any) -const DashboardInvoicesRouteRoute = DashboardInvoicesRouteRouteImport.update({ - id: '/invoices', - path: '/invoices', - getParentRoute: () => DashboardRouteRoute, + +const PathlessLayoutRouteBRoute = PathlessLayoutRouteBRouteImport.update({ + id: '/route-b', + path: '/route-b', + getParentRoute: () => PathlessLayoutRoute, } as any) + +const PathlessLayoutRouteARoute = PathlessLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutRoute, +} as any) + +const AuthProfileRoute = AuthProfileRouteImport.update({ + id: '/profile', + path: '/profile', + getParentRoute: () => AuthRoute, +} as any) + +const thisFolderIsNotInTheUrlRouteGroupRoute = + thisFolderIsNotInTheUrlRouteGroupRouteImport.update({ + id: '/(this-folder-is-not-in-the-url)/route-group', + path: '/route-group', + getParentRoute: () => rootRoute, + } as any) + const DashboardUsersRouteRoute = DashboardUsersRouteRouteImport.update({ id: '/users', path: '/users', getParentRoute: () => DashboardRouteRoute, } as any) -const ExpensiveIndexRoute = ExpensiveIndexRouteImport.update({ - id: '/expensive/', - path: '/expensive/', - getParentRoute: () => rootRouteImport, + +const DashboardInvoicesRouteRoute = DashboardInvoicesRouteRouteImport.update({ + id: '/invoices', + path: '/invoices', + getParentRoute: () => DashboardRouteRoute, } as any) -const DashboardInvoicesIndexRoute = DashboardInvoicesIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => DashboardInvoicesRouteRoute, -} 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 DashboardInvoicesIndexRoute = DashboardInvoicesIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => DashboardInvoicesRouteRoute, +} as any) + const DashboardUsersUserRoute = DashboardUsersUserRouteImport.update({ id: '/user', path: '/user', getParentRoute: () => DashboardUsersRouteRoute, } as any) -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 -} +const DashboardInvoicesInvoiceIdRoute = + DashboardInvoicesInvoiceIdRouteImport.update({ + id: '/$invoiceId', + path: '/$invoiceId', + getParentRoute: () => DashboardInvoicesRouteRoute, + } as any) + +// Populate the FileRoutesByPath interface declare module '@tanstack/react-router' { interface FileRoutesByPath { @@ -234,123 +142,125 @@ declare module '@tanstack/react-router' { path: '/' fullPath: '/' preLoaderRoute: typeof IndexRouteImport - 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 + parentRoute: typeof rootRoute } '/dashboard': { id: '/dashboard' path: '/dashboard' fullPath: '/dashboard' preLoaderRoute: typeof DashboardRouteRouteImport - parentRoute: typeof rootRouteImport + 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 } '/login': { id: '/login' path: '/login' fullPath: '/login' preLoaderRoute: typeof LoginRouteImport - 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 rootRouteImport - } - '/_auth/profile': { - id: '/_auth/profile' - path: '/profile' - fullPath: '/profile' - preLoaderRoute: typeof AuthProfileRouteImport - parentRoute: typeof AuthRoute - } - '/_pathlessLayout/route-a': { - id: '/_pathlessLayout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutRoute - } - '/_pathlessLayout/route-b': { - id: '/_pathlessLayout/route-b' - path: '/route-b' - fullPath: '/route-b' - preLoaderRoute: typeof PathlessLayoutRouteBRouteImport - parentRoute: typeof PathlessLayoutRoute - } - '/dashboard/': { - id: '/dashboard/' - path: '/' - fullPath: '/dashboard/' - preLoaderRoute: typeof DashboardIndexRouteImport - parentRoute: typeof DashboardRouteRoute + parentRoute: typeof rootRoute } '/dashboard/invoices': { id: '/dashboard/invoices' path: '/invoices' fullPath: '/dashboard/invoices' preLoaderRoute: typeof DashboardInvoicesRouteRouteImport - parentRoute: typeof DashboardRouteRoute + parentRoute: typeof DashboardRouteRouteImport } '/dashboard/users': { id: '/dashboard/users' path: '/users' fullPath: '/dashboard/users' preLoaderRoute: typeof DashboardUsersRouteRouteImport - parentRoute: typeof DashboardRouteRoute + parentRoute: typeof DashboardRouteRouteImport + } + '/(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 + } + '/_auth/profile': { + id: '/_auth/profile' + path: '/profile' + fullPath: '/profile' + preLoaderRoute: typeof AuthProfileRouteImport + parentRoute: typeof AuthRouteImport + } + '/_pathlessLayout/route-a': { + id: '/_pathlessLayout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutRouteImport + } + '/_pathlessLayout/route-b': { + id: '/_pathlessLayout/route-b' + path: '/route-b' + fullPath: '/route-b' + preLoaderRoute: typeof PathlessLayoutRouteBRouteImport + parentRoute: typeof PathlessLayoutRouteImport + } + '/dashboard/': { + id: '/dashboard/' + path: '/' + fullPath: '/dashboard/' + preLoaderRoute: typeof DashboardIndexRouteImport + parentRoute: typeof DashboardRouteRouteImport } '/expensive/': { id: '/expensive/' path: '/expensive' - fullPath: '/expensive/' + fullPath: '/expensive' preLoaderRoute: typeof ExpensiveIndexRouteImport - parentRoute: typeof rootRouteImport - } - '/dashboard/invoices/': { - id: '/dashboard/invoices/' - path: '/' - fullPath: '/dashboard/invoices/' - preLoaderRoute: typeof DashboardInvoicesIndexRouteImport - parentRoute: typeof DashboardInvoicesRouteRoute + parentRoute: typeof rootRoute } '/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 DashboardUsersRouteRoute + parentRoute: typeof DashboardInvoicesRouteRouteImport } '/dashboard/users/user': { id: '/dashboard/users/user' path: '/user' fullPath: '/dashboard/users/user' preLoaderRoute: typeof DashboardUsersUserRouteImport - parentRoute: typeof DashboardUsersRouteRoute + parentRoute: typeof DashboardUsersRouteRouteImport + } + '/dashboard/invoices/': { + id: '/dashboard/invoices/' + path: '/' + fullPath: '/dashboard/invoices/' + preLoaderRoute: typeof DashboardInvoicesIndexRouteImport + parentRoute: typeof DashboardInvoicesRouteRouteImport + } + '/dashboard/users/': { + id: '/dashboard/users/' + path: '/' + fullPath: '/dashboard/users/' + preLoaderRoute: typeof DashboardUsersIndexRouteImport + parentRoute: typeof DashboardUsersRouteRouteImport } } } +// Create and export the route tree + interface DashboardInvoicesRouteRouteChildren { DashboardInvoicesInvoiceIdRoute: typeof DashboardInvoicesInvoiceIdRoute DashboardInvoicesIndexRoute: typeof DashboardInvoicesIndexRoute @@ -420,6 +330,128 @@ 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, @@ -430,6 +462,107 @@ const rootRouteChildren: RootRouteChildren = { thisFolderIsNotInTheUrlRouteGroupRoute, ExpensiveIndexRoute: ExpensiveIndexRoute, } -export const routeTree = rootRouteImport + +export const routeTree = rootRoute ._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/vite-env.d.ts b/examples/react/kitchen-sink-file-based/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/kitchen-sink-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/kitchen-sink-react-query-file-based/package.json b/examples/react/kitchen-sink-react-query-file-based/package.json index e3dd032ac2..670a614308 100644 --- a/examples/react/kitchen-sink-react-query-file-based/package.json +++ b/examples/react/kitchen-sink-react-query-file-based/package.json @@ -10,24 +10,23 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.102.0", + "@tanstack/react-query": "^5.90.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", + "@tanstack/router-plugin": "^1.167.2", "immer": "^10.1.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { "@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" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } 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 dbce8cf604..66180a8554 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,65 +9,80 @@ // Additionally, you should also exclude this file 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 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 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 DashboardUsersRouteRouteImport } from './routes/dashboard.users.route' +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 DashboardInvoicesIndexRouteImport } from './routes/dashboard.invoices.index' -import { Route as DashboardInvoicesInvoiceIdRouteImport } from './routes/dashboard.invoices.$invoiceId' +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 DashboardUsersRouteRouteImport } from './routes/dashboard.users.route' +import { Route as DashboardInvoicesRouteRouteImport } from './routes/dashboard.invoices.route' import { Route as DashboardUsersIndexRouteImport } from './routes/dashboard.users.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' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const AuthRoute = AuthRouteImport.update({ - id: '/_auth', +const LoginRoute = LoginRouteImport.update({ + id: '/login', + path: '/login', getParentRoute: () => rootRouteImport, } as any) const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, } as any) +const AuthRoute = AuthRouteImport.update({ + id: '/_auth', + getParentRoute: () => rootRouteImport, +} as any) const DashboardRouteRoute = DashboardRouteRouteImport.update({ id: '/dashboard', path: '/dashboard', getParentRoute: () => rootRouteImport, } as any) -const LoginRoute = LoginRouteImport.update({ - id: '/login', - path: '/login', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const AuthProfileRoute = AuthProfileRouteImport.update({ - id: '/profile', - path: '/profile', - getParentRoute: () => AuthRoute, +const ExpensiveIndexRoute = ExpensiveIndexRouteImport.update({ + id: '/expensive/', + path: '/expensive/', + getParentRoute: () => rootRouteImport, } as any) -const PathlessLayoutRouteARoute = PathlessLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutRoute, +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 DashboardIndexRoute = DashboardIndexRouteImport.update({ - id: '/', - path: '/', +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', getParentRoute: () => DashboardRouteRoute, } as any) const DashboardInvoicesRouteRoute = DashboardInvoicesRouteRouteImport.update({ @@ -75,42 +90,27 @@ const DashboardInvoicesRouteRoute = DashboardInvoicesRouteRouteImport.update({ path: '/invoices', getParentRoute: () => DashboardRouteRoute, } as any) -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, +const DashboardUsersIndexRoute = DashboardUsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => DashboardUsersRouteRoute, } as any) const DashboardInvoicesIndexRoute = DashboardInvoicesIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => DashboardInvoicesRouteRoute, } as any) +const DashboardUsersUserRoute = DashboardUsersUserRouteImport.update({ + id: '/user', + path: '/user', + getParentRoute: () => DashboardUsersRouteRoute, +} as any) const DashboardInvoicesInvoiceIdRoute = DashboardInvoicesInvoiceIdRouteImport.update({ id: '/$invoiceId', path: '/$invoiceId', getParentRoute: () => DashboardInvoicesRouteRoute, } as any) -const DashboardUsersIndexRoute = DashboardUsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => DashboardUsersRouteRoute, -} as any) -const DashboardUsersUserRoute = DashboardUsersUserRouteImport.update({ - id: '/user', - path: '/user', - getParentRoute: () => DashboardUsersRouteRoute, -} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -228,18 +228,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_auth': { - id: '/_auth' - path: '' - fullPath: '/' - preLoaderRoute: typeof AuthRouteImport + '/login': { + id: '/login' + path: '/login' + fullPath: '/login' + preLoaderRoute: typeof LoginRouteImport parentRoute: typeof rootRouteImport } '/_pathlessLayout': { @@ -249,6 +242,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PathlessLayoutRouteImport parentRoute: typeof rootRouteImport } + '/_auth': { + id: '/_auth' + path: '' + fullPath: '/' + preLoaderRoute: typeof AuthRouteImport + parentRoute: typeof rootRouteImport + } '/dashboard': { id: '/dashboard' path: '/dashboard' @@ -256,26 +256,33 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof DashboardRouteRouteImport parentRoute: typeof rootRouteImport } - '/login': { - id: '/login' - path: '/login' - fullPath: '/login' - preLoaderRoute: typeof LoginRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/_auth/profile': { - id: '/_auth/profile' - path: '/profile' - fullPath: '/profile' - preLoaderRoute: typeof AuthProfileRouteImport - parentRoute: typeof AuthRoute + '/expensive/': { + id: '/expensive/' + path: '/expensive' + fullPath: '/expensive/' + preLoaderRoute: typeof ExpensiveIndexRouteImport + parentRoute: typeof rootRouteImport } - '/_pathlessLayout/route-a': { - id: '/_pathlessLayout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutRoute + '/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' @@ -284,11 +291,25 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PathlessLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutRoute } - '/dashboard/': { - id: '/dashboard/' - path: '/' - fullPath: '/dashboard/' - preLoaderRoute: typeof DashboardIndexRouteImport + '/_pathlessLayout/route-a': { + id: '/_pathlessLayout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutRoute + } + '/_auth/profile': { + id: '/_auth/profile' + path: '/profile' + fullPath: '/profile' + preLoaderRoute: typeof AuthProfileRouteImport + parentRoute: typeof AuthRoute + } + '/dashboard/users': { + id: '/dashboard/users' + path: '/users' + fullPath: '/dashboard/users' + preLoaderRoute: typeof DashboardUsersRouteRouteImport parentRoute: typeof DashboardRouteRoute } '/dashboard/invoices': { @@ -298,26 +319,12 @@ declare module '@tanstack/react-router' { 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/' - preLoaderRoute: typeof ExpensiveIndexRouteImport - parentRoute: typeof rootRouteImport - } - '/foo/bar': { - id: '/foo/bar' - path: '/foo/bar' - fullPath: '/foo/bar' - preLoaderRoute: typeof FooBarRouteImport - parentRoute: typeof rootRouteImport + '/dashboard/users/': { + id: '/dashboard/users/' + path: '/' + fullPath: '/dashboard/users/' + preLoaderRoute: typeof DashboardUsersIndexRouteImport + parentRoute: typeof DashboardUsersRouteRoute } '/dashboard/invoices/': { id: '/dashboard/invoices/' @@ -326,20 +333,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof DashboardInvoicesIndexRouteImport 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 DashboardUsersRouteRoute - } '/dashboard/users/user': { id: '/dashboard/users/user' path: '/user' @@ -347,6 +340,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof DashboardUsersUserRouteImport parentRoute: typeof DashboardUsersRouteRoute } + '/dashboard/invoices/$invoiceId': { + id: '/dashboard/invoices/$invoiceId' + path: '/$invoiceId' + fullPath: '/dashboard/invoices/$invoiceId' + preLoaderRoute: typeof DashboardInvoicesInvoiceIdRouteImport + parentRoute: typeof DashboardInvoicesRouteRoute + } } } 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 deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/kitchen-sink-react-query-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/kitchen-sink-react-query/package.json b/examples/react/kitchen-sink-react-query/package.json index 14d0dc8e86..9ec02a1ee7 100644 --- a/examples/react/kitchen-sink-react-query/package.json +++ b/examples/react/kitchen-sink-react-query/package.json @@ -10,23 +10,22 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.102.0", + "@tanstack/react-query": "^5.90.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", "immer": "^10.1.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { "@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" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } 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 deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/kitchen-sink-react-query/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/kitchen-sink/package.json b/examples/react/kitchen-sink/package.json index f738efc37e..771977f2ec 100644 --- a/examples/react/kitchen-sink/package.json +++ b/examples/react/kitchen-sink/package.json @@ -10,21 +10,20 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", "immer": "^10.1.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { "@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" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/react/kitchen-sink/src/vite-env.d.ts b/examples/react/kitchen-sink/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/kitchen-sink/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/large-file-based/package.json b/examples/react/large-file-based/package.json index 23d469d120..4d47abc875 100644 --- a/examples/react/large-file-based/package.json +++ b/examples/react/large-file-based/package.json @@ -12,22 +12,21 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.102.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-query": "^5.90.0", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", + "@tanstack/router-plugin": "^1.167.2", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { "@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" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/react/large-file-based/src/routeTree.gen.ts b/examples/react/large-file-based/src/routeTree.gen.ts index 8494f51d73..93a5be975c 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 IndexRouteImport } from './routes/index' -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 LinkPropsRouteImport } from './routes/linkProps' +import { Route as AbsoluteRouteImport } from './routes/absolute' import { Route as SearchRouteRouteImport } from './routes/search/route' -import { Route as ParamsParamsPlaceholderRouteImport } from './routes/params/$paramsPlaceholder' +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 ParamsParamsPlaceholderRouteImport } from './routes/params/$paramsPlaceholder' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const AbsoluteRoute = AbsoluteRouteImport.update({ - id: '/absolute', - path: '/absolute', +const RelativeRoute = RelativeRouteImport.update({ + id: '/relative', + path: '/relative', getParentRoute: () => rootRouteImport, } as any) const LinkPropsRoute = LinkPropsRouteImport.update({ @@ -33,14 +28,9 @@ const LinkPropsRoute = LinkPropsRouteImport.update({ path: '/linkProps', getParentRoute: () => rootRouteImport, } as any) -const ParamsRouteRoute = ParamsRouteRouteImport.update({ - id: '/params', - path: '/params', - getParentRoute: () => rootRouteImport, -} as any) -const RelativeRoute = RelativeRouteImport.update({ - id: '/relative', - path: '/relative', +const AbsoluteRoute = AbsoluteRouteImport.update({ + id: '/absolute', + path: '/absolute', getParentRoute: () => rootRouteImport, } as any) const SearchRouteRoute = SearchRouteRouteImport.update({ @@ -48,16 +38,26 @@ const SearchRouteRoute = SearchRouteRouteImport.update({ path: '/search', getParentRoute: () => rootRouteImport, } as any) -const ParamsParamsPlaceholderRoute = ParamsParamsPlaceholderRouteImport.update({ - id: '/$paramsPlaceholder', - path: '/$paramsPlaceholder', - getParentRoute: () => ParamsRouteRoute, +const ParamsRouteRoute = ParamsRouteRouteImport.update({ + id: '/params', + path: '/params', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, } as any) const SearchSearchPlaceholderRoute = SearchSearchPlaceholderRouteImport.update({ id: '/searchPlaceholder', path: '/searchPlaceholder', getParentRoute: () => SearchRouteRoute, } as any) +const ParamsParamsPlaceholderRoute = ParamsParamsPlaceholderRouteImport.update({ + id: '/$paramsPlaceholder', + path: '/$paramsPlaceholder', + getParentRoute: () => ParamsRouteRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -134,18 +134,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/absolute': { - id: '/absolute' - path: '/absolute' - fullPath: '/absolute' - preLoaderRoute: typeof AbsoluteRouteImport + '/relative': { + id: '/relative' + path: '/relative' + fullPath: '/relative' + preLoaderRoute: typeof RelativeRouteImport parentRoute: typeof rootRouteImport } '/linkProps': { @@ -155,18 +148,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof LinkPropsRouteImport parentRoute: typeof rootRouteImport } - '/params': { - id: '/params' - path: '/params' - fullPath: '/params' - preLoaderRoute: typeof ParamsRouteRouteImport - parentRoute: typeof rootRouteImport - } - '/relative': { - id: '/relative' - path: '/relative' - fullPath: '/relative' - preLoaderRoute: typeof RelativeRouteImport + '/absolute': { + id: '/absolute' + path: '/absolute' + fullPath: '/absolute' + preLoaderRoute: typeof AbsoluteRouteImport parentRoute: typeof rootRouteImport } '/search': { @@ -176,12 +162,19 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof SearchRouteRouteImport parentRoute: typeof rootRouteImport } - '/params/$paramsPlaceholder': { - id: '/params/$paramsPlaceholder' - path: '/$paramsPlaceholder' - fullPath: '/params/$paramsPlaceholder' - preLoaderRoute: typeof ParamsParamsPlaceholderRouteImport - parentRoute: typeof ParamsRouteRoute + '/params': { + id: '/params' + path: '/params' + fullPath: '/params' + preLoaderRoute: typeof ParamsRouteRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport } '/search/searchPlaceholder': { id: '/search/searchPlaceholder' @@ -190,6 +183,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof SearchSearchPlaceholderRouteImport parentRoute: typeof SearchRouteRoute } + '/params/$paramsPlaceholder': { + id: '/params/$paramsPlaceholder' + path: '/$paramsPlaceholder' + fullPath: '/params/$paramsPlaceholder' + preLoaderRoute: typeof ParamsParamsPlaceholderRouteImport + parentRoute: typeof ParamsRouteRoute + } } } diff --git a/examples/react/large-file-based/src/vite-env.d.ts b/examples/react/large-file-based/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/large-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/location-masking/package.json b/examples/react/location-masking/package.json index fe005c0d2f..12d22f9b74 100644 --- a/examples/react/location-masking/package.json +++ b/examples/react/location-masking/package.json @@ -11,9 +11,9 @@ "dependencies": { "@radix-ui/react-dialog": "^1.1.6", "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.102.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-query": "^5.90.0", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -23,8 +23,7 @@ "@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" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/react/location-masking/src/vite-env.d.ts b/examples/react/location-masking/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/location-masking/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/navigation-blocking/package.json b/examples/react/navigation-blocking/package.json index a7677dfd51..c846dda927 100644 --- a/examples/react/navigation-blocking/package.json +++ b/examples/react/navigation-blocking/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.102.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-query": "^5.90.0", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -22,8 +22,7 @@ "@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" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/react/navigation-blocking/src/vite-env.d.ts b/examples/react/navigation-blocking/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/navigation-blocking/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/quickstart-esbuild-file-based/esbuild.config.js b/examples/react/quickstart-esbuild-file-based/esbuild.config.js index 2f83a79984..fb7950d1fa 100644 --- a/examples/react/quickstart-esbuild-file-based/esbuild.config.js +++ b/examples/react/quickstart-esbuild-file-based/esbuild.config.js @@ -7,5 +7,5 @@ export default { bundle: true, format: 'esm', target: ['esnext'], - plugins: [tanstackRouter({ target: 'react' })], + plugins: [tanstackRouter({ target: 'react', autoCodeSplitting: true })], } diff --git a/examples/react/quickstart-esbuild-file-based/package.json b/examples/react/quickstart-esbuild-file-based/package.json index d855694fec..6e5c4c586f 100644 --- a/examples/react/quickstart-esbuild-file-based/package.json +++ b/examples/react/quickstart-esbuild-file-based/package.json @@ -9,13 +9,13 @@ "start": "dev" }, "dependencies": { - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", + "@tanstack/router-plugin": "^1.167.2", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { "@types/react": "^19.0.8", diff --git a/examples/react/quickstart-file-based/package.json b/examples/react/quickstart-file-based/package.json index 976ec838d1..419bc3deae 100644 --- a/examples/react/quickstart-file-based/package.json +++ b/examples/react/quickstart-file-based/package.json @@ -10,21 +10,20 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", + "@tanstack/router-plugin": "^1.167.2", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { "@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" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/react/quickstart-file-based/src/routeTree.gen.ts b/examples/react/quickstart-file-based/src/routeTree.gen.ts index 12bc916ae4..59499d9fbf 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 IndexRouteImport } from './routes/index' import { Route as AboutRouteImport } from './routes/about' +import { Route as IndexRouteImport } from './routes/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const AboutRoute = AboutRouteImport.update({ id: '/about', path: '/about', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/about': { id: '/about' path: '/about' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AboutRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/react/quickstart-file-based/src/vite-env.d.ts b/examples/react/quickstart-file-based/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/quickstart-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/quickstart-rspack-file-based/package.json b/examples/react/quickstart-rspack-file-based/package.json index 824998f428..3df374e58f 100644 --- a/examples/react/quickstart-rspack-file-based/package.json +++ b/examples/react/quickstart-rspack-file-based/package.json @@ -9,20 +9,19 @@ }, "dependencies": { "@tailwindcss/postcss": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", "postcss": "^8.5.1", "react": "^19.0.0", "react-dom": "^19.0.0", "tailwindcss": "^4.2.2" }, "devDependencies": { - "@rsbuild/core": "^2.3.1", - "@rsbuild/plugin-react": "^2.0.0", - "@tanstack/router-plugin": "^1.169.0", + "@rsbuild/core": "^1.2.4", + "@rsbuild/plugin-react": "^1.1.0", + "@tanstack/router-plugin": "^1.167.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2" + "typescript": "^5.6.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 12bc916ae4..59499d9fbf 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 IndexRouteImport } from './routes/index' import { Route as AboutRouteImport } from './routes/about' +import { Route as IndexRouteImport } from './routes/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const AboutRoute = AboutRouteImport.update({ id: '/about', path: '/about', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/about': { id: '/about' path: '/about' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AboutRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } } } 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 deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/quickstart-rspack-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/quickstart-webpack-file-based/package.json b/examples/react/quickstart-webpack-file-based/package.json index baa14b89dd..e31fae09db 100644 --- a/examples/react/quickstart-webpack-file-based/package.json +++ b/examples/react/quickstart-webpack-file-based/package.json @@ -7,23 +7,21 @@ "build": "webpack build && tsc --noEmit" }, "dependencies": { - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", "react": "^19.0.0", "react-dom": "^19.0.0" }, "devDependencies": { - "@swc/core": "^1.15.33", - "@tanstack/router-plugin": "^1.169.0", + "@swc/core": "^1.10.15", + "@tanstack/router-plugin": "^1.167.2", "@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/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", + "typescript": "^5.7.2", "webpack": "^5.97.1", "webpack-cli": "^5.1.4", - "webpack-dev-server": "^5.2.4" + "webpack-dev-server": "^5.2.0" } } 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 12bc916ae4..59499d9fbf 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 IndexRouteImport } from './routes/index' import { Route as AboutRouteImport } from './routes/about' +import { Route as IndexRouteImport } from './routes/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const AboutRoute = AboutRouteImport.update({ id: '/about', path: '/about', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/about': { id: '/about' path: '/about' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AboutRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + 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 878d2a9735..d83e2bea10 100644 --- a/examples/react/quickstart-webpack-file-based/webpack.config.js +++ b/examples/react/quickstart-webpack-file-based/webpack.config.js @@ -23,11 +23,7 @@ export default ({ WEBPACK_SERVE }) => ({ template: path.resolve(__dirname, './public/index.html'), filename: 'index.html', }), - tanstackRouter({ - target: 'react', - autoCodeSplitting: true, - codeSplittingOptions: { addHmr: Boolean(WEBPACK_SERVE) }, - }), + tanstackRouter({ target: 'react', autoCodeSplitting: true }), ], module: { rules: [ diff --git a/examples/react/quickstart/package.json b/examples/react/quickstart/package.json index b6db476ea8..73fbed591f 100644 --- a/examples/react/quickstart/package.json +++ b/examples/react/quickstart/package.json @@ -10,8 +10,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", "react": "^19.0.0", "react-dom": "^19.0.0", "tailwindcss": "^4.2.2" @@ -20,8 +20,7 @@ "@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" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/react/quickstart/src/vite-env.d.ts b/examples/react/quickstart/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/quickstart/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/router-monorepo-react-query/package.json b/examples/react/router-monorepo-react-query/package.json index b158eeda56..96b75bde91 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.102.0", + "@tanstack/react-query": "^5.90.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", + "@tanstack/router-plugin": "^1.167.2", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1" @@ -23,10 +23,9 @@ "@types/node": "^22.10.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", + "typescript": "^5.7.2", "@vitejs/plugin-react": "^6.0.1", - "vite": "^8.0.14", + "vite": "^8.0.0", "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 f0994165c2..7931f67b5d 100644 --- a/examples/react/router-monorepo-react-query/packages/app/package.json +++ b/examples/react/router-monorepo-react-query/packages/app/package.json @@ -11,19 +11,18 @@ "dependencies": { "@router-mono-react-query/post-feature": "workspace:*", "@router-mono-react-query/router": "workspace:*", - "@tanstack/react-query": "^5.102.0", + "@tanstack/react-query": "^5.90.0", "react": "^19.0.0", "react-dom": "^19.0.0" }, "devDependencies": { - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router-devtools": "^1.166.10", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@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", + "typescript": "^5.7.2", + "vite": "^8.0.0", "vite-plugin-dts": "^4.5.4", "@tailwindcss/vite": "^4.2.2" }, @@ -33,12 +32,6 @@ "dependsOn": [ "^build" ] - }, - "build": { - "inputs": [ - "...", - "{workspaceRoot}/examples/react/router-monorepo-react-query/.gitignore" - ] } } } 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 deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/router-monorepo-react-query/packages/app/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/router-monorepo-react-query/packages/app/tsconfig.json b/examples/react/router-monorepo-react-query/packages/app/tsconfig.json index 196cb055a9..ce3a7d2339 100644 --- a/examples/react/router-monorepo-react-query/packages/app/tsconfig.json +++ b/examples/react/router-monorepo-react-query/packages/app/tsconfig.json @@ -8,6 +8,5 @@ "module": "ESNext", "lib": ["DOM", "DOM.Iterable", "ES2022"], "skipLibCheck": true - }, - "exclude": ["node_modules", "dist"] + } } diff --git a/examples/react/router-monorepo-react-query/packages/post-feature/package.json b/examples/react/router-monorepo-react-query/packages/post-feature/package.json index 7f5e186ab0..edd19337fd 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.102.0", + "@tanstack/react-query": "^5.90.0", "@router-mono-react-query/post-query": "workspace:*", "@router-mono-react-query/router": "workspace:*", "react": "^19.0.0", @@ -18,9 +18,8 @@ "@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", + "typescript": "^5.7.2", + "vite": "^8.0.0", "vite-plugin-dts": "^4.5.4" } } diff --git a/examples/react/router-monorepo-react-query/packages/post-query/package.json b/examples/react/router-monorepo-react-query/packages/post-query/package.json index 98a06051be..a6fad5b810 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,14 +8,13 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "dependencies": { - "@tanstack/react-query": "^5.102.0", + "@tanstack/react-query": "^5.90.0", "redaxios": "^0.5.1", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/react/router-monorepo-react-query/packages/router/package.json b/examples/react/router-monorepo-react-query/packages/router/package.json index 1397db14b5..579c5d3a68 100644 --- a/examples/react/router-monorepo-react-query/packages/router/package.json +++ b/examples/react/router-monorepo-react-query/packages/router/package.json @@ -8,23 +8,22 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "dependencies": { + "@tanstack/history": "^1.161.6", + "@tanstack/react-query": "^5.90.0", + "@tanstack/react-router": "^1.168.1", + "@tanstack/router-plugin": "^1.167.2", "@router-mono-react-query/post-query": "workspace:*", - "@tanstack/history": "^1.162.5", - "@tanstack/react-query": "^5.102.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/router-plugin": "^1.169.0", - "react": "^19.0.0", - "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "zod": "^4.4.3" + "zod": "^3.24.2", + "react": "^19.0.0", + "react-dom": "^19.0.0" }, "devDependencies": { "@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", + "typescript": "^5.7.2", + "vite": "^8.0.0", "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 a4ed448d2f..0820fc5f30 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 IndexRouteImport } from './routes/index' import { Route as PostIdRouteImport } from './routes/$postId' +import { Route as IndexRouteImport } from './routes/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const PostIdRoute = PostIdRouteImport.update({ id: '/$postId', path: '/$postId', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/$postId': { id: '/$postId' path: '/$postId' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostIdRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + 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 aeb605df28..0d04c7789d 100644 --- a/examples/react/router-monorepo-react-query/packages/router/tsconfig.json +++ b/examples/react/router-monorepo-react-query/packages/router/tsconfig.json @@ -7,8 +7,7 @@ "moduleResolution": "Bundler", "module": "ESNext", "lib": ["DOM", "DOM.Iterable", "ES2022"], - "skipLibCheck": true, - "rootDir": "src" + "skipLibCheck": true }, "include": ["src"] } diff --git a/examples/react/router-monorepo-simple-lazy/package.json b/examples/react/router-monorepo-simple-lazy/package.json index e044d86681..8169a94151 100644 --- a/examples/react/router-monorepo-simple-lazy/package.json +++ b/examples/react/router-monorepo-simple-lazy/package.json @@ -8,9 +8,9 @@ "dev": "pnpm router build && pnpm post-feature build && pnpm app dev" }, "dependencies": { - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", + "@tanstack/router-plugin": "^1.167.2", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1" @@ -20,9 +20,8 @@ "@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", + "typescript": "^5.7.2", + "vite": "^8.0.0", "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 cfc7a94942..247246080e 100644 --- a/examples/react/router-monorepo-simple-lazy/packages/app/package.json +++ b/examples/react/router-monorepo-simple-lazy/packages/app/package.json @@ -15,14 +15,13 @@ "react-dom": "^19.0.0" }, "devDependencies": { - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router-devtools": "^1.166.10", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@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", + "typescript": "^5.7.2", + "vite": "^8.0.0", "vite-plugin-dts": "^4.5.4", "@tailwindcss/vite": "^4.2.2" }, @@ -32,12 +31,6 @@ "dependsOn": [ "^build" ] - }, - "build": { - "inputs": [ - "...", - "{workspaceRoot}/examples/react/router-monorepo-simple-lazy/.gitignore" - ] } } } 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 deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/router-monorepo-simple-lazy/packages/app/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/router-monorepo-simple-lazy/packages/app/tsconfig.json b/examples/react/router-monorepo-simple-lazy/packages/app/tsconfig.json index 196cb055a9..ce3a7d2339 100644 --- a/examples/react/router-monorepo-simple-lazy/packages/app/tsconfig.json +++ b/examples/react/router-monorepo-simple-lazy/packages/app/tsconfig.json @@ -8,6 +8,5 @@ "module": "ESNext", "lib": ["DOM", "DOM.Iterable", "ES2022"], "skipLibCheck": true - }, - "exclude": ["node_modules", "dist"] + } } diff --git a/examples/react/router-monorepo-simple-lazy/packages/post-feature/package.json b/examples/react/router-monorepo-simple-lazy/packages/post-feature/package.json index 65738d6025..d6a5967ed8 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.102.0", + "@tanstack/react-query": "^5.90.0", "@router-mono-simple-lazy/router": "workspace:*", "react": "^19.0.0", "react-dom": "^19.0.0" @@ -25,9 +25,8 @@ "@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", + "typescript": "^5.7.2", + "vite": "^8.0.0", "vite-plugin-dts": "^4.5.4" } } diff --git a/examples/react/router-monorepo-simple-lazy/packages/router/package.json b/examples/react/router-monorepo-simple-lazy/packages/router/package.json index afd4702b5d..558a9acf32 100644 --- a/examples/react/router-monorepo-simple-lazy/packages/router/package.json +++ b/examples/react/router-monorepo-simple-lazy/packages/router/package.json @@ -8,21 +8,20 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "dependencies": { - "@tanstack/history": "^1.162.5", - "@tanstack/react-router": "^1.170.46", - "@tanstack/router-plugin": "^1.169.0", - "react": "^19.0.0", - "react-dom": "^19.0.0", + "@tanstack/history": "^1.161.6", + "@tanstack/react-router": "^1.168.1", + "@tanstack/router-plugin": "^1.167.2", "redaxios": "^0.5.1", - "zod": "^4.4.3" + "zod": "^3.24.2", + "react": "^19.0.0", + "react-dom": "^19.0.0" }, "devDependencies": { "@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", + "typescript": "^5.7.2", + "vite": "^8.0.0", "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 a4ed448d2f..0820fc5f30 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 IndexRouteImport } from './routes/index' import { Route as PostIdRouteImport } from './routes/$postId' +import { Route as IndexRouteImport } from './routes/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const PostIdRoute = PostIdRouteImport.update({ id: '/$postId', path: '/$postId', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/$postId': { id: '/$postId' path: '/$postId' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostIdRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + 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 aeb605df28..0d04c7789d 100644 --- a/examples/react/router-monorepo-simple-lazy/packages/router/tsconfig.json +++ b/examples/react/router-monorepo-simple-lazy/packages/router/tsconfig.json @@ -7,8 +7,7 @@ "moduleResolution": "Bundler", "module": "ESNext", "lib": ["DOM", "DOM.Iterable", "ES2022"], - "skipLibCheck": true, - "rootDir": "src" + "skipLibCheck": true }, "include": ["src"] } diff --git a/examples/react/router-monorepo-simple/package.json b/examples/react/router-monorepo-simple/package.json index 800d948c81..e270144314 100644 --- a/examples/react/router-monorepo-simple/package.json +++ b/examples/react/router-monorepo-simple/package.json @@ -8,9 +8,9 @@ "dev": "pnpm router build && pnpm post-feature build && pnpm app dev" }, "dependencies": { - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", + "@tanstack/router-plugin": "^1.167.2", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1" @@ -20,9 +20,8 @@ "@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", + "typescript": "^5.7.2", + "vite": "^8.0.0", "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 a06431ef86..4cd0044f4f 100644 --- a/examples/react/router-monorepo-simple/packages/app/package.json +++ b/examples/react/router-monorepo-simple/packages/app/package.json @@ -15,14 +15,13 @@ "react-dom": "^19.0.0" }, "devDependencies": { - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router-devtools": "^1.166.10", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@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", + "typescript": "^5.7.2", + "vite": "^8.0.0", "vite-plugin-dts": "^4.5.4", "@tailwindcss/vite": "^4.2.2" }, @@ -32,12 +31,6 @@ "dependsOn": [ "^build" ] - }, - "build": { - "inputs": [ - "...", - "{workspaceRoot}/examples/react/router-monorepo-simple/.gitignore" - ] } } } 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 deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/router-monorepo-simple/packages/app/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/router-monorepo-simple/packages/app/tsconfig.json b/examples/react/router-monorepo-simple/packages/app/tsconfig.json index 196cb055a9..ce3a7d2339 100644 --- a/examples/react/router-monorepo-simple/packages/app/tsconfig.json +++ b/examples/react/router-monorepo-simple/packages/app/tsconfig.json @@ -8,6 +8,5 @@ "module": "ESNext", "lib": ["DOM", "DOM.Iterable", "ES2022"], "skipLibCheck": true - }, - "exclude": ["node_modules", "dist"] + } } diff --git a/examples/react/router-monorepo-simple/packages/post-feature/package.json b/examples/react/router-monorepo-simple/packages/post-feature/package.json index 885aa6bbed..ee6280402a 100644 --- a/examples/react/router-monorepo-simple/packages/post-feature/package.json +++ b/examples/react/router-monorepo-simple/packages/post-feature/package.json @@ -16,9 +16,8 @@ "@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", + "typescript": "^5.7.2", + "vite": "^8.0.0", "vite-plugin-dts": "^4.5.4" } } diff --git a/examples/react/router-monorepo-simple/packages/router/package.json b/examples/react/router-monorepo-simple/packages/router/package.json index 391b72e610..d7945424d4 100644 --- a/examples/react/router-monorepo-simple/packages/router/package.json +++ b/examples/react/router-monorepo-simple/packages/router/package.json @@ -8,21 +8,20 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "dependencies": { - "@tanstack/history": "^1.162.5", - "@tanstack/react-router": "^1.170.46", - "@tanstack/router-plugin": "^1.169.0", - "react": "^19.0.0", - "react-dom": "^19.0.0", + "@tanstack/history": "^1.161.6", + "@tanstack/react-router": "^1.168.1", + "@tanstack/router-plugin": "^1.167.2", "redaxios": "^0.5.1", - "zod": "^4.4.3" + "zod": "^3.24.2", + "react": "^19.0.0", + "react-dom": "^19.0.0" }, "devDependencies": { "@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", + "typescript": "^5.7.2", + "vite": "^8.0.0", "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 a4ed448d2f..0820fc5f30 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 IndexRouteImport } from './routes/index' import { Route as PostIdRouteImport } from './routes/$postId' +import { Route as IndexRouteImport } from './routes/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const PostIdRoute = PostIdRouteImport.update({ id: '/$postId', path: '/$postId', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/$postId': { id: '/$postId' path: '/$postId' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostIdRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + 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 aeb605df28..0d04c7789d 100644 --- a/examples/react/router-monorepo-simple/packages/router/tsconfig.json +++ b/examples/react/router-monorepo-simple/packages/router/tsconfig.json @@ -7,8 +7,7 @@ "moduleResolution": "Bundler", "module": "ESNext", "lib": ["DOM", "DOM.Iterable", "ES2022"], - "skipLibCheck": true, - "rootDir": "src" + "skipLibCheck": true }, "include": ["src"] } diff --git a/examples/react/scroll-restoration/package.json b/examples/react/scroll-restoration/package.json index 704ff13838..192475f5d7 100644 --- a/examples/react/scroll-restoration/package.json +++ b/examples/react/scroll-restoration/package.json @@ -10,8 +10,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", "@tanstack/react-virtual": "^3.13.0", "react": "^19.0.0", "react-dom": "^19.0.0", @@ -21,8 +21,7 @@ "@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" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/react/scroll-restoration/src/vite-env.d.ts b/examples/react/scroll-restoration/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/scroll-restoration/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/search-validator-adapters/package.json b/examples/react/search-validator-adapters/package.json index 35e041e825..7685df899e 100644 --- a/examples/react/search-validator-adapters/package.json +++ b/examples/react/search-validator-adapters/package.json @@ -4,20 +4,20 @@ "type": "module", "scripts": { "dev": "vite --port 3000", - "build": "vite build && NODE_OPTIONS=--max-old-space-size=4096 tsc --noEmit", + "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", "test:unit": "vitest" }, "dependencies": { "@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", + "@tanstack/arktype-adapter": "^1.166.9", + "@tanstack/react-query": "^5.90.0", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", + "@tanstack/router-plugin": "^1.167.2", + "@tanstack/valibot-adapter": "^1.166.9", + "@tanstack/zod-adapter": "^1.166.9", "arktype": "^2.1.7", "react": "^19.0.0", "react-dom": "^19.0.0", @@ -26,15 +26,12 @@ "zod": "^3.24.2" }, "devDependencies": { - "@testing-library/jest-dom": "^7.0.1", + "@testing-library/jest-dom": "^6.6.3", "@testing-library/react": "^16.2.0", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@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" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/react/search-validator-adapters/src/routeTree.gen.ts b/examples/react/search-validator-adapters/src/routeTree.gen.ts index d58c1ddfa1..c3d792c411 100644 --- a/examples/react/search-validator-adapters/src/routeTree.gen.ts +++ b/examples/react/search-validator-adapters/src/routeTree.gen.ts @@ -8,20 +8,22 @@ // 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 UsersArktypeIndexRouteImport } from './routes/users/arktype.index' -import { Route as UsersValibotIndexRouteImport } from './routes/users/valibot.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' const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const UsersArktypeIndexRoute = UsersArktypeIndexRouteImport.update({ - id: '/users/arktype/', - path: '/users/arktype/', +const UsersZodIndexRoute = UsersZodIndexRouteImport.update({ + id: '/users/zod/', + path: '/users/zod/', getParentRoute: () => rootRouteImport, } as any) const UsersValibotIndexRoute = UsersValibotIndexRouteImport.update({ @@ -29,9 +31,9 @@ const UsersValibotIndexRoute = UsersValibotIndexRouteImport.update({ path: '/users/valibot/', getParentRoute: () => rootRouteImport, } as any) -const UsersZodIndexRoute = UsersZodIndexRouteImport.update({ - id: '/users/zod/', - path: '/users/zod/', +const UsersArktypeIndexRoute = UsersArktypeIndexRouteImport.update({ + id: '/users/arktype/', + path: '/users/arktype/', getParentRoute: () => rootRouteImport, } as any) @@ -78,11 +80,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport 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 } '/users/valibot/': { @@ -92,16 +94,53 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof UsersValibotIndexRouteImport 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 } } } +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 d0eff7e9f3..e279d9c1e0 100644 --- a/examples/react/search-validator-adapters/src/routes/index.tsx +++ b/examples/react/search-validator-adapters/src/routes/index.tsx @@ -1,4 +1,3 @@ -import { createFileRoute } from '@tanstack/react-router' import * as React from 'react' import { Header } from '../components/Header' @@ -13,6 +12,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 702db7a5d5..38af594c85 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, createFileRoute } from '@tanstack/react-router' +import { useNavigate } 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('/users/arktype/')({ +export const Route = createFileRoute({ 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 8ed997e722..1a8bc7dd18 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, createFileRoute } from '@tanstack/react-router' +import { useNavigate } 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('/users/valibot/')({ +export const Route = createFileRoute({ 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 526509c8d8..8f095d156f 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, createFileRoute } from '@tanstack/react-router' +import { useNavigate } from '@tanstack/react-router' import { fallback, zodValidator } from '@tanstack/zod-adapter' import { z } from 'zod' import { Header } from '../../components/Header' @@ -7,11 +7,6 @@ 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 ?? '', @@ -34,10 +29,10 @@ const Zod = () => { ) } -export const Route = createFileRoute('/users/zod/')({ +export const Route = createFileRoute({ validateSearch: zodValidator( z.object({ - search: fallbackString(z.string(), '').default(''), + search: fallback(z.string().optional(), undefined), }), ), loaderDeps: (opt) => ({ search: opt.search }), diff --git a/examples/react/search-validator-adapters/src/vite-env.d.ts b/examples/react/search-validator-adapters/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/search-validator-adapters/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/search-validator-adapters/tests/arktype.test.tsx b/examples/react/search-validator-adapters/tests/arktype.test.tsx index 776cc8369e..1c3a1baf76 100644 --- a/examples/react/search-validator-adapters/tests/arktype.test.tsx +++ b/examples/react/search-validator-adapters/tests/arktype.test.tsx @@ -8,6 +8,7 @@ import { createRouter, } from '@tanstack/react-router' +import '@testing-library/jest-dom/vitest' import { type } from 'arktype' test('can navigate to the route', async () => { diff --git a/examples/react/search-validator-adapters/tests/jest-dom.setup.ts b/examples/react/search-validator-adapters/tests/jest-dom.setup.ts deleted file mode 100644 index 8f7cbf15be..0000000000 --- a/examples/react/search-validator-adapters/tests/jest-dom.setup.ts +++ /dev/null @@ -1,18 +0,0 @@ -import * as jestDomMatchers from '@testing-library/jest-dom/matchers' -import { expect } from 'vitest' -import type { TestingLibraryMatchers } from '@testing-library/jest-dom/matchers' - -// Workaround for Vitest 5: remove once testing-library/jest-dom#742 is merged -// and released, and go back to `import '@testing-library/jest-dom/vitest'`. -// That entry imports `vitest` from its own install location, which can resolve -// a different Vitest copy than the one running these tests, and its types -// augment Vitest 4's `Assertion` instead of Vitest 5's `Matchers`. -// Keep `jest-dom` in this file name: vite-plugin-solid only skips injecting -// `@testing-library/jest-dom/vitest` when a setup file path contains it. -expect.extend(jestDomMatchers) - -declare module 'vitest' { - // Type parameter names must match Vitest's declaration for the interfaces to merge. - // eslint-disable-next-line @typescript-eslint/naming-convention - interface Matchers extends TestingLibraryMatchers {} -} diff --git a/examples/react/search-validator-adapters/tests/valibot.test.tsx b/examples/react/search-validator-adapters/tests/valibot.test.tsx index d3e18db414..3680d2302c 100644 --- a/examples/react/search-validator-adapters/tests/valibot.test.tsx +++ b/examples/react/search-validator-adapters/tests/valibot.test.tsx @@ -8,6 +8,7 @@ import { createRouter, } from '@tanstack/react-router' import * as v from 'valibot' +import '@testing-library/jest-dom/vitest' test('can navigate to the route', async () => { const rootRoute = createRootRoute() diff --git a/examples/react/search-validator-adapters/vite.config.ts b/examples/react/search-validator-adapters/vite.config.ts index e4b93f5cc3..f4a9fa4f26 100644 --- a/examples/react/search-validator-adapters/vite.config.ts +++ b/examples/react/search-validator-adapters/vite.config.ts @@ -11,13 +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/package.json b/examples/react/start-bare/package.json index 4ab9aff272..dfc301ad60 100644 --- a/examples/react/start-bare/package.json +++ b/examples/react/start-bare/package.json @@ -10,20 +10,19 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", + "@tanstack/react-start": "^1.167.2", "react": "^19.0.0", "react-dom": "^19.0.0", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { "@types/node": "^22.5.4", "@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" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/react/start-bare/src/routeTree.gen.ts b/examples/react/start-bare/src/routeTree.gen.ts index d89758e684..421daf2790 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 IndexRouteImport } from './routes/index' import { Route as AboutRouteImport } from './routes/about' +import { Route as IndexRouteImport } from './routes/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const AboutRoute = AboutRouteImport.update({ id: '/about', path: '/about', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/about': { id: '/about' path: '/about' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AboutRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/react/start-bare/src/router.tsx b/examples/react/start-bare/src/router.tsx index 6f82cbf378..a464233af9 100644 --- a/examples/react/start-bare/src/router.tsx +++ b/examples/react/start-bare/src/router.tsx @@ -5,9 +5,7 @@ export function getRouter() { const router = createRouter({ routeTree, defaultPreload: 'intent', - defaultErrorComponent: (err) => ( -

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

- ), + defaultErrorComponent: (err) =>

{err.error.stack}

, defaultNotFoundComponent: () =>

not found

, scrollRestoration: true, }) diff --git a/examples/react/start-bare/tsconfig.json b/examples/react/start-bare/tsconfig.json index af81492efb..b3a2d67dfa 100644 --- a/examples/react/start-bare/tsconfig.json +++ b/examples/react/start-bare/tsconfig.json @@ -13,6 +13,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/react/start-basic-auth/README.md b/examples/react/start-basic-auth/README.md index 7f1b093ba5..4e5ee29b40 100644 --- a/examples/react/start-basic-auth/README.md +++ b/examples/react/start-basic-auth/README.md @@ -39,13 +39,3 @@ This example demonstrates: - Protected routes - Login/logout functionality - Redirect after authentication - -## Session configuration - -This example uses [iron-session](https://github.com/vvo/iron-session) through Start's `getCookie` and `setCookie` helpers. Set `SESSION_PASSWORD` to a random secret of at least 32 characters before starting the app, for example: - -```sh -export SESSION_PASSWORD="$(openssl rand -base64 32)" -``` - -Keep the same secret across instances and deployments that must read the same sessions. The cookie requires HTTPS in production. Each handler reads its own session, then awaits `session.save()` before redirecting or returning. diff --git a/examples/react/start-basic-auth/package.json b/examples/react/start-basic-auth/package.json index 9ab89bdac9..09bab58fef 100644 --- a/examples/react/start-basic-auth/package.json +++ b/examples/react/start-basic-auth/package.json @@ -14,14 +14,13 @@ "@libsql/client": "^0.15.15", "@prisma/adapter-libsql": "^7.0.0", "@prisma/client": "^7.0.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", - "iron-session": "^9.0.1", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", + "@tanstack/react-start": "^1.167.2", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwind-merge": "^3.6.0" + "tailwind-merge": "^2.6.0" }, "devDependencies": { "@tailwindcss/vite": "^4.2.2", @@ -32,8 +31,7 @@ "dotenv": "^17.2.3", "prisma": "^7.0.0", "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/react/start-basic-auth/src/components/DefaultCatchBoundary.tsx b/examples/react/start-basic-auth/src/components/DefaultCatchBoundary.tsx index 405fb5f4a7..ef2daa1ea1 100644 --- a/examples/react/start-basic-auth/src/components/DefaultCatchBoundary.tsx +++ b/examples/react/start-basic-auth/src/components/DefaultCatchBoundary.tsx @@ -1,15 +1,17 @@ import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, 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 === '/', + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, }) console.error(error) diff --git a/examples/react/start-basic-auth/src/routeTree.gen.ts b/examples/react/start-basic-auth/src/routeTree.gen.ts index a74e753aec..389f656645 100644 --- a/examples/react/start-basic-auth/src/routeTree.gen.ts +++ b/examples/react/start-basic-auth/src/routeTree.gen.ts @@ -9,27 +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 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 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 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 IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const AuthedRoute = AuthedRouteImport.update({ - id: '/_authed', - getParentRoute: () => rootRouteImport, -} as any) -const LoginRoute = LoginRouteImport.update({ - id: '/login', - path: '/login', +const SignupRoute = SignupRouteImport.update({ + id: '/signup', + path: '/signup', getParentRoute: () => rootRouteImport, } as any) const LogoutRoute = LogoutRouteImport.update({ @@ -37,9 +28,18 @@ const LogoutRoute = LogoutRouteImport.update({ path: '/logout', getParentRoute: () => rootRouteImport, } as any) -const SignupRoute = SignupRouteImport.update({ - id: '/signup', - path: '/signup', +const LoginRoute = LoginRouteImport.update({ + id: '/login', + path: '/login', + getParentRoute: () => rootRouteImport, +} as any) +const AuthedRoute = AuthedRouteImport.update({ + id: '/_authed', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AuthedPostsRouteRoute = AuthedPostsRouteRouteImport.update({ @@ -120,25 +120,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_authed': { - id: '/_authed' - path: '' - fullPath: '/' - preLoaderRoute: typeof AuthedRouteImport - parentRoute: typeof rootRouteImport - } - '/login': { - id: '/login' - path: '/login' - fullPath: '/login' - preLoaderRoute: typeof LoginRouteImport + '/signup': { + id: '/signup' + path: '/signup' + fullPath: '/signup' + preLoaderRoute: typeof SignupRouteImport parentRoute: typeof rootRouteImport } '/logout': { @@ -148,11 +134,25 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof LogoutRouteImport parentRoute: typeof rootRouteImport } - '/signup': { - id: '/signup' - path: '/signup' - fullPath: '/signup' - preLoaderRoute: typeof SignupRouteImport + '/login': { + id: '/login' + path: '/login' + fullPath: '/login' + preLoaderRoute: typeof LoginRouteImport + parentRoute: typeof rootRouteImport + } + '/_authed': { + id: '/_authed' + path: '' + fullPath: '/' + preLoaderRoute: typeof AuthedRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport 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 3367c62f27..5728345fcf 100644 --- a/examples/react/start-basic-auth/src/routes/__root.tsx +++ b/examples/react/start-basic-auth/src/routes/__root.tsx @@ -13,18 +13,18 @@ import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary.js' import { NotFound } from '~/components/NotFound.js' import appCss from '~/styles/app.css?url' import { seo } from '~/utils/seo.js' -import { getAppSession } from '~/utils/session.js' +import { useAppSession } from '~/utils/session.js' const fetchUser = createServerFn({ method: 'GET' }).handler(async () => { // We need to auth on the server so we have access to secure cookies - const session = await getAppSession() + const session = await useAppSession() - if (!session.userEmail) { + if (!session.data.userEmail) { return null } return { - email: session.userEmail, + email: session.data.userEmail, } }) diff --git a/examples/react/start-basic-auth/src/routes/_authed.tsx b/examples/react/start-basic-auth/src/routes/_authed.tsx index 0b5c6f9047..230be64c62 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 { getAppSession } from '~/utils/session' +import { useAppSession } from '~/utils/session' export const loginFn = createServerFn({ method: 'POST' }) - .validator((d: { email: string; password: string }) => d) + .inputValidator((d: { email: string; password: string }) => d) .handler(async ({ data }) => { // Find the user const user = await prismaClient.user.findUnique({ @@ -33,10 +33,13 @@ export const loginFn = createServerFn({ method: 'POST' }) } } + // Create a session + const session = await useAppSession() + // Store the user's email in the session - const session = await getAppSession() - session.userEmail = user.email - await session.save() + await session.update({ + userEmail: user.email, + }) }) export const Route = createFileRoute('/_authed')({ @@ -46,7 +49,7 @@ export const Route = createFileRoute('/_authed')({ } }, errorComponent: ({ error }) => { - if (error instanceof Error && error.message === 'Not authenticated') { + if (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 73cdaf1600..28f3c9f8fe 100644 --- a/examples/react/start-basic-auth/src/routes/logout.tsx +++ b/examples/react/start-basic-auth/src/routes/logout.tsx @@ -1,10 +1,11 @@ import { redirect, createFileRoute } from '@tanstack/react-router' import { createServerFn } from '@tanstack/react-start' -import { getAppSession } from '~/utils/session' +import { useAppSession } from '~/utils/session' const logoutFn = createServerFn().handler(async () => { - const session = await getAppSession() - session.destroy() + const session = await useAppSession() + + session.clear() throw redirect({ href: '/', diff --git a/examples/react/start-basic-auth/src/routes/signup.tsx b/examples/react/start-basic-auth/src/routes/signup.tsx index 4dc8e350ac..7b64265840 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 { getAppSession } from '~/utils/session' +import { useAppSession } from '~/utils/session' export const signupFn = createServerFn({ method: 'POST' }) - .validator( + .inputValidator( (d: { email: string; password: string; redirectUrl?: string }) => d, ) .handler(async ({ data }) => { @@ -20,6 +20,9 @@ export const signupFn = createServerFn({ method: 'POST' }) // Encrypt the password using Sha256 into plaintext const password = await hashPassword(data.password) + // Create a session + const session = await useAppSession() + if (found) { if (found.password !== password) { return { @@ -30,9 +33,9 @@ export const signupFn = createServerFn({ method: 'POST' }) } // Store the user's email in the session - const session = await getAppSession() - session.userEmail = found.email - await session.save() + await session.update({ + userEmail: found.email, + }) // Redirect to the prev page stored in the "redirect" search param throw redirect({ @@ -49,9 +52,9 @@ export const signupFn = createServerFn({ method: 'POST' }) }) // Store the user's email in the session - const session = await getAppSession() - session.userEmail = user.email - await session.save() + await session.update({ + userEmail: user.email, + }) // Redirect to the prev page stored in the "redirect" search param throw redirect({ diff --git a/examples/react/start-basic-auth/src/utils/posts.ts b/examples/react/start-basic-auth/src/utils/posts.ts index a7e0e99cfa..fbcc43c34b 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' }) - .validator((postId: string) => postId) + .inputValidator((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 7df7bc4da2..c38bac1e48 100644 --- a/examples/react/start-basic-auth/src/utils/session.ts +++ b/examples/react/start-basic-auth/src/utils/session.ts @@ -1,29 +1,13 @@ -import { getIronSession } from 'iron-session' -import { getCookie, setCookie } from '@tanstack/react-start/server' +// src/services/session.server.ts +import { useSession } from '@tanstack/react-start/server' import type { User } from '@prisma/client' type SessionUser = { userEmail: User['email'] } -export function getAppSession() { - const password = process.env.SESSION_PASSWORD - if (!password || password.length < 32) { - throw new Error('Set SESSION_PASSWORD to at least 32 characters') - } - - return getIronSession( - { read: getCookie, write: setCookie }, - { - cookieName: 'app-session', - password, - ttl: 7 * 24 * 60 * 60, - cookieOptions: { - httpOnly: true, - sameSite: 'lax', - secure: process.env.NODE_ENV === 'production', - path: '/', - }, - }, - ) +export function useAppSession() { + return useSession({ + password: 'ChangeThisBeforeShippingToProdOrYouWillBeFired', + }) } diff --git a/examples/react/start-basic-auth/tsconfig.json b/examples/react/start-basic-auth/tsconfig.json index cef9369516..3a9fb7cd71 100644 --- a/examples/react/start-basic-auth/tsconfig.json +++ b/examples/react/start-basic-auth/tsconfig.json @@ -13,6 +13,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/react/start-basic-authjs/package.json b/examples/react/start-basic-authjs/package.json index e9fa789ea6..dc315cf2b6 100644 --- a/examples/react/start-basic-authjs/package.json +++ b/examples/react/start-basic-authjs/package.json @@ -11,23 +11,22 @@ }, "dependencies": { "@auth/core": "^0.41.1", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", + "@tanstack/react-start": "^1.167.2", + "start-authjs": "^1.0.0", "react": "^19.0.0", "react-dom": "^19.0.0", - "start-authjs": "^1.0.0", - "tailwind-merge": "^3.6.0" + "tailwind-merge": "^2.6.0" }, "devDependencies": { "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.4", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@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" + "typescript": "^5.7.2", + "vite": "^8.0.0", + "@vitejs/plugin-react": "^6.0.1" } } diff --git a/examples/react/start-basic-authjs/src/components/DefaultCatchBoundary.tsx b/examples/react/start-basic-authjs/src/components/DefaultCatchBoundary.tsx index 4a22649ed4..260c2ea41f 100644 --- a/examples/react/start-basic-authjs/src/components/DefaultCatchBoundary.tsx +++ b/examples/react/start-basic-authjs/src/components/DefaultCatchBoundary.tsx @@ -1,15 +1,17 @@ import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, 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 === '/', + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, }) 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 4abcbc8048..2f59e4ba33 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 IndexRouteImport } from './routes/index' -import { Route as LoginRouteImport } from './routes/login' import { Route as ProtectedRouteImport } from './routes/protected' +import { Route as LoginRouteImport } from './routes/login' +import { Route as IndexRouteImport } from './routes/index' import { Route as ApiAuthSplatRouteImport } from './routes/api/auth/$' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const ProtectedRoute = ProtectedRouteImport.update({ + id: '/protected', + path: '/protected', getParentRoute: () => rootRouteImport, } as any) const LoginRoute = LoginRouteImport.update({ @@ -24,9 +24,9 @@ const LoginRoute = LoginRouteImport.update({ path: '/login', getParentRoute: () => rootRouteImport, } as any) -const ProtectedRoute = ProtectedRouteImport.update({ - id: '/protected', - path: '/protected', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const ApiAuthSplatRoute = ApiAuthSplatRouteImport.update({ @@ -71,11 +71,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/protected': { + id: '/protected' + path: '/protected' + fullPath: '/protected' + preLoaderRoute: typeof ProtectedRouteImport parentRoute: typeof rootRouteImport } '/login': { @@ -85,11 +85,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof LoginRouteImport parentRoute: typeof rootRouteImport } - '/protected': { - id: '/protected' - path: '/protected' - fullPath: '/protected' - preLoaderRoute: typeof ProtectedRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/api/auth/$': { diff --git a/examples/react/start-basic-authjs/tsconfig.json b/examples/react/start-basic-authjs/tsconfig.json index ff21ac7cfa..70cbbc5ce3 100644 --- a/examples/react/start-basic-authjs/tsconfig.json +++ b/examples/react/start-basic-authjs/tsconfig.json @@ -15,6 +15,7 @@ "noUnusedParameters": true, "noFallthroughCasesInSwitch": true, "allowSyntheticDefaultImports": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] } diff --git a/examples/react/start-basic-cloudflare/package.json b/examples/react/start-basic-cloudflare/package.json index 2108922446..9ac6f300e5 100644 --- a/examples/react/start-basic-cloudflare/package.json +++ b/examples/react/start-basic-cloudflare/package.json @@ -9,12 +9,12 @@ "preview": "vite preview", "deploy": "npm run build && wrangler deploy", "cf-typegen": "wrangler types", - "postinstall": "WRANGLER_LOG=warn npm run --silent cf-typegen" + "postinstall": "npm run cf-typegen" }, "dependencies": { - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", + "@tanstack/react-start": "^1.167.2", "react": "^19.0.0", "react-dom": "^19.0.0" }, @@ -26,9 +26,8 @@ "@types/react-dom": "^19.0.3", "@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", + "typescript": "^5.7.2", + "vite": "^8.0.0", "wrangler": "^4.74.0" } } diff --git a/examples/react/start-basic-cloudflare/src/components/DefaultCatchBoundary.tsx b/examples/react/start-basic-cloudflare/src/components/DefaultCatchBoundary.tsx index 4a22649ed4..260c2ea41f 100644 --- a/examples/react/start-basic-cloudflare/src/components/DefaultCatchBoundary.tsx +++ b/examples/react/start-basic-cloudflare/src/components/DefaultCatchBoundary.tsx @@ -1,15 +1,17 @@ import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, 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 === '/', + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, }) 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 57b849492d..0bd698a666 100644 --- a/examples/react/start-basic-cloudflare/src/routeTree.gen.ts +++ b/examples/react/start-basic-cloudflare/src/routeTree.gen.ts @@ -9,46 +9,27 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as 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 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 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 PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as ApiUsersRouteImport } from './routes/api/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 PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' -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', +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', getParentRoute: () => rootRouteImport, } as any) const RedirectRoute = RedirectRouteImport.update({ @@ -56,9 +37,53 @@ const RedirectRoute = RedirectRouteImport.update({ path: '/redirect', getParentRoute: () => rootRouteImport, } as any) -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', + getParentRoute: () => rootRouteImport, +} as any) +const DeferredRoute = DeferredRouteImport.update({ + id: '/deferred', + path: '/deferred', + getParentRoute: () => rootRouteImport, +} as any) +const CustomScriptDotjsRoute = CustomScriptDotjsRouteImport.update({ + id: '/customScript.js', + path: '/customScript.js', + 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 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', getParentRoute: () => rootRouteImport, } as any) const PathlessLayoutNestedLayoutRoute = @@ -66,53 +91,28 @@ const PathlessLayoutNestedLayoutRoute = id: '/_nested-layout', getParentRoute: () => PathlessLayoutRoute, } as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', 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({ +const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ id: '/$userId', path: '/$userId', - getParentRoute: () => UsersRoute, + getParentRoute: () => ApiUsersRoute, } 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) +const PathlessLayoutNestedLayoutRouteARoute = + PathlessLayoutNestedLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + } as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -234,39 +234,11 @@ export interface RootRouteChildren { 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 + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport parentRoute: typeof rootRouteImport } '/redirect': { @@ -276,11 +248,74 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof RedirectRouteImport parentRoute: typeof rootRouteImport } - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport + parentRoute: typeof rootRouteImport + } + '/customScript.js': { + id: '/customScript.js' + path: '/customScript.js' + fullPath: '/customScript.js' + preLoaderRoute: typeof CustomScriptDotjsRouteImport + parentRoute: typeof rootRouteImport + } + '/_pathlessLayout': { + id: '/_pathlessLayout' + 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 + } + '/api/users': { + id: '/api/users' + path: '/api/users' + fullPath: '/api/users' + preLoaderRoute: typeof ApiUsersRouteImport parentRoute: typeof rootRouteImport } '/_pathlessLayout/_nested-layout': { @@ -290,55 +325,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport parentRoute: typeof PathlessLayoutRoute } - '/api/users': { - id: '/api/users' - path: '/api/users' - fullPath: '/api/users' - preLoaderRoute: typeof ApiUsersRouteImport + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport parentRoute: typeof rootRouteImport } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute - } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute - } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRoute - } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } - '/_pathlessLayout/_nested-layout/route-b': { - id: '/_pathlessLayout/_nested-layout/route-b' - path: '/route-b' - fullPath: '/route-b' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } '/api/users/$userId': { id: '/api/users/$userId' path: '/$userId' @@ -346,12 +339,19 @@ declare module '@tanstack/react-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 + '/_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 } } } diff --git a/examples/react/start-basic-cloudflare/src/routes/deferred.tsx b/examples/react/start-basic-cloudflare/src/routes/deferred.tsx index f3e09d1d4e..c38808243e 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' }) - .validator((d: string) => d) + .inputValidator((d: string) => d) .handler(({ data: name }) => { return { name, randomNumber: Math.floor(Math.random() * 100) } }) const slowServerFn = createServerFn({ method: 'GET' }) - .validator((d: string) => d) + .inputValidator((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/users.$userId.tsx b/examples/react/start-basic-cloudflare/src/routes/users.$userId.tsx index fe22eb86c3..212e83d8fe 100644 --- a/examples/react/start-basic-cloudflare/src/routes/users.$userId.tsx +++ b/examples/react/start-basic-cloudflare/src/routes/users.$userId.tsx @@ -1,6 +1,6 @@ import { createFileRoute } from '@tanstack/react-router' -import { NotFound } from '../components/NotFound' -import { UserErrorComponent } from '../components/UserError' +import { NotFound } from 'src/components/NotFound' +import { UserErrorComponent } from 'src/components/UserError' import type { User } from '~/utils/users' export const Route = createFileRoute('/users/$userId')({ diff --git a/examples/react/start-basic-cloudflare/src/utils/posts.tsx b/examples/react/start-basic-cloudflare/src/utils/posts.tsx index ea7dd0a721..098542fd74 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' }) - .validator((d: string) => d) + .inputValidator((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 cef9369516..3a9fb7cd71 100644 --- a/examples/react/start-basic-cloudflare/tsconfig.json +++ b/examples/react/start-basic-cloudflare/tsconfig.json @@ -13,6 +13,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/react/start-basic-react-query/README.md b/examples/react/start-basic-react-query/README.md index 70cc728ae4..77c61c2504 100644 --- a/examples/react/start-basic-react-query/README.md +++ b/examples/react/start-basic-react-query/README.md @@ -38,18 +38,5 @@ This example demonstrates how to use TanStack Query with TanStack Start for: - Server-side data fetching - Client-side caching and synchronization -- 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. +- Optimistic updates +- Automatic refetching diff --git a/examples/react/start-basic-react-query/package.json b/examples/react/start-basic-react-query/package.json index 9d819d4390..3b78a551f3 100644 --- a/examples/react/start-basic-react-query/package.json +++ b/examples/react/start-basic-react-query/package.json @@ -7,20 +7,19 @@ "dev": "vite dev", "build": "vite build && tsc --noEmit", "preview": "vite preview", - "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test" + "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/react-query": "^5.102.0", + "@tanstack/react-query": "^5.90.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-router-ssr-query": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", + "@tanstack/react-router-ssr-query": "^1.166.10", + "@tanstack/react-start": "^1.167.2", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwind-merge": "^3.6.0" + "tailwind-merge": "^2.6.0" }, "devDependencies": { "@tailwindcss/vite": "^4.2.2", @@ -29,9 +28,7 @@ "@types/react-dom": "^19.0.3", "@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" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/react/start-basic-react-query/playwright.config.ts b/examples/react/start-basic-react-query/playwright.config.ts deleted file mode 100644 index 298a1133e9..0000000000 --- a/examples/react/start-basic-react-query/playwright.config.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { defineConfig } from '@playwright/test' - -export default defineConfig({ - testDir: './tests', - use: { baseURL: 'http://localhost:3110', browserName: 'chromium' }, - webServer: { - command: - process.env.QUERY_EXAMPLE_PRODUCTION === '1' - ? 'PORT=3110 pnpm start' - : 'pnpm dev --port 3110', - url: 'http://localhost:3110/preferences', - timeout: 120_000, - }, -}) diff --git a/examples/react/start-basic-react-query/src/components/DefaultCatchBoundary.tsx b/examples/react/start-basic-react-query/src/components/DefaultCatchBoundary.tsx index 405fb5f4a7..ef2daa1ea1 100644 --- a/examples/react/start-basic-react-query/src/components/DefaultCatchBoundary.tsx +++ b/examples/react/start-basic-react-query/src/components/DefaultCatchBoundary.tsx @@ -1,15 +1,17 @@ import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, 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 === '/', + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, }) 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 0c7a90d4a1..a3a4ddf49f 100644 --- a/examples/react/start-basic-react-query/src/routeTree.gen.ts +++ b/examples/react/start-basic-react-query/src/routeTree.gen.ts @@ -9,31 +9,26 @@ // Additionally, you should also exclude this file 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 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 DeferredRouteImport } from './routes/deferred' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as UsersRouteRouteImport } from './routes/users.route' -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 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 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 PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as ApiUsersRouteImport } from './routes/api/users' +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 PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', +const RedirectRoute = RedirectRouteImport.update({ + id: '/redirect', + path: '/redirect', getParentRoute: () => rootRouteImport, } as any) const DeferredRoute = DeferredRouteImport.update({ @@ -41,19 +36,8 @@ const DeferredRoute = DeferredRouteImport.update({ path: '/deferred', getParentRoute: () => rootRouteImport, } as any) -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', +const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ + id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, } as any) const UsersRouteRoute = UsersRouteRouteImport.update({ @@ -61,65 +45,74 @@ const UsersRouteRoute = UsersRouteRouteImport.update({ 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', +const PostsRouteRoute = PostsRouteRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ +const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', - getParentRoute: () => PostsRouteRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRouteRoute, + 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 PathlessLayoutNestedLayoutRouteARoute = - PathlessLayoutNestedLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRouteRoute, +} as any) +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/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, +} 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 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 PathlessLayoutNestedLayoutRouteARoute = + PathlessLayoutNestedLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + } 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 @@ -134,7 +127,6 @@ 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 @@ -153,7 +145,6 @@ 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 @@ -173,7 +164,6 @@ export interface FileRouteTypes { | '/posts' | '/users' | '/deferred' - | '/preferences' | '/redirect' | '/api/users' | '/posts/$postId' @@ -188,7 +178,6 @@ export interface FileRouteTypes { to: | '/' | '/deferred' - | '/preferences' | '/redirect' | '/api/users' | '/posts/$postId' @@ -206,7 +195,6 @@ export interface FileRouteTypes { | '/users' | '/_pathlessLayout' | '/deferred' - | '/preferences' | '/redirect' | '/_pathlessLayout/_nested-layout' | '/api/users' @@ -226,7 +214,6 @@ export interface RootRouteChildren { UsersRouteRoute: typeof UsersRouteRouteWithChildren PathlessLayoutRoute: typeof PathlessLayoutRouteWithChildren DeferredRoute: typeof DeferredRoute - PreferencesRoute: typeof PreferencesRoute RedirectRoute: typeof RedirectRoute ApiUsersRoute: typeof ApiUsersRouteWithChildren PostsPostIdDeepRoute: typeof PostsPostIdDeepRoute @@ -234,18 +221,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_pathlessLayout': { - id: '/_pathlessLayout' - path: '' - fullPath: '/' - preLoaderRoute: typeof PathlessLayoutRouteImport + '/redirect': { + id: '/redirect' + path: '/redirect' + fullPath: '/redirect' + preLoaderRoute: typeof RedirectRouteImport parentRoute: typeof rootRouteImport } '/deferred': { @@ -255,25 +235,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof DeferredRouteImport parentRoute: typeof rootRouteImport } - '/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 + '/_pathlessLayout': { + id: '/_pathlessLayout' + path: '' + fullPath: '/' + preLoaderRoute: typeof PathlessLayoutRouteImport parentRoute: typeof rootRouteImport } '/users': { @@ -283,33 +249,19 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof UsersRouteRouteImport 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 + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } - '/posts/': { - id: '/posts/' + '/': { + id: '/' path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRouteRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRouteRoute + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport } '/users/': { id: '/users/' @@ -318,6 +270,13 @@ declare module '@tanstack/react-router' { 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' @@ -325,19 +284,33 @@ declare module '@tanstack/react-router' { 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 + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRouteRoute } - '/_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': { + id: '/api/users' + path: '/api/users' + fullPath: '/api/users' + preLoaderRoute: typeof ApiUsersRouteImport + parentRoute: typeof rootRouteImport + } + '/_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 } '/api/users/$id': { id: '/api/users/$id' @@ -346,12 +319,19 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ApiUsersIdRouteImport parentRoute: typeof ApiUsersRoute } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport - parentRoute: typeof rootRouteImport + '/_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 } } } @@ -432,7 +412,6 @@ const rootRouteChildren: RootRouteChildren = { UsersRouteRoute: UsersRouteRouteWithChildren, PathlessLayoutRoute: PathlessLayoutRouteWithChildren, DeferredRoute: DeferredRoute, - PreferencesRoute: PreferencesRoute, RedirectRoute: RedirectRoute, ApiUsersRoute: ApiUsersRouteWithChildren, PostsPostIdDeepRoute: PostsPostIdDeepRoute, @@ -442,11 +421,10 @@ export const routeTree = rootRouteImport ._addFileTypes() import type { getRouter } from './router.tsx' -import type { startInstance } from './start.ts' +import type { createStart } from '@tanstack/react-start' 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 345055c116..314b29edd0 100644 --- a/examples/react/start-basic-react-query/src/router.tsx +++ b/examples/react/start-basic-react-query/src/router.tsx @@ -6,15 +6,12 @@ import { DefaultCatchBoundary } from './components/DefaultCatchBoundary' import { NotFound } from './components/NotFound' export function getRouter() { - const queryClient = new QueryClient({ - defaultOptions: { queries: { staleTime: 30_000 } }, - }) + const queryClient = new QueryClient() 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 71c19b2c6f..bc278f8036 100644 --- a/examples/react/start-basic-react-query/src/routes/__root.tsx +++ b/examples/react/start-basic-react-query/src/routes/__root.tsx @@ -83,7 +83,6 @@ function RootDocument({ children }: { children: React.ReactNode }) {
- Preferences diff --git a/examples/react/start-basic-react-query/src/routes/preferences.tsx b/examples/react/start-basic-react-query/src/routes/preferences.tsx deleted file mode 100644 index 603257fc0f..0000000000 --- a/examples/react/start-basic-react-query/src/routes/preferences.tsx +++ /dev/null @@ -1,68 +0,0 @@ -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 deleted file mode 100644 index 5fb1e247fb..0000000000 --- a/examples/react/start-basic-react-query/src/start.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { createCsrfMiddleware, createStart } from '@tanstack/react-start' - -export const startInstance = createStart(() => ({ - requestMiddleware: [ - createCsrfMiddleware({ - filter: (ctx) => ctx.handlerType === 'serverFn', - }), - ], -})) diff --git a/examples/react/start-basic-react-query/src/utils/posts.tsx b/examples/react/start-basic-react-query/src/utils/posts.tsx index dc6979005e..a95e9dce27 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' }) - .validator((d: string) => d) + .inputValidator((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 deleted file mode 100644 index 74c33e5848..0000000000 --- a/examples/react/start-basic-react-query/src/utils/preferences.ts +++ /dev/null @@ -1,34 +0,0 @@ -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 deleted file mode 100644 index 309c402798..0000000000 --- a/examples/react/start-basic-react-query/tests/preferences.spec.ts +++ /dev/null @@ -1,67 +0,0 @@ -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 cef9369516..3a9fb7cd71 100644 --- a/examples/react/start-basic-react-query/tsconfig.json +++ b/examples/react/start-basic-react-query/tsconfig.json @@ -13,6 +13,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/react/start-basic-rsbuild/.gitignore b/examples/react/start-basic-rsbuild/.gitignore deleted file mode 100644 index 1f189d9bc0..0000000000 --- a/examples/react/start-basic-rsbuild/.gitignore +++ /dev/null @@ -1,19 +0,0 @@ -node_modules -package-lock.json -yarn.lock - -.DS_Store -.cache -.env -.vercel -dist -/build/ -/api/ -/server/build -/public/build# Sentry Config File -.env.sentry-build-plugin -/test-results/ -/playwright-report/ -/blob-report/ -/playwright/.cache/ -.tanstack diff --git a/examples/react/start-basic-rsbuild/README.md b/examples/react/start-basic-rsbuild/README.md deleted file mode 100644 index 64117c915b..0000000000 --- a/examples/react/start-basic-rsbuild/README.md +++ /dev/null @@ -1,36 +0,0 @@ -# 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 deleted file mode 100644 index bea4ba26ef..0000000000 --- a/examples/react/start-basic-rsbuild/package.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "name": "tanstack-start-example-basic-rsbuild", - "private": true, - "sideEffects": false, - "type": "module", - "scripts": { - "dev": "rsbuild dev --port 3000", - "build": "rsbuild build && tsc --noEmit", - "preview": "rsbuild preview", - "start": "srvx --prod -s ../client dist/server/index.js" - }, - "dependencies": { - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", - "react": "^19.2.3", - "react-dom": "^19.2.3", - "tailwind-merge": "^3.6.0", - "zod": "^4.4.3" - }, - "devDependencies": { - "@rsbuild/core": "^2.3.1", - "@rsbuild/plugin-react": "^2.0.0", - "@rsbuild/plugin-tailwindcss": "^2.0.3", - "@types/node": "25.0.9", - "@types/react": "^19.2.8", - "@types/react-dom": "^19.2.3", - "srvx": "^1.0.0", - "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2" - } -} diff --git a/examples/react/start-basic-rsbuild/rsbuild.config.ts b/examples/react/start-basic-rsbuild/rsbuild.config.ts deleted file mode 100644 index 3705696818..0000000000 --- a/examples/react/start-basic-rsbuild/rsbuild.config.ts +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index 4a22649ed4..0000000000 --- a/examples/react/start-basic-rsbuild/src/components/DefaultCatchBoundary.tsx +++ /dev/null @@ -1,51 +0,0 @@ -import { - ErrorComponent, - Link, - useLocation, - useRouter, -} from '@tanstack/react-router' -import type { ErrorComponentProps } from '@tanstack/react-router' - -export function DefaultCatchBoundary({ error }: ErrorComponentProps) { - const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', - }) - - console.error('DefaultCatchBoundary Error:', error) - - return ( -
- -
- - {isRoot ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
-
- ) -} diff --git a/examples/react/start-basic-rsbuild/src/components/PostError.tsx b/examples/react/start-basic-rsbuild/src/components/PostError.tsx deleted file mode 100644 index 271f2d1de1..0000000000 --- a/examples/react/start-basic-rsbuild/src/components/PostError.tsx +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index af5d0c6f16..0000000000 --- a/examples/react/start-basic-rsbuild/src/components/UserError.tsx +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index b0ac762b09..0000000000 --- a/examples/react/start-basic-rsbuild/src/env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/start-basic-rsbuild/src/routeTree.gen.ts b/examples/react/start-basic-rsbuild/src/routeTree.gen.ts deleted file mode 100644 index 57b849492d..0000000000 --- a/examples/react/start-basic-rsbuild/src/routeTree.gen.ts +++ /dev/null @@ -1,447 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index f380f73be7..0000000000 --- a/examples/react/start-basic-rsbuild/src/router.tsx +++ /dev/null @@ -1,15 +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 -} diff --git a/examples/react/start-basic-rsbuild/src/routes/__root.tsx b/examples/react/start-basic-rsbuild/src/routes/__root.tsx deleted file mode 100644 index 6d4aed1fe0..0000000000 --- a/examples/react/start-basic-rsbuild/src/routes/__root.tsx +++ /dev/null @@ -1,130 +0,0 @@ -import { - HeadContent, - Link, - Scripts, - createRootRoute, -} from '@tanstack/react-router' -import { TanStackRouterDevtools } from '@tanstack/react-router-devtools' -import * as React from 'react' -import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary' -import { NotFound } from '~/components/NotFound' -import appCss from '~/styles/app.css?url' -import { seo } from '~/utils/seo' - -export const Route = createRootRoute({ - head: () => ({ - meta: [ - { - charSet: 'utf-8', - }, - { - name: 'viewport', - content: 'width=device-width, initial-scale=1', - }, - ...seo({ - title: - 'TanStack Start | Type-Safe, Client-First, Full-Stack React Framework', - description: `TanStack Start is a type-safe, client-first, full-stack React framework. `, - }), - ], - links: [ - { rel: 'stylesheet', href: appCss }, - { - rel: 'apple-touch-icon', - sizes: '180x180', - href: '/apple-touch-icon.png', - }, - { - rel: 'icon', - type: 'image/png', - sizes: '32x32', - href: '/favicon-32x32.png', - }, - { - rel: 'icon', - type: 'image/png', - sizes: '16x16', - href: '/favicon-16x16.png', - }, - { rel: 'manifest', href: '/site.webmanifest', color: '#fffff' }, - { rel: 'icon', href: '/favicon.ico' }, - ], - scripts: [ - { - src: '/customScript.js', - type: 'text/javascript', - }, - ], - }), - errorComponent: DefaultCatchBoundary, - notFoundComponent: () => , - shellComponent: RootDocument, -}) - -function RootDocument({ children }: { children: React.ReactNode }) { - return ( - - - - - -
- - Home - {' '} - - Posts - {' '} - - Users - {' '} - - Pathless Layout - {' '} - - Deferred - {' '} - - This Route Does Not Exist - -
-
- {children} - - - - - ) -} diff --git a/examples/react/start-basic-rsbuild/src/routes/api/users.$userId.ts b/examples/react/start-basic-rsbuild/src/routes/api/users.$userId.ts deleted file mode 100644 index ee34d7a189..0000000000 --- a/examples/react/start-basic-rsbuild/src/routes/api/users.$userId.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import type { User } from '~/utils/users' - -export const Route = createFileRoute('/api/users/$userId')({ - server: { - handlers: { - GET: async ({ params, request }) => { - console.info(`Fetching users by id=${params.userId}... @`, request.url) - try { - const res = await fetch( - 'https://jsonplaceholder.typicode.com/users/' + params.userId, - ) - if (!res.ok) { - throw new Error('Failed to fetch user') - } - - const user = (await res.json()) as User - - return Response.json({ - id: user.id, - name: user.name, - email: user.email, - }) - } catch (e) { - console.error(e) - return Response.json({ error: 'User not found' }, { status: 404 }) - } - }, - }, - }, -}) diff --git a/examples/react/start-basic-rsbuild/src/routes/api/users.ts b/examples/react/start-basic-rsbuild/src/routes/api/users.ts deleted file mode 100644 index 4cecd01852..0000000000 --- a/examples/react/start-basic-rsbuild/src/routes/api/users.ts +++ /dev/null @@ -1,63 +0,0 @@ -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 deleted file mode 100644 index 811471ac15..0000000000 --- a/examples/react/start-basic-rsbuild/src/routes/customScript[.]js.ts +++ /dev/null @@ -1,15 +0,0 @@ -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 deleted file mode 100644 index f3e09d1d4e..0000000000 --- a/examples/react/start-basic-rsbuild/src/routes/deferred.tsx +++ /dev/null @@ -1,62 +0,0 @@ -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 deleted file mode 100644 index 09a907cb18..0000000000 --- a/examples/react/start-basic-rsbuild/src/routes/index.tsx +++ /dev/null @@ -1,13 +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-rsbuild/src/routes/posts.$postId.tsx b/examples/react/start-basic-rsbuild/src/routes/posts.$postId.tsx deleted file mode 100644 index 65905bf8c4..0000000000 --- a/examples/react/start-basic-rsbuild/src/routes/posts.$postId.tsx +++ /dev/null @@ -1,34 +0,0 @@ -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 deleted file mode 100644 index 5b5f08f95b..0000000000 --- a/examples/react/start-basic-rsbuild/src/routes/posts.index.tsx +++ /dev/null @@ -1,9 +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-rsbuild/src/routes/posts.tsx b/examples/react/start-basic-rsbuild/src/routes/posts.tsx deleted file mode 100644 index 9b9162be7c..0000000000 --- a/examples/react/start-basic-rsbuild/src/routes/posts.tsx +++ /dev/null @@ -1,38 +0,0 @@ -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 deleted file mode 100644 index 29e6c39b5a..0000000000 --- a/examples/react/start-basic-rsbuild/src/routes/posts_.$postId.deep.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index ea34b6e420..0000000000 --- a/examples/react/start-basic-rsbuild/src/routes/redirect.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 4e4d470075..0000000000 --- a/examples/react/start-basic-rsbuild/src/routes/users.$userId.tsx +++ /dev/null @@ -1,45 +0,0 @@ -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 ( -
- ) -} diff --git a/examples/react/start-basic-rsbuild/src/routes/users.index.tsx b/examples/react/start-basic-rsbuild/src/routes/users.index.tsx deleted file mode 100644 index 27d136987e..0000000000 --- a/examples/react/start-basic-rsbuild/src/routes/users.index.tsx +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index 64ca3ce156..0000000000 --- a/examples/react/start-basic-rsbuild/src/routes/users.tsx +++ /dev/null @@ -1,49 +0,0 @@ -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 deleted file mode 100644 index 37c1f5a6e2..0000000000 --- a/examples/react/start-basic-rsbuild/src/styles/app.css +++ /dev/null @@ -1,30 +0,0 @@ -@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 deleted file mode 100644 index 3ea9a06439..0000000000 --- a/examples/react/start-basic-rsbuild/src/utils/loggingMiddleware.tsx +++ /dev/null @@ -1,41 +0,0 @@ -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 deleted file mode 100644 index ea7dd0a721..0000000000 --- a/examples/react/start-basic-rsbuild/src/utils/posts.tsx +++ /dev/null @@ -1,40 +0,0 @@ -import { notFound } from '@tanstack/react-router' -import { createServerFn } from '@tanstack/react-start' - -export type PostType = { - id: number - title: string - body: string -} - -export const fetchPost = createServerFn({ method: 'POST' }) - .validator((d: string) => d) - .handler(async ({ data }) => { - console.info(`Fetching post with id ${data}...`) - const res = await fetch( - `https://jsonplaceholder.typicode.com/posts/${data}`, - ) - if (!res.ok) { - if (res.status === 404) { - throw notFound() - } - - throw new Error('Failed to fetch post') - } - - const post = await res.json() - - return post as PostType - }) - -export const fetchPosts = createServerFn().handler(async () => { - console.info('Fetching posts...') - const res = await fetch('https://jsonplaceholder.typicode.com/posts') - if (!res.ok) { - throw new Error('Failed to fetch posts') - } - - const posts = await res.json() - - return (posts as Array).slice(0, 10) -}) diff --git a/examples/react/start-basic-rsbuild/src/utils/users.tsx b/examples/react/start-basic-rsbuild/src/utils/users.tsx deleted file mode 100644 index 7ba645b383..0000000000 --- a/examples/react/start-basic-rsbuild/src/utils/users.tsx +++ /dev/null @@ -1,5 +0,0 @@ -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 deleted file mode 100644 index cc479423a1..0000000000 --- a/examples/react/start-basic-rsbuild/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "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/.gitignore b/examples/react/start-basic-rsc/.gitignore new file mode 100644 index 0000000000..3c8e6870b3 --- /dev/null +++ b/examples/react/start-basic-rsc/.gitignore @@ -0,0 +1,14 @@ +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-rscs/.prettierignore b/examples/react/start-basic-rsc/.prettierignore similarity index 100% rename from examples/react/start-rscs/.prettierignore rename to examples/react/start-basic-rsc/.prettierignore diff --git a/examples/react/start-basic-rsbuild/.vscode/settings.json b/examples/react/start-basic-rsc/.vscode/settings.json similarity index 100% rename from examples/react/start-basic-rsbuild/.vscode/settings.json rename to examples/react/start-basic-rsc/.vscode/settings.json diff --git a/examples/react/start-basic-rsc/README.md b/examples/react/start-basic-rsc/README.md new file mode 100644 index 0000000000..494e34f03f --- /dev/null +++ b/examples/react/start-basic-rsc/README.md @@ -0,0 +1,43 @@ +# 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 new file mode 100644 index 0000000000..3916003ffe --- /dev/null +++ b/examples/react/start-basic-rsc/package.json @@ -0,0 +1,34 @@ +{ + "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.168.1", + "@tanstack/react-router-devtools": "^1.166.10", + "@tanstack/react-start": "^1.167.2", + "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": "^6.0.1", + "tailwindcss": "^4.2.2", + "typescript": "^5.7.2", + "vite": "^8.0.0", + "@tailwindcss/vite": "^4.2.2" + }, + "overrides": { + "react": "0.0.0-experimental-035a41c4e-20230704", + "react-dom": "0.0.0-experimental-035a41c4e-20230704" + } +} diff --git a/examples/react/start-rscs/public/android-chrome-192x192.png b/examples/react/start-basic-rsc/public/android-chrome-192x192.png similarity index 100% rename from examples/react/start-rscs/public/android-chrome-192x192.png rename to examples/react/start-basic-rsc/public/android-chrome-192x192.png diff --git a/examples/react/start-rscs/public/android-chrome-512x512.png b/examples/react/start-basic-rsc/public/android-chrome-512x512.png similarity index 100% rename from examples/react/start-rscs/public/android-chrome-512x512.png rename to examples/react/start-basic-rsc/public/android-chrome-512x512.png diff --git a/examples/react/start-rscs/public/apple-touch-icon.png b/examples/react/start-basic-rsc/public/apple-touch-icon.png similarity index 100% rename from examples/react/start-rscs/public/apple-touch-icon.png rename to examples/react/start-basic-rsc/public/apple-touch-icon.png diff --git a/examples/react/start-rscs/public/favicon-16x16.png b/examples/react/start-basic-rsc/public/favicon-16x16.png similarity index 100% rename from examples/react/start-rscs/public/favicon-16x16.png rename to examples/react/start-basic-rsc/public/favicon-16x16.png diff --git a/examples/react/start-rscs/public/favicon-32x32.png b/examples/react/start-basic-rsc/public/favicon-32x32.png similarity index 100% rename from examples/react/start-rscs/public/favicon-32x32.png rename to examples/react/start-basic-rsc/public/favicon-32x32.png diff --git a/examples/react/start-rscs/public/favicon.ico b/examples/react/start-basic-rsc/public/favicon.ico similarity index 100% rename from examples/react/start-rscs/public/favicon.ico rename to examples/react/start-basic-rsc/public/favicon.ico diff --git a/examples/react/start-rscs/public/favicon.png b/examples/react/start-basic-rsc/public/favicon.png similarity index 100% rename from examples/react/start-rscs/public/favicon.png rename to examples/react/start-basic-rsc/public/favicon.png diff --git a/examples/react/start-rscs/public/site.webmanifest b/examples/react/start-basic-rsc/public/site.webmanifest similarity index 100% rename from examples/react/start-rscs/public/site.webmanifest rename to examples/react/start-basic-rsc/public/site.webmanifest diff --git a/examples/react/start-basic-rsc/src/components/DefaultCatchBoundary.tsx b/examples/react/start-basic-rsc/src/components/DefaultCatchBoundary.tsx new file mode 100644 index 0000000000..ef2daa1ea1 --- /dev/null +++ b/examples/react/start-basic-rsc/src/components/DefaultCatchBoundary.tsx @@ -0,0 +1,53 @@ +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 new file mode 100644 index 0000000000..fd4e75befe --- /dev/null +++ b/examples/react/start-basic-rsc/src/components/NotFound.tsx @@ -0,0 +1,25 @@ +import { Link } from '@tanstack/react-router' + +export function NotFound({ children }: { children?: any }) { + return ( +
+
+ {children ||

The page you are looking for does not exist.

} +
+

+ + + Start Over + +

+
+ ) +} diff --git a/examples/react/start-basic-rsc/src/routeTree.gen.ts b/examples/react/start-basic-rsc/src/routeTree.gen.ts new file mode 100644 index 0000000000..723bc9ef42 --- /dev/null +++ b/examples/react/start-basic-rsc/src/routeTree.gen.ts @@ -0,0 +1,263 @@ +/* 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 { + ssr: true + router: Awaited> + } +} diff --git a/examples/react/start-basic-rsc/src/router.tsx b/examples/react/start-basic-rsc/src/router.tsx new file mode 100644 index 0000000000..f648dfcf8c --- /dev/null +++ b/examples/react/start-basic-rsc/src/router.tsx @@ -0,0 +1,22 @@ +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 new file mode 100644 index 0000000000..0a5e0bf370 --- /dev/null +++ b/examples/react/start-basic-rsc/src/routes/__root.tsx @@ -0,0 +1,125 @@ +/// +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-rsbuild/src/routes/_pathlessLayout.tsx b/examples/react/start-basic-rsc/src/routes/_pathlessLayout.tsx similarity index 100% rename from examples/react/start-basic-rsbuild/src/routes/_pathlessLayout.tsx rename to examples/react/start-basic-rsc/src/routes/_pathlessLayout.tsx diff --git a/examples/react/start-basic-rsbuild/src/routes/_pathlessLayout/_nested-layout.tsx b/examples/react/start-basic-rsc/src/routes/_pathlessLayout/_nested-layout.tsx similarity index 93% rename from examples/react/start-basic-rsbuild/src/routes/_pathlessLayout/_nested-layout.tsx rename to examples/react/start-basic-rsc/src/routes/_pathlessLayout/_nested-layout.tsx index 9a48b73a46..c5bcffd5a4 100644 --- a/examples/react/start-basic-rsbuild/src/routes/_pathlessLayout/_nested-layout.tsx +++ b/examples/react/start-basic-rsc/src/routes/_pathlessLayout/_nested-layout.tsx @@ -7,7 +7,7 @@ export const Route = createFileRoute('/_pathlessLayout/_nested-layout')({ function LayoutComponent() { return (
-
I'm a nested layout
+
I'm a nested pathless layout
+

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 new file mode 100644 index 0000000000..f3dba9bfd3 --- /dev/null +++ b/examples/react/start-basic-rsc/src/routes/posts.$postId.tsx @@ -0,0 +1,45 @@ +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 new file mode 100644 index 0000000000..c659274567 --- /dev/null +++ b/examples/react/start-basic-rsc/src/routes/posts.index.tsx @@ -0,0 +1,8 @@ +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 new file mode 100644 index 0000000000..a3ef2a2e20 --- /dev/null +++ b/examples/react/start-basic-rsc/src/routes/posts.tsx @@ -0,0 +1,16 @@ +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 new file mode 100644 index 0000000000..13d368cf9c --- /dev/null +++ b/examples/react/start-basic-rsc/src/routes/posts_.$postId.deep.tsx @@ -0,0 +1,26 @@ +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 new file mode 100644 index 0000000000..0ef1bc98da --- /dev/null +++ b/examples/react/start-basic-rsc/src/styles/app.css @@ -0,0 +1,40 @@ +@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 { + 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 new file mode 100644 index 0000000000..16fc1744e6 --- /dev/null +++ b/examples/react/start-basic-rsc/src/utils/posts.tsx @@ -0,0 +1,35 @@ +// 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 new file mode 100644 index 0000000000..37c0661217 --- /dev/null +++ b/examples/react/start-basic-rsc/src/utils/renderPosts.tsx @@ -0,0 +1,63 @@ +'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/examples/react/start-basic-rsc/src/utils/seo.ts b/examples/react/start-basic-rsc/src/utils/seo.ts new file mode 100644 index 0000000000..d18ad84b74 --- /dev/null +++ b/examples/react/start-basic-rsc/src/utils/seo.ts @@ -0,0 +1,33 @@ +export const seo = ({ + title, + description, + keywords, + image, +}: { + title: string + description?: string + image?: string + keywords?: string +}) => { + const tags = [ + { title }, + { name: 'description', content: description }, + { name: 'keywords', content: keywords }, + { name: 'twitter:title', content: title }, + { name: 'twitter:description', content: description }, + { name: 'twitter:creator', content: '@tannerlinsley' }, + { name: 'twitter:site', content: '@tannerlinsley' }, + { name: 'og:type', content: 'website' }, + { name: 'og:title', content: title }, + { name: 'og:description', content: description }, + ...(image + ? [ + { name: 'twitter:image', content: image }, + { name: 'twitter:card', content: 'summary_large_image' }, + { name: 'og:image', content: image }, + ] + : []), + ] + + return tags +} diff --git a/examples/react/start-basic-rsc/tsconfig.json b/examples/react/start-basic-rsc/tsconfig.json new file mode 100644 index 0000000000..3a9fb7cd71 --- /dev/null +++ b/examples/react/start-basic-rsc/tsconfig.json @@ -0,0 +1,22 @@ +{ + "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 new file mode 100644 index 0000000000..ed6799764a --- /dev/null +++ b/examples/react/start-basic-rsc/vite.config.ts @@ -0,0 +1,14 @@ +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import { defineConfig } from 'vite' +import viteReact from '@vitejs/plugin-react' +import tailwindcss from '@tailwindcss/vite' + +export default defineConfig({ + server: { + port: 3000, + }, + resolve: { + tsconfigPaths: true, + }, + plugins: [tailwindcss(), tanstackStart(), viteReact()], +}) diff --git a/examples/react/start-basic-static/package.json b/examples/react/start-basic-static/package.json index 58d573ca36..d1113b4f21 100644 --- a/examples/react/start-basic-static/package.json +++ b/examples/react/start-basic-static/package.json @@ -10,24 +10,23 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", - "@tanstack/start-static-server-functions": "^1.167.44", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", + "@tanstack/react-start": "^1.167.2", + "@tanstack/start-static-server-functions": "^1.166.17", "@vitejs/plugin-react": "^6.0.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwind-merge": "^3.6.0" + "tailwind-merge": "^2.6.0" }, "devDependencies": { - "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.4", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "typescript": "^5.6.2", + "vite": "^8.0.0", + "@tailwindcss/vite": "^4.2.2" } } diff --git a/examples/react/start-basic-static/src/components/DefaultCatchBoundary.tsx b/examples/react/start-basic-static/src/components/DefaultCatchBoundary.tsx index 4a22649ed4..260c2ea41f 100644 --- a/examples/react/start-basic-static/src/components/DefaultCatchBoundary.tsx +++ b/examples/react/start-basic-static/src/components/DefaultCatchBoundary.tsx @@ -1,15 +1,17 @@ import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, 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 === '/', + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, }) console.error('DefaultCatchBoundary Error:', error) diff --git a/examples/react/start-basic-static/src/routeTree.gen.ts b/examples/react/start-basic-static/src/routeTree.gen.ts index d4a8e72343..ddc8fc320a 100644 --- a/examples/react/start-basic-static/src/routeTree.gen.ts +++ b/examples/react/start-basic-static/src/routeTree.gen.ts @@ -9,38 +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 IndexRouteImport } from './routes/index' -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 PostsIndexRouteImport } from './routes/posts.index' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +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 PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +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 IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', - getParentRoute: () => rootRouteImport, -} as any) -const DeferredRoute = DeferredRouteImport.update({ - id: '/deferred', - path: '/deferred', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', getParentRoute: () => rootRouteImport, } as any) const RedirectRoute = RedirectRouteImport.update({ @@ -48,53 +34,67 @@ const RedirectRoute = RedirectRouteImport.update({ path: '/redirect', getParentRoute: () => rootRouteImport, } as any) -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +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({ +const DeferredRoute = DeferredRouteImport.update({ + id: '/deferred', + path: '/deferred', + getParentRoute: () => rootRouteImport, +} as any) +const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ + id: '/_pathlessLayout', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', - getParentRoute: () => PostsRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, + 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 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, +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 @@ -196,32 +196,11 @@ export interface RootRouteChildren { 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 - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport parentRoute: typeof rootRouteImport } '/redirect': { @@ -231,33 +210,33 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof RedirectRouteImport parentRoute: typeof rootRouteImport } - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport + parentRoute: typeof rootRouteImport + } + '/_pathlessLayout': { + id: '/_pathlessLayout' path: '' fullPath: '/' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute + preLoaderRoute: typeof PathlessLayoutRouteImport + parentRoute: typeof rootRouteImport } - '/posts/': { - id: '/posts/' + '/': { + id: '/' 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 + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport } '/users/': { id: '/users/' @@ -266,6 +245,13 @@ declare module '@tanstack/react-router' { 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' @@ -273,12 +259,26 @@ declare module '@tanstack/react-router' { 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 + '/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' @@ -287,12 +287,12 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutNestedLayoutRoute } - '/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-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute } } } diff --git a/examples/react/start-basic-static/src/routes/deferred.tsx b/examples/react/start-basic-static/src/routes/deferred.tsx index 07810ddc39..f0d832b805 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]) - .validator((d: string) => d) + .inputValidator((d: string) => d) .handler(({ data: name }) => { return { name, randomNumber: Math.floor(Math.random() * 100) } }) const slowServerFn = createServerFn({ method: 'GET' }) .middleware([staticFunctionMiddleware]) - .validator((d: string) => d) + .inputValidator((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 2d2d32279d..2e163f86ef 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]) - .validator((d: string) => d) + .inputValidator((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/utils/posts.tsx b/examples/react/start-basic-static/src/utils/posts.tsx index 82e568ceef..5f01de769a 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]) - .validator((d: string) => d) + .inputValidator((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/tsconfig.json b/examples/react/start-basic-static/tsconfig.json index cef9369516..3a9fb7cd71 100644 --- a/examples/react/start-basic-static/tsconfig.json +++ b/examples/react/start-basic-static/tsconfig.json @@ -13,6 +13,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/react/start-basic/package.json b/examples/react/start-basic/package.json index 46df8e4650..1c753cb87e 100644 --- a/examples/react/start-basic/package.json +++ b/examples/react/start-basic/package.json @@ -10,13 +10,13 @@ "start": "node .output/server/index.mjs" }, "dependencies": { - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", + "@tanstack/react-start": "^1.167.2", "react": "^19.0.0", "react-dom": "^19.0.0", - "tailwind-merge": "^3.6.0", - "zod": "^4.4.3" + "tailwind-merge": "^2.6.0", + "zod": "^3.24.2" }, "devDependencies": { "@tailwindcss/vite": "^4.2.2", @@ -24,10 +24,9 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "nitro": "^3.0.260903-beta", + "nitro": "^3.0.260311-beta", "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/react/start-basic/src/components/DefaultCatchBoundary.tsx b/examples/react/start-basic/src/components/DefaultCatchBoundary.tsx index 4a22649ed4..260c2ea41f 100644 --- a/examples/react/start-basic/src/components/DefaultCatchBoundary.tsx +++ b/examples/react/start-basic/src/components/DefaultCatchBoundary.tsx @@ -1,15 +1,17 @@ import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, 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 === '/', + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, }) 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 57b849492d..0bd698a666 100644 --- a/examples/react/start-basic/src/routeTree.gen.ts +++ b/examples/react/start-basic/src/routeTree.gen.ts @@ -9,46 +9,27 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as 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 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 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 PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as ApiUsersRouteImport } from './routes/api/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 PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' -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', +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', getParentRoute: () => rootRouteImport, } as any) const RedirectRoute = RedirectRouteImport.update({ @@ -56,9 +37,53 @@ const RedirectRoute = RedirectRouteImport.update({ path: '/redirect', getParentRoute: () => rootRouteImport, } as any) -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', + getParentRoute: () => rootRouteImport, +} as any) +const DeferredRoute = DeferredRouteImport.update({ + id: '/deferred', + path: '/deferred', + getParentRoute: () => rootRouteImport, +} as any) +const CustomScriptDotjsRoute = CustomScriptDotjsRouteImport.update({ + id: '/customScript.js', + path: '/customScript.js', + 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 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', getParentRoute: () => rootRouteImport, } as any) const PathlessLayoutNestedLayoutRoute = @@ -66,53 +91,28 @@ const PathlessLayoutNestedLayoutRoute = id: '/_nested-layout', getParentRoute: () => PathlessLayoutRoute, } as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', 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({ +const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ id: '/$userId', path: '/$userId', - getParentRoute: () => UsersRoute, + getParentRoute: () => ApiUsersRoute, } 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) +const PathlessLayoutNestedLayoutRouteARoute = + PathlessLayoutNestedLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + } as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -234,39 +234,11 @@ export interface RootRouteChildren { 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 + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport parentRoute: typeof rootRouteImport } '/redirect': { @@ -276,11 +248,74 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof RedirectRouteImport parentRoute: typeof rootRouteImport } - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport + parentRoute: typeof rootRouteImport + } + '/customScript.js': { + id: '/customScript.js' + path: '/customScript.js' + fullPath: '/customScript.js' + preLoaderRoute: typeof CustomScriptDotjsRouteImport + parentRoute: typeof rootRouteImport + } + '/_pathlessLayout': { + id: '/_pathlessLayout' + 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 + } + '/api/users': { + id: '/api/users' + path: '/api/users' + fullPath: '/api/users' + preLoaderRoute: typeof ApiUsersRouteImport parentRoute: typeof rootRouteImport } '/_pathlessLayout/_nested-layout': { @@ -290,55 +325,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport parentRoute: typeof PathlessLayoutRoute } - '/api/users': { - id: '/api/users' - path: '/api/users' - fullPath: '/api/users' - preLoaderRoute: typeof ApiUsersRouteImport + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport parentRoute: typeof rootRouteImport } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute - } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute - } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRoute - } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } - '/_pathlessLayout/_nested-layout/route-b': { - id: '/_pathlessLayout/_nested-layout/route-b' - path: '/route-b' - fullPath: '/route-b' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } '/api/users/$userId': { id: '/api/users/$userId' path: '/$userId' @@ -346,12 +339,19 @@ declare module '@tanstack/react-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 + '/_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 } } } diff --git a/examples/react/start-basic/src/routes/deferred.tsx b/examples/react/start-basic/src/routes/deferred.tsx index f3e09d1d4e..c38808243e 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' }) - .validator((d: string) => d) + .inputValidator((d: string) => d) .handler(({ data: name }) => { return { name, randomNumber: Math.floor(Math.random() * 100) } }) const slowServerFn = createServerFn({ method: 'GET' }) - .validator((d: string) => d) + .inputValidator((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 4e4d470075..1df768344d 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 '../components/NotFound' -import { UserErrorComponent } from '../components/UserError' +import { NotFound } from 'src/components/NotFound' +import { UserErrorComponent } from 'src/components/UserError' import type { User } from '../utils/users' export const Route = createFileRoute('/users/$userId')({ diff --git a/examples/react/start-basic/src/utils/posts.tsx b/examples/react/start-basic/src/utils/posts.tsx index ea7dd0a721..098542fd74 100644 --- a/examples/react/start-basic/src/utils/posts.tsx +++ b/examples/react/start-basic/src/utils/posts.tsx @@ -8,7 +8,7 @@ export type PostType = { } export const fetchPost = createServerFn({ method: 'POST' }) - .validator((d: string) => d) + .inputValidator((d: string) => d) .handler(async ({ data }) => { console.info(`Fetching post with id ${data}...`) const res = await fetch( diff --git a/examples/react/start-basic/tsconfig.json b/examples/react/start-basic/tsconfig.json index cc479423a1..3a9fb7cd71 100644 --- a/examples/react/start-basic/tsconfig.json +++ b/examples/react/start-basic/tsconfig.json @@ -1,18 +1,19 @@ { - "include": ["**/*.ts", "**/*.tsx", "**/*.d.ts"], + "include": ["**/*.ts", "**/*.tsx"], "compilerOptions": { "strict": true, "esModuleInterop": true, "jsx": "react-jsx", "module": "ESNext", "moduleResolution": "Bundler", - "lib": ["DOM", "DOM.Iterable", "ES2024"], + "lib": ["DOM", "DOM.Iterable", "ES2022"], "isolatedModules": true, "resolveJsonModule": true, "skipLibCheck": true, - "target": "ES2024", + "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/react/start-bun/package.json b/examples/react/start-bun/package.json index 24f7113912..ba14098a2c 100644 --- a/examples/react/start-bun/package.json +++ b/examples/react/start-bun/package.json @@ -14,12 +14,11 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-devtools": "^0.7.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-router-ssr-query": "^1.167.3", - "@tanstack/react-start": "^1.169.6", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", + "@tanstack/react-router-ssr-query": "^1.166.10", + "@tanstack/react-start": "^1.167.2", + "@tanstack/router-plugin": "^1.167.2", "react": "^19.1.1", "react-dom": "^19.1.1", "tailwindcss": "^4.2.2" @@ -35,10 +34,9 @@ "@vitejs/plugin-react": "^6.0.1", "jsdom": "^27.0.0", "prettier": "^3.6.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", - "vitest": "^5.0.4", + "typescript": "^5.9.2", + "vite": "^8.0.0", + "vitest": "^3.2.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 77415f9088..18fbc9b60e 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 DemoStartApiRequestRouteImport } from './routes/demo.start.api-request' import { Route as DemoStartServerFuncsRouteImport } from './routes/demo.start.server-funcs' +import { Route as DemoStartApiRequestRouteImport } from './routes/demo.start.api-request' const IndexRoute = IndexRouteImport.update({ id: '/', @@ -24,16 +24,16 @@ const ApiDemoNamesRoute = ApiDemoNamesRouteImport.update({ path: '/api/demo-names', 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) +const DemoStartApiRequestRoute = DemoStartApiRequestRouteImport.update({ + id: '/demo/start/api-request', + path: '/demo/start/api-request', + 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/api-request': { - id: '/demo/start/api-request' - path: '/demo/start/api-request' - fullPath: '/demo/start/api-request' - preLoaderRoute: typeof DemoStartApiRequestRouteImport - parentRoute: typeof rootRouteImport - } '/demo/start/server-funcs': { id: '/demo/start/server-funcs' path: '/demo/start/server-funcs' @@ -112,6 +105,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof DemoStartServerFuncsRouteImport parentRoute: typeof rootRouteImport } + '/demo/start/api-request': { + id: '/demo/start/api-request' + path: '/demo/start/api-request' + fullPath: '/demo/start/api-request' + preLoaderRoute: typeof DemoStartApiRequestRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/react/start-bun/src/routes/__root.tsx b/examples/react/start-bun/src/routes/__root.tsx index cf53f185c5..781d3914ef 100644 --- a/examples/react/start-bun/src/routes/__root.tsx +++ b/examples/react/start-bun/src/routes/__root.tsx @@ -1,6 +1,5 @@ -import { TanStackDevtools } from '@tanstack/react-devtools' import { HeadContent, Scripts, createRootRoute } from '@tanstack/react-router' -import { TanStackRouterDevtoolsPanel } from '@tanstack/react-router-devtools' +import { TanStackRouterDevtools } from '@tanstack/react-router-devtools' import Header from '../components/Header' @@ -40,17 +39,7 @@ function RootDocument({ children }: { children: React.ReactNode }) {
{children} - , - }, - ]} - /> + 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 64629c0bdc..e1a132aa1d 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' }) - .validator((d: string) => d) + .inputValidator((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/vite-env.d.ts b/examples/react/start-bun/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/start-bun/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/start-bun/tsconfig.json b/examples/react/start-bun/tsconfig.json index 2f09fb43be..2cc3abd5d4 100644 --- a/examples/react/start-bun/tsconfig.json +++ b/examples/react/start-bun/tsconfig.json @@ -27,6 +27,7 @@ "noUnusedParameters": true, "noFallthroughCasesInSwitch": true, "noUncheckedSideEffectImports": true, + "baseUrl": ".", "paths": { "@/*": ["./src/*"] } diff --git a/examples/react/start-clerk-basic/package.json b/examples/react/start-clerk-basic/package.json index 022300e159..16e7f4f04c 100644 --- a/examples/react/start-clerk-basic/package.json +++ b/examples/react/start-clerk-basic/package.json @@ -11,15 +11,15 @@ }, "dependencies": { "@clerk/tanstack-react-start": "^0.27.14", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", + "@tanstack/react-start": "^1.167.2", "@vitejs/plugin-react": "^6.0.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "srvx": "^1.0.0", - "tailwind-merge": "^3.6.0" + "srvx": "^0.11.9", + "tailwind-merge": "^2.6.0" }, "devDependencies": { "@tailwindcss/vite": "^4.2.2", @@ -27,8 +27,7 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/react/start-clerk-basic/src/components/DefaultCatchBoundary.tsx b/examples/react/start-clerk-basic/src/components/DefaultCatchBoundary.tsx index 405fb5f4a7..ef2daa1ea1 100644 --- a/examples/react/start-clerk-basic/src/components/DefaultCatchBoundary.tsx +++ b/examples/react/start-clerk-basic/src/components/DefaultCatchBoundary.tsx @@ -1,15 +1,17 @@ import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, 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 === '/', + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, }) 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 87269f2faf..04f57442e2 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 IndexRouteImport } from './routes/index' import { Route as AuthedRouteImport } from './routes/_authed' +import { Route as IndexRouteImport } from './routes/index' 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' import { Route as AuthedProfileSplatRouteImport } from './routes/_authed/profile.$' +import { Route as AuthedPostsPostIdRouteImport } from './routes/_authed/posts.$postId' +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 AuthedPostsPostIdRoute = AuthedPostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - 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) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -90,13 +90,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/_authed': { id: '/_authed' path: '' @@ -104,6 +97,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthedRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + 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/posts/$postId': { - id: '/_authed/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof AuthedPostsPostIdRouteImport - parentRoute: typeof AuthedPostsRoute - } '/_authed/profile/$': { id: '/_authed/profile/$' path: '/profile/$' @@ -132,6 +125,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthedProfileSplatRouteImport parentRoute: typeof AuthedRoute } + '/_authed/posts/$postId': { + id: '/_authed/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof AuthedPostsPostIdRouteImport + parentRoute: typeof AuthedPostsRoute + } } } diff --git a/examples/react/start-clerk-basic/src/routes/_authed.tsx b/examples/react/start-clerk-basic/src/routes/_authed.tsx index 04f8196894..1a97917c12 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 instanceof Error && error.message === 'Not authenticated') { + if (error.message === 'Not authenticated') { return (
diff --git a/examples/react/start-clerk-basic/src/utils/posts.ts b/examples/react/start-clerk-basic/src/utils/posts.ts index a7e0e99cfa..fbcc43c34b 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' }) - .validator((postId: string) => postId) + .inputValidator((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 cef9369516..3a9fb7cd71 100644 --- a/examples/react/start-clerk-basic/tsconfig.json +++ b/examples/react/start-clerk-basic/tsconfig.json @@ -13,6 +13,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/react/start-convex-trellaux/convex/board.ts b/examples/react/start-convex-trellaux/convex/board.ts index f585a01cd3..bae241a773 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 './invariant' +import invariant from 'tiny-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 deleted file mode 100644 index 41fcded35e..0000000000 --- a/examples/react/start-convex-trellaux/convex/invariant.ts +++ /dev/null @@ -1,5 +0,0 @@ -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 3452f910d0..171c516d08 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.102.0", + "@tanstack/react-query": "^5.90.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-router-ssr-query": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", + "@tanstack/react-router-ssr-query": "^1.166.10", + "@tanstack/react-start": "^1.167.2", "concurrently": "^8.2.2", "convex": "^1.19.0", "ky": "^1.7.4", @@ -27,8 +27,9 @@ "react-dom": "^19.0.0", "react-hot-toast": "^2.5.1", "redaxios": "^0.5.1", - "tailwind-merge": "^3.6.0", - "zod": "^4.4.3" + "tailwind-merge": "^2.6.0", + "tiny-invariant": "^1.3.3", + "zod": "^3.24.2" }, "devDependencies": { "@tailwindcss/vite": "^4.2.2", @@ -37,8 +38,7 @@ "@types/react-dom": "^19.0.3", "@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" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/react/start-convex-trellaux/src/components/Board.tsx b/examples/react/start-convex-trellaux/src/components/Board.tsx index ac78c7baae..327603e204 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 '../invariant' +import invariant from 'tiny-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 23f77ca2b2..eacf87d759 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 '../invariant' +import invariant from 'tiny-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 fdf2916f6b..dd90e02ee7 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 405fb5f4a7..ef2daa1ea1 100644 --- a/examples/react/start-convex-trellaux/src/components/DefaultCatchBoundary.tsx +++ b/examples/react/start-convex-trellaux/src/components/DefaultCatchBoundary.tsx @@ -1,15 +1,17 @@ import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, 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 === '/', + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, }) 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 99b0b14839..47cadcf5ae 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 '../invariant' +import invariant from 'tiny-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 0cd1f6aa53..50a7d608c5 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 '../invariant' +import invariant from 'tiny-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 74c449e894..99bd5e220b 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 deleted file mode 100644 index 41fcded35e..0000000000 --- a/examples/react/start-convex-trellaux/src/invariant.ts +++ /dev/null @@ -1,5 +0,0 @@ -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/utils/posts.tsx b/examples/react/start-convex-trellaux/src/utils/posts.tsx index e87764806d..cf602f9827 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' }) - .validator((postId: string) => postId) + .inputValidator((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 8de1ae61be..3a9fb7cd71 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/*"], - "convex/*": ["./convex/*"] + "~/*": ["./src/*"] }, "noEmit": true } diff --git a/examples/react/start-counter/package.json b/examples/react/start-counter/package.json index 8f4673143e..a60f15bcd2 100644 --- a/examples/react/start-counter/package.json +++ b/examples/react/start-counter/package.json @@ -10,9 +10,9 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", + "@tanstack/react-start": "^1.167.2", "react": "^19.0.0", "react-dom": "^19.0.0" }, @@ -21,8 +21,7 @@ "@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" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/react/start-counter/src/routes/index.tsx b/examples/react/start-counter/src/routes/index.tsx index b95cc76ec8..0faec87836 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' }) - .validator((addBy: number) => addBy) + .inputValidator((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 cef9369516..3a9fb7cd71 100644 --- a/examples/react/start-counter/tsconfig.json +++ b/examples/react/start-counter/tsconfig.json @@ -13,6 +13,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/react/start-i18n-paraglide/package.json b/examples/react/start-i18n-paraglide/package.json index 074f714d5c..ec55663e6d 100644 --- a/examples/react/start-i18n-paraglide/package.json +++ b/examples/react/start-i18n-paraglide/package.json @@ -9,10 +9,9 @@ "preview": "vite preview" }, "dependencies": { - "@tanstack/react-devtools": "^0.7.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", + "@tanstack/react-start": "^1.167.2", "react": "^19.1.1", "react-dom": "^19.1.1" }, @@ -21,22 +20,10 @@ "@types/react": "^19.1.13", "@types/react-dom": "^19.1.9", "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", + "typescript": "^5.9.2", + "vite": "^8.0.0", "@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 d89758e684..421daf2790 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 IndexRouteImport } from './routes/index' import { Route as AboutRouteImport } from './routes/about' +import { Route as IndexRouteImport } from './routes/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const AboutRoute = AboutRouteImport.update({ id: '/about', path: '/about', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/about': { id: '/about' path: '/about' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AboutRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/react/start-i18n-paraglide/src/routes/__root.tsx b/examples/react/start-i18n-paraglide/src/routes/__root.tsx index f1a83836a0..422dcee893 100644 --- a/examples/react/start-i18n-paraglide/src/routes/__root.tsx +++ b/examples/react/start-i18n-paraglide/src/routes/__root.tsx @@ -4,8 +4,7 @@ import { Scripts, createRootRoute, } from '@tanstack/react-router' -import { TanStackRouterDevtoolsPanel } from '@tanstack/react-router-devtools' -import { TanStackDevtools } from '@tanstack/react-devtools' +import { TanStackRouterDevtools } from '@tanstack/react-router-devtools' import styles from '../styles.css?url' import { getLocale, locales, setLocale } from '@/paraglide/runtime' import { m } from '@/paraglide/messages' @@ -77,17 +76,7 @@ function RootDocument({ children }: { children: React.ReactNode }) {
{children}
- , - }, - ]} - /> + diff --git a/examples/react/start-i18n-paraglide/src/routes/index.tsx b/examples/react/start-i18n-paraglide/src/routes/index.tsx index 84aa381436..6a9efa6f88 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() - .validator((emoji: string) => emoji) + .inputValidator((emoji: string) => emoji) .handler((ctx) => { return m.server_message({ emoji: ctx.data }) }) diff --git a/examples/react/start-i18n-paraglide/src/vite-env.d.ts b/examples/react/start-i18n-paraglide/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/start-i18n-paraglide/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/start-i18n-paraglide/tsconfig.json b/examples/react/start-i18n-paraglide/tsconfig.json index 471d55aed8..3e42c72626 100644 --- a/examples/react/start-i18n-paraglide/tsconfig.json +++ b/examples/react/start-i18n-paraglide/tsconfig.json @@ -21,6 +21,7 @@ "noUnusedParameters": true, "noFallthroughCasesInSwitch": true, "noUncheckedSideEffectImports": true, + "baseUrl": ".", "paths": { "@/*": ["./src/*"] } diff --git a/examples/react/start-large/package.json b/examples/react/start-large/package.json index f9f86b81d1..aae67d405d 100644 --- a/examples/react/start-large/package.json +++ b/examples/react/start-large/package.json @@ -12,14 +12,14 @@ "test:types": "tsc --extendedDiagnostics" }, "dependencies": { - "@tanstack/react-query": "^5.102.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-query": "^5.90.0", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", + "@tanstack/react-start": "^1.167.2", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwind-merge": "^3.6.0", + "tailwind-merge": "^2.6.0", "valibot": "^1.0.0-beta.15" }, "devDependencies": { @@ -29,9 +29,8 @@ "@types/react-dom": "^19.0.3", "@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" + "typescript": "^5.7.2", + "vite": "^8.0.0" }, "keywords": [], "author": "", diff --git a/examples/react/start-large/src/routeTree.gen.ts b/examples/react/start-large/src/routeTree.gen.ts index 4f1551f71d..03cc2b9080 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 IndexRouteImport } from './routes/index' -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 LinkPropsRouteImport } from './routes/linkProps' +import { Route as AbsoluteRouteImport } from './routes/absolute' import { Route as SearchRouteRouteImport } from './routes/search/route' -import { Route as ParamsParamsPlaceholderRouteImport } from './routes/params/$paramsPlaceholder' +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 ParamsParamsPlaceholderRouteImport } from './routes/params/$paramsPlaceholder' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const AbsoluteRoute = AbsoluteRouteImport.update({ - id: '/absolute', - path: '/absolute', +const RelativeRoute = RelativeRouteImport.update({ + id: '/relative', + path: '/relative', getParentRoute: () => rootRouteImport, } as any) const LinkPropsRoute = LinkPropsRouteImport.update({ @@ -33,14 +28,9 @@ const LinkPropsRoute = LinkPropsRouteImport.update({ path: '/linkProps', getParentRoute: () => rootRouteImport, } as any) -const ParamsRouteRoute = ParamsRouteRouteImport.update({ - id: '/params', - path: '/params', - getParentRoute: () => rootRouteImport, -} as any) -const RelativeRoute = RelativeRouteImport.update({ - id: '/relative', - path: '/relative', +const AbsoluteRoute = AbsoluteRouteImport.update({ + id: '/absolute', + path: '/absolute', getParentRoute: () => rootRouteImport, } as any) const SearchRouteRoute = SearchRouteRouteImport.update({ @@ -48,16 +38,26 @@ const SearchRouteRoute = SearchRouteRouteImport.update({ path: '/search', getParentRoute: () => rootRouteImport, } as any) -const ParamsParamsPlaceholderRoute = ParamsParamsPlaceholderRouteImport.update({ - id: '/$paramsPlaceholder', - path: '/$paramsPlaceholder', - getParentRoute: () => ParamsRouteRoute, +const ParamsRouteRoute = ParamsRouteRouteImport.update({ + id: '/params', + path: '/params', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, } as any) const SearchSearchPlaceholderRoute = SearchSearchPlaceholderRouteImport.update({ id: '/searchPlaceholder', path: '/searchPlaceholder', getParentRoute: () => SearchRouteRoute, } as any) +const ParamsParamsPlaceholderRoute = ParamsParamsPlaceholderRouteImport.update({ + id: '/$paramsPlaceholder', + path: '/$paramsPlaceholder', + getParentRoute: () => ParamsRouteRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -134,18 +134,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/absolute': { - id: '/absolute' - path: '/absolute' - fullPath: '/absolute' - preLoaderRoute: typeof AbsoluteRouteImport + '/relative': { + id: '/relative' + path: '/relative' + fullPath: '/relative' + preLoaderRoute: typeof RelativeRouteImport parentRoute: typeof rootRouteImport } '/linkProps': { @@ -155,18 +148,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof LinkPropsRouteImport parentRoute: typeof rootRouteImport } - '/params': { - id: '/params' - path: '/params' - fullPath: '/params' - preLoaderRoute: typeof ParamsRouteRouteImport - parentRoute: typeof rootRouteImport - } - '/relative': { - id: '/relative' - path: '/relative' - fullPath: '/relative' - preLoaderRoute: typeof RelativeRouteImport + '/absolute': { + id: '/absolute' + path: '/absolute' + fullPath: '/absolute' + preLoaderRoute: typeof AbsoluteRouteImport parentRoute: typeof rootRouteImport } '/search': { @@ -176,12 +162,19 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof SearchRouteRouteImport parentRoute: typeof rootRouteImport } - '/params/$paramsPlaceholder': { - id: '/params/$paramsPlaceholder' - path: '/$paramsPlaceholder' - fullPath: '/params/$paramsPlaceholder' - preLoaderRoute: typeof ParamsParamsPlaceholderRouteImport - parentRoute: typeof ParamsRouteRoute + '/params': { + id: '/params' + path: '/params' + fullPath: '/params' + preLoaderRoute: typeof ParamsRouteRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport } '/search/searchPlaceholder': { id: '/search/searchPlaceholder' @@ -190,6 +183,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof SearchSearchPlaceholderRouteImport parentRoute: typeof SearchRouteRoute } + '/params/$paramsPlaceholder': { + id: '/params/$paramsPlaceholder' + path: '/$paramsPlaceholder' + fullPath: '/params/$paramsPlaceholder' + preLoaderRoute: typeof ParamsParamsPlaceholderRouteImport + parentRoute: typeof ParamsRouteRoute + } } } diff --git a/examples/react/start-large/src/routes/params/$paramsPlaceholder.tsx b/examples/react/start-large/src/routes/params/$paramsPlaceholder.tsx index 7238dea314..568adb11be 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' }) - .validator(params) + .inputValidator(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 b8bdfbb453..bcf6bc777f 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' }) - .validator(search) + .inputValidator(search) .client(({ next }) => { const context = { client: { searchPlaceholder: 'searchPlaceholder' } } return next({ diff --git a/examples/react/start-large/tsconfig.json b/examples/react/start-large/tsconfig.json index cef9369516..3a9fb7cd71 100644 --- a/examples/react/start-large/tsconfig.json +++ b/examples/react/start-large/tsconfig.json @@ -13,6 +13,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/react/start-material-ui/package.json b/examples/react/start-material-ui/package.json index 1647e95f20..a0083c7041 100644 --- a/examples/react/start-material-ui/package.json +++ b/examples/react/start-material-ui/package.json @@ -15,20 +15,19 @@ "@emotion/styled": "11.14.0", "@fontsource-variable/roboto": "5.2.5", "@mui/material": "6.4.7", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-start": "^1.167.2", + "@tanstack/react-router-devtools": "^1.166.10", "react": "^19.0.0", "react-dom": "^19.0.0", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { "@types/node": "^22.5.4", "@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" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/react/start-material-ui/src/routeTree.gen.ts b/examples/react/start-material-ui/src/routeTree.gen.ts index d89758e684..421daf2790 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 IndexRouteImport } from './routes/index' import { Route as AboutRouteImport } from './routes/about' +import { Route as IndexRouteImport } from './routes/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const AboutRoute = AboutRouteImport.update({ id: '/about', path: '/about', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/about': { id: '/about' path: '/about' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AboutRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/react/start-material-ui/src/router.tsx b/examples/react/start-material-ui/src/router.tsx index 6f82cbf378..a464233af9 100644 --- a/examples/react/start-material-ui/src/router.tsx +++ b/examples/react/start-material-ui/src/router.tsx @@ -5,9 +5,7 @@ export function getRouter() { const router = createRouter({ routeTree, defaultPreload: 'intent', - defaultErrorComponent: (err) => ( -

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

- ), + defaultErrorComponent: (err) =>

{err.error.stack}

, defaultNotFoundComponent: () =>

not found

, scrollRestoration: true, }) diff --git a/examples/react/start-material-ui/tsconfig.json b/examples/react/start-material-ui/tsconfig.json index af81492efb..b3a2d67dfa 100644 --- a/examples/react/start-material-ui/tsconfig.json +++ b/examples/react/start-material-ui/tsconfig.json @@ -13,6 +13,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/react/start-next-migration/.gitignore b/examples/react/start-next-migration/.gitignore deleted file mode 100644 index 24e8148a7d..0000000000 --- a/examples/react/start-next-migration/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -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 deleted file mode 100644 index 03bb53244e..0000000000 --- a/examples/react/start-next-migration/README.md +++ /dev/null @@ -1,61 +0,0 @@ -# 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 deleted file mode 100644 index 7073518994..0000000000 --- a/examples/react/start-next-migration/next-app/account.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 325a4de176..0000000000 --- a/examples/react/start-next-migration/next-app/app/actions.ts +++ /dev/null @@ -1,36 +0,0 @@ -'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 deleted file mode 100644 index 2aafe653dd..0000000000 --- a/examples/react/start-next-migration/next-app/app/layout.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 41347eb65b..0000000000 --- a/examples/react/start-next-migration/next-app/app/login/form.tsx +++ /dev/null @@ -1,25 +0,0 @@ -'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 deleted file mode 100644 index 9cbb900629..0000000000 --- a/examples/react/start-next-migration/next-app/app/login/page.tsx +++ /dev/null @@ -1,13 +0,0 @@ -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 deleted file mode 100644 index 5da341bf43..0000000000 --- a/examples/react/start-next-migration/next-app/app/not-found.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 75653b8344..0000000000 --- a/examples/react/start-next-migration/next-app/app/page.tsx +++ /dev/null @@ -1,37 +0,0 @@ -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 deleted file mode 100644 index 36ed5b62da..0000000000 --- a/examples/react/start-next-migration/next-app/app/posts/[slug]/page.tsx +++ /dev/null @@ -1,36 +0,0 @@ -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 deleted file mode 100644 index 5310dbc37e..0000000000 --- a/examples/react/start-next-migration/next-app/app/saved/page.tsx +++ /dev/null @@ -1,28 +0,0 @@ -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 deleted file mode 100644 index 9859cffa17..0000000000 --- a/examples/react/start-next-migration/next-app/app/sitemap.ts +++ /dev/null @@ -1,7 +0,0 @@ -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 deleted file mode 100644 index 2a9d15c1c0..0000000000 --- a/examples/react/start-next-migration/next-app/content.ts +++ /dev/null @@ -1,15 +0,0 @@ -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 deleted file mode 100644 index dc72c3ae72..0000000000 --- a/examples/react/start-next-migration/next-app/next.config.ts +++ /dev/null @@ -1,13 +0,0 @@ -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 deleted file mode 100644 index 8786ab9834..0000000000 --- a/examples/react/start-next-migration/next-app/tsconfig.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "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 deleted file mode 100644 index 0c2a2a9563..0000000000 --- a/examples/react/start-next-migration/package.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "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 deleted file mode 100644 index ce48715df4..0000000000 --- a/examples/react/start-next-migration/playwright.config.ts +++ /dev/null @@ -1,30 +0,0 @@ -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 deleted file mode 100644 index 2a9d15c1c0..0000000000 --- a/examples/react/start-next-migration/src/content.ts +++ /dev/null @@ -1,15 +0,0 @@ -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 deleted file mode 100644 index 15eeafce02..0000000000 --- a/examples/react/start-next-migration/src/routeTree.gen.ts +++ /dev/null @@ -1,167 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 9711e610bf..0000000000 --- a/examples/react/start-next-migration/src/router.tsx +++ /dev/null @@ -1,5 +0,0 @@ -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 deleted file mode 100644 index a7eaa0168f..0000000000 --- a/examples/react/start-next-migration/src/routes/__root.tsx +++ /dev/null @@ -1,46 +0,0 @@ -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 deleted file mode 100644 index 8778d9d01f..0000000000 --- a/examples/react/start-next-migration/src/routes/index.tsx +++ /dev/null @@ -1,45 +0,0 @@ -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 deleted file mode 100644 index 628261cc8e..0000000000 --- a/examples/react/start-next-migration/src/routes/login.tsx +++ /dev/null @@ -1,70 +0,0 @@ -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 deleted file mode 100644 index 1fb5ce846b..0000000000 --- a/examples/react/start-next-migration/src/routes/old-notes.tsx +++ /dev/null @@ -1,10 +0,0 @@ -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 deleted file mode 100644 index 1998717393..0000000000 --- a/examples/react/start-next-migration/src/routes/posts.$slug.tsx +++ /dev/null @@ -1,34 +0,0 @@ -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 deleted file mode 100644 index 2f526eb7b5..0000000000 --- a/examples/react/start-next-migration/src/routes/saved.tsx +++ /dev/null @@ -1,79 +0,0 @@ -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 deleted file mode 100644 index a7dfcaa594..0000000000 --- a/examples/react/start-next-migration/src/routes/sitemap[.]xml.ts +++ /dev/null @@ -1,13 +0,0 @@ -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 deleted file mode 100644 index 85e921c74b..0000000000 --- a/examples/react/start-next-migration/src/server/account.ts +++ /dev/null @@ -1,77 +0,0 @@ -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 deleted file mode 100644 index 5fb1e247fb..0000000000 --- a/examples/react/start-next-migration/src/start.ts +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 7009095977..0000000000 --- a/examples/react/start-next-migration/tests/migration.spec.ts +++ /dev/null @@ -1,163 +0,0 @@ -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 deleted file mode 100644 index a41553b9a1..0000000000 --- a/examples/react/start-next-migration/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "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 deleted file mode 100644 index 26d0e455d5..0000000000 --- a/examples/react/start-next-migration/vite.config.ts +++ /dev/null @@ -1,5 +0,0 @@ -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 deleted file mode 100644 index 6ab0517d9f..0000000000 --- a/examples/react/start-rscs/.gitignore +++ /dev/null @@ -1,20 +0,0 @@ -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/.vscode/settings.json b/examples/react/start-rscs/.vscode/settings.json deleted file mode 100644 index 00b5278e58..0000000000 --- a/examples/react/start-rscs/.vscode/settings.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "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 deleted file mode 100644 index e47983c58e..0000000000 --- a/examples/react/start-rscs/README.md +++ /dev/null @@ -1,36 +0,0 @@ -# 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 deleted file mode 100644 index 00c88681d7..0000000000 --- a/examples/react/start-rscs/package.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "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-rscs/public/example-guitar-flowers.jpg b/examples/react/start-rscs/public/example-guitar-flowers.jpg deleted file mode 100644 index debe785efe..0000000000 Binary files a/examples/react/start-rscs/public/example-guitar-flowers.jpg and /dev/null differ diff --git a/examples/react/start-rscs/public/example-guitar-motherboard.jpg b/examples/react/start-rscs/public/example-guitar-motherboard.jpg deleted file mode 100644 index 8f1a8d72f8..0000000000 Binary files a/examples/react/start-rscs/public/example-guitar-motherboard.jpg and /dev/null differ diff --git a/examples/react/start-rscs/public/example-guitar-racing.jpg b/examples/react/start-rscs/public/example-guitar-racing.jpg deleted file mode 100644 index 44555574c4..0000000000 Binary files a/examples/react/start-rscs/public/example-guitar-racing.jpg and /dev/null 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 deleted file mode 100644 index 7b93189397..0000000000 Binary files a/examples/react/start-rscs/public/example-guitar-steamer-trunk.jpg and /dev/null differ diff --git a/examples/react/start-rscs/public/example-guitar-superhero.jpg b/examples/react/start-rscs/public/example-guitar-superhero.jpg deleted file mode 100644 index 3bbea2743d..0000000000 Binary files a/examples/react/start-rscs/public/example-guitar-superhero.jpg and /dev/null differ diff --git a/examples/react/start-rscs/public/example-ukelele-tanstack.jpg b/examples/react/start-rscs/public/example-ukelele-tanstack.jpg deleted file mode 100644 index 1e8a556696..0000000000 Binary files a/examples/react/start-rscs/public/example-ukelele-tanstack.jpg and /dev/null differ diff --git a/examples/react/start-rscs/src/components/Layout.tsx b/examples/react/start-rscs/src/components/Layout.tsx deleted file mode 100644 index ff0dafa9df..0000000000 --- a/examples/react/start-rscs/src/components/Layout.tsx +++ /dev/null @@ -1,139 +0,0 @@ -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 deleted file mode 100644 index 79c3a44e61..0000000000 --- a/examples/react/start-rscs/src/e-Commerce/components/AddToCartButton.tsx +++ /dev/null @@ -1,86 +0,0 @@ -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 deleted file mode 100644 index 5b719dfd52..0000000000 --- a/examples/react/start-rscs/src/e-Commerce/components/AlsoBoughtCarousel.tsx +++ /dev/null @@ -1,94 +0,0 @@ -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 deleted file mode 100644 index 35542557fd..0000000000 --- a/examples/react/start-rscs/src/e-Commerce/components/Header.tsx +++ /dev/null @@ -1,62 +0,0 @@ -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 deleted file mode 100644 index a1c3bf845b..0000000000 --- a/examples/react/start-rscs/src/e-Commerce/components/StreamingComments.tsx +++ /dev/null @@ -1,117 +0,0 @@ -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 deleted file mode 100644 index 3e34aa8d27..0000000000 --- a/examples/react/start-rscs/src/e-Commerce/server-functions.tsx +++ /dev/null @@ -1,257 +0,0 @@ -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 deleted file mode 100644 index 20c3c53f59..0000000000 --- a/examples/react/start-rscs/src/e-Commerce/store/cartStore.ts +++ /dev/null @@ -1,79 +0,0 @@ -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 deleted file mode 100644 index 123944781c..0000000000 --- a/examples/react/start-rscs/src/home/server-functions.tsx +++ /dev/null @@ -1,102 +0,0 @@ -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 deleted file mode 100644 index 004921dbc4..0000000000 --- a/examples/react/start-rscs/src/low-level/components/DemoSection.tsx +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index d2278947d9..0000000000 --- a/examples/react/start-rscs/src/low-level/components/dexie-cache/DexieCacheDemo.tsx +++ /dev/null @@ -1,199 +0,0 @@ -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 deleted file mode 100644 index 0226aa57e1..0000000000 --- a/examples/react/start-rscs/src/low-level/components/dexie-cache/server-functions.tsx +++ /dev/null @@ -1,76 +0,0 @@ -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 deleted file mode 100644 index 781ddb0bfe..0000000000 --- a/examples/react/start-rscs/src/low-level/components/direct-flight/DirectFlightStreamDemo.tsx +++ /dev/null @@ -1,56 +0,0 @@ -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 deleted file mode 100644 index c7ba42ffb6..0000000000 --- a/examples/react/start-rscs/src/low-level/components/direct-flight/server-functions.tsx +++ /dev/null @@ -1,34 +0,0 @@ -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 deleted file mode 100644 index d49d8988db..0000000000 --- a/examples/react/start-rscs/src/low-level/components/fetch-flight/FetchFlightStreamDemo.tsx +++ /dev/null @@ -1,41 +0,0 @@ -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 deleted file mode 100644 index 4bc5ab339d..0000000000 --- a/examples/react/start-rscs/src/low-level/components/nested-suspense/NestedSuspenseDemo.tsx +++ /dev/null @@ -1,45 +0,0 @@ -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 deleted file mode 100644 index 9b40b68c25..0000000000 --- a/examples/react/start-rscs/src/low-level/components/nested-suspense/server-functions.tsx +++ /dev/null @@ -1,59 +0,0 @@ -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 deleted file mode 100644 index 14500905c1..0000000000 --- a/examples/react/start-rscs/src/low-level/components/parallel-streams/ParallelStreamsDemo.tsx +++ /dev/null @@ -1,98 +0,0 @@ -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 deleted file mode 100644 index 3e5e9628b6..0000000000 --- a/examples/react/start-rscs/src/low-level/components/parallel-streams/server-functions.tsx +++ /dev/null @@ -1,37 +0,0 @@ -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 deleted file mode 100644 index 109187ee87..0000000000 --- a/examples/react/start-rscs/src/low-level/components/streaming-ticker/StreamingTicker.tsx +++ /dev/null @@ -1,152 +0,0 @@ -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 deleted file mode 100644 index 2525b06f26..0000000000 --- a/examples/react/start-rscs/src/low-level/components/streaming-ticker/server-functions.tsx +++ /dev/null @@ -1,91 +0,0 @@ -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 deleted file mode 100644 index 1c50f67f82..0000000000 --- a/examples/react/start-rscs/src/low-level/db.ts +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index 1f575e2c0b..0000000000 --- a/examples/react/start-rscs/src/low-level/index.ts +++ /dev/null @@ -1,29 +0,0 @@ -// 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 deleted file mode 100644 index e458cac948..0000000000 --- a/examples/react/start-rscs/src/pokemon/Button.tsx +++ /dev/null @@ -1,19 +0,0 @@ -'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 deleted file mode 100644 index 37aa33a7c2..0000000000 --- a/examples/react/start-rscs/src/pokemon/server-functions.tsx +++ /dev/null @@ -1,139 +0,0 @@ -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 deleted file mode 100644 index d89ab3d3e7..0000000000 --- a/examples/react/start-rscs/src/routeTree.gen.ts +++ /dev/null @@ -1,177 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 deleted file mode 100644 index 335a55600f..0000000000 --- a/examples/react/start-rscs/src/router.tsx +++ /dev/null @@ -1,11 +0,0 @@ -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 deleted file mode 100644 index 80891bd2ee..0000000000 --- a/examples/react/start-rscs/src/routes/__root.tsx +++ /dev/null @@ -1,44 +0,0 @@ -/// -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 deleted file mode 100644 index e2c9aeccd4..0000000000 --- a/examples/react/start-rscs/src/routes/api/rsc.tsx +++ /dev/null @@ -1,43 +0,0 @@ -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 deleted file mode 100644 index eb215d256c..0000000000 --- a/examples/react/start-rscs/src/routes/e-commerce.tsx +++ /dev/null @@ -1,48 +0,0 @@ -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 deleted file mode 100644 index 244bb4ca1d..0000000000 --- a/examples/react/start-rscs/src/routes/index.tsx +++ /dev/null @@ -1,71 +0,0 @@ -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 deleted file mode 100644 index 58ccf6d1ad..0000000000 --- a/examples/react/start-rscs/src/routes/low-level-api.tsx +++ /dev/null @@ -1,82 +0,0 @@ -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 deleted file mode 100644 index a654c1f3a5..0000000000 --- a/examples/react/start-rscs/src/routes/pokemon-rsc.tsx +++ /dev/null @@ -1,52 +0,0 @@ -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 deleted file mode 100644 index e4cffba044..0000000000 --- a/examples/react/start-rscs/src/routes/pokemon.tsx +++ /dev/null @@ -1,105 +0,0 @@ -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/examples/react/start-rscs/src/styles/app.css b/examples/react/start-rscs/src/styles/app.css deleted file mode 100644 index c36c737cd4..0000000000 --- a/examples/react/start-rscs/src/styles/app.css +++ /dev/null @@ -1,30 +0,0 @@ -@import 'tailwindcss'; - -@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-rscs/tsconfig.json b/examples/react/start-rscs/tsconfig.json deleted file mode 100644 index 8554925771..0000000000 --- a/examples/react/start-rscs/tsconfig.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "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 deleted file mode 100644 index 3fffc19f6d..0000000000 --- a/examples/react/start-rscs/vite.config.ts +++ /dev/null @@ -1,24 +0,0 @@ -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/package.json b/examples/react/start-streaming-data-from-server-functions/package.json index 762bbff733..2fbae64edb 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,19 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", + "@tanstack/react-start": "^1.167.2", "react": "^19.0.0", "react-dom": "^19.0.0", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { "@types/node": "^22.5.4", "@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" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } 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 6f82cbf378..a464233af9 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,9 +5,7 @@ export function getRouter() { const router = createRouter({ routeTree, defaultPreload: 'intent', - defaultErrorComponent: (err) => ( -

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

- ), + defaultErrorComponent: (err) =>

{err.error.stack}

, 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 af81492efb..b3a2d67dfa 100644 --- a/examples/react/start-streaming-data-from-server-functions/tsconfig.json +++ b/examples/react/start-streaming-data-from-server-functions/tsconfig.json @@ -13,6 +13,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/react/start-supabase-basic/.gitignore b/examples/react/start-supabase-basic/.gitignore index 372dc30373..8293849e8d 100644 --- a/examples/react/start-supabase-basic/.gitignore +++ b/examples/react/start-supabase-basic/.gitignore @@ -1,11 +1,12 @@ node_modules +# Keep environment variables out of version control +!.env package-lock.json yarn.lock .DS_Store .cache -# The checked-in .env contains public demo values used by the build. -!.env +.env .vercel .output /build/ diff --git a/examples/react/start-supabase-basic/package.json b/examples/react/start-supabase-basic/package.json index 0bf4b2c246..6cb67740e7 100644 --- a/examples/react/start-supabase-basic/package.json +++ b/examples/react/start-supabase-basic/package.json @@ -15,9 +15,9 @@ "dependencies": { "@supabase/ssr": "^0.5.2", "@supabase/supabase-js": "^2.48.1", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", + "@tanstack/react-start": "^1.167.2", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1" @@ -28,8 +28,7 @@ "@types/react-dom": "^19.0.3", "@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" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/react/start-supabase-basic/src/components/DefaultCatchBoundary.tsx b/examples/react/start-supabase-basic/src/components/DefaultCatchBoundary.tsx index 405fb5f4a7..30e64b85b9 100644 --- a/examples/react/start-supabase-basic/src/components/DefaultCatchBoundary.tsx +++ b/examples/react/start-supabase-basic/src/components/DefaultCatchBoundary.tsx @@ -1,15 +1,18 @@ +import * as React from 'react' import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, 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 === '/', + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, }) 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 998d34a709..6be84444eb 100644 --- a/examples/react/start-supabase-basic/src/routeTree.gen.ts +++ b/examples/react/start-supabase-basic/src/routeTree.gen.ts @@ -9,27 +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 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 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 AuthedPostsRouteImport } from './routes/_authed/posts' import { Route as AuthedPostsIndexRouteImport } from './routes/_authed/posts.index' import { Route as AuthedPostsPostIdRouteImport } from './routes/_authed/posts.$postId' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const AuthedRoute = AuthedRouteImport.update({ - id: '/_authed', - getParentRoute: () => rootRouteImport, -} as any) -const LoginRoute = LoginRouteImport.update({ - id: '/login', - path: '/login', +const SignupRoute = SignupRouteImport.update({ + id: '/signup', + path: '/signup', getParentRoute: () => rootRouteImport, } as any) const LogoutRoute = LogoutRouteImport.update({ @@ -37,9 +28,18 @@ const LogoutRoute = LogoutRouteImport.update({ path: '/logout', getParentRoute: () => rootRouteImport, } as any) -const SignupRoute = SignupRouteImport.update({ - id: '/signup', - path: '/signup', +const LoginRoute = LoginRouteImport.update({ + id: '/login', + path: '/login', + getParentRoute: () => rootRouteImport, +} as any) +const AuthedRoute = AuthedRouteImport.update({ + id: '/_authed', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AuthedPostsRoute = AuthedPostsRouteImport.update({ @@ -120,25 +120,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_authed': { - id: '/_authed' - path: '' - fullPath: '/' - preLoaderRoute: typeof AuthedRouteImport - parentRoute: typeof rootRouteImport - } - '/login': { - id: '/login' - path: '/login' - fullPath: '/login' - preLoaderRoute: typeof LoginRouteImport + '/signup': { + id: '/signup' + path: '/signup' + fullPath: '/signup' + preLoaderRoute: typeof SignupRouteImport parentRoute: typeof rootRouteImport } '/logout': { @@ -148,11 +134,25 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof LogoutRouteImport parentRoute: typeof rootRouteImport } - '/signup': { - id: '/signup' - path: '/signup' - fullPath: '/signup' - preLoaderRoute: typeof SignupRouteImport + '/login': { + id: '/login' + path: '/login' + fullPath: '/login' + preLoaderRoute: typeof LoginRouteImport + parentRoute: typeof rootRouteImport + } + '/_authed': { + id: '/_authed' + path: '' + fullPath: '/' + preLoaderRoute: typeof AuthedRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport 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 697e35e427..f6edff63c1 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' }) - .validator((d: { email: string; password: string }) => d) + .inputValidator((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 instanceof Error && error.message === 'Not authenticated') { + if (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 d7c0060084..908d8ffcb3 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' }) - .validator( + .inputValidator( (d: { email: string; password: string; redirectUrl?: string }) => d, ) .handler(async ({ data }) => { diff --git a/examples/react/start-supabase-basic/src/utils/posts.ts b/examples/react/start-supabase-basic/src/utils/posts.ts index 5512187e92..297beefeb7 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' }) - .validator((d: string) => d) + .inputValidator((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 cef9369516..3a9fb7cd71 100644 --- a/examples/react/start-supabase-basic/tsconfig.json +++ b/examples/react/start-supabase-basic/tsconfig.json @@ -13,6 +13,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/react/start-tailwind-v4/package.json b/examples/react/start-tailwind-v4/package.json index b58fbe4ff0..61232a810a 100644 --- a/examples/react/start-tailwind-v4/package.json +++ b/examples/react/start-tailwind-v4/package.json @@ -10,13 +10,13 @@ "start": "node .output/server/index.mjs" }, "dependencies": { - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", + "@tanstack/react-start": "^1.167.2", "react": "^19.0.0", "react-dom": "^19.0.0", - "tailwind-merge": "^3.6.0", - "zod": "^4.4.3" + "tailwind-merge": "^2.6.0", + "zod": "^3.24.2" }, "devDependencies": { "@tailwindcss/vite": "^4.2.2", @@ -25,8 +25,7 @@ "@types/react-dom": "^19.0.3", "@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" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/react/start-tailwind-v4/tsconfig.json b/examples/react/start-tailwind-v4/tsconfig.json index cef9369516..3a9fb7cd71 100644 --- a/examples/react/start-tailwind-v4/tsconfig.json +++ b/examples/react/start-tailwind-v4/tsconfig.json @@ -13,6 +13,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/react/start-trellaux/package.json b/examples/react/start-trellaux/package.json index 7755d227fc..7a76758fe8 100644 --- a/examples/react/start-trellaux/package.json +++ b/examples/react/start-trellaux/package.json @@ -10,20 +10,21 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/react-query": "^5.102.0", + "@tanstack/react-query": "^5.90.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-router-ssr-query": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", + "@tanstack/react-router-ssr-query": "^1.166.10", + "@tanstack/react-start": "^1.167.2", "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": "^3.6.0", - "zod": "^4.4.3" + "tailwind-merge": "^2.6.0", + "tiny-invariant": "^1.3.3", + "zod": "^3.24.2" }, "devDependencies": { "@tailwindcss/vite": "^4.2.2", @@ -32,8 +33,7 @@ "@types/react-dom": "^19.0.3", "@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" + "typescript": "^5.6.2", + "vite": "^8.0.0" } } diff --git a/examples/react/start-trellaux/src/components/Board.tsx b/examples/react/start-trellaux/src/components/Board.tsx index 0ba9a3c288..0b43e1d923 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 '../invariant' +import invariant from 'tiny-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 729b93d2f8..6c73ca079f 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 '../invariant' +import invariant from 'tiny-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 a95faedb54..f9fddaaf5f 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 4a22649ed4..260c2ea41f 100644 --- a/examples/react/start-trellaux/src/components/DefaultCatchBoundary.tsx +++ b/examples/react/start-trellaux/src/components/DefaultCatchBoundary.tsx @@ -1,15 +1,17 @@ import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, 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 === '/', + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, }) 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 b46f965c8b..8201083bb3 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 '../invariant' +import invariant from 'tiny-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 655b380743..acb6c82cfb 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 '../invariant' +import invariant from 'tiny-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 91ec369936..92f94967e9 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 '../invariant' +import invariant from 'tiny-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' }) - .validator(z.string()) + .inputValidator(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() - .validator(newColumnSchema) + .inputValidator(newColumnSchema) .handler(async ({ data }) => { await delay(DELAY) const newColumn = newColumnSchema.parse(data) @@ -62,7 +62,7 @@ export const createColumn = createServerFn() }) export const createItem = createServerFn() - .validator(itemSchema) + .inputValidator(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' }) - .validator(deleteItemSchema) + .inputValidator(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() - .validator(itemSchema) + .inputValidator(itemSchema) .handler(async ({ data }) => { await delay(DELAY) const item = itemSchema.parse(data) @@ -97,7 +97,7 @@ export const updateItem = createServerFn() }) export const updateColumn = createServerFn() - .validator(updateColumnSchema) + .inputValidator(updateColumnSchema) .handler(async ({ data }) => { await delay(DELAY) const column = updateColumnSchema.parse(data) @@ -109,7 +109,7 @@ export const updateColumn = createServerFn() }) export const updateBoard = createServerFn() - .validator(updateBoardSchema) + .inputValidator(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' }) - .validator(deleteColumnSchema) + .inputValidator(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 5fe4da32fa..52c3587703 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 deleted file mode 100644 index 41fcded35e..0000000000 --- a/examples/react/start-trellaux/src/invariant.ts +++ /dev/null @@ -1,5 +0,0 @@ -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/utils/posts.tsx b/examples/react/start-trellaux/src/utils/posts.tsx index e87764806d..cf602f9827 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' }) - .validator((postId: string) => postId) + .inputValidator((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 cef9369516..3a9fb7cd71 100644 --- a/examples/react/start-trellaux/tsconfig.json +++ b/examples/react/start-trellaux/tsconfig.json @@ -13,6 +13,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/react/start-workos/README.md b/examples/react/start-workos/README.md index 52dde9410a..d6e222c7ba 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/api/auth/callback + WORKOS_REDIRECT_URI=http://localhost:3000/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 0ab7e89c2d..199298251b 100644 --- a/examples/react/start-workos/package.json +++ b/examples/react/start-workos/package.json @@ -14,9 +14,9 @@ "license": "MIT", "dependencies": { "@radix-ui/themes": "^3.3.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", + "@tanstack/react-start": "^1.167.2", "@workos/authkit-tanstack-react-start": "^0.5.0", "react": "^19.0.0", "react-dom": "^19.0.0" @@ -25,8 +25,7 @@ "@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" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/react/start-workos/src/routeTree.gen.ts b/examples/react/start-workos/src/routeTree.gen.ts index 559db280de..49009fc848 100644 --- a/examples/react/start-workos/src/routeTree.gen.ts +++ b/examples/react/start-workos/src/routeTree.gen.ts @@ -9,20 +9,16 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as AuthenticatedRouteImport } from './routes/_authenticated' -import { Route as ClientRouteImport } from './routes/client' import { Route as LogoutRouteImport } from './routes/logout' +import { Route as ClientRouteImport } from './routes/client' +import { Route as AuthenticatedRouteImport } from './routes/_authenticated' +import { Route as IndexRouteImport } from './routes/index' import { Route as AuthenticatedAccountRouteImport } from './routes/_authenticated/account' import { Route as ApiAuthCallbackRouteImport } from './routes/api/auth/callback' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const AuthenticatedRoute = AuthenticatedRouteImport.update({ - id: '/_authenticated', +const LogoutRoute = LogoutRouteImport.update({ + id: '/logout', + path: '/logout', getParentRoute: () => rootRouteImport, } as any) const ClientRoute = ClientRouteImport.update({ @@ -30,9 +26,13 @@ const ClientRoute = ClientRouteImport.update({ path: '/client', getParentRoute: () => rootRouteImport, } as any) -const LogoutRoute = LogoutRouteImport.update({ - id: '/logout', - path: '/logout', +const AuthenticatedRoute = AuthenticatedRouteImport.update({ + id: '/_authenticated', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AuthenticatedAccountRoute = AuthenticatedAccountRouteImport.update({ @@ -94,18 +94,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_authenticated': { - id: '/_authenticated' - path: '' - fullPath: '/' - preLoaderRoute: typeof AuthenticatedRouteImport + '/logout': { + id: '/logout' + path: '/logout' + fullPath: '/logout' + preLoaderRoute: typeof LogoutRouteImport parentRoute: typeof rootRouteImport } '/client': { @@ -115,11 +108,18 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ClientRouteImport parentRoute: typeof rootRouteImport } - '/logout': { - id: '/logout' - path: '/logout' - fullPath: '/logout' - preLoaderRoute: typeof LogoutRouteImport + '/_authenticated': { + id: '/_authenticated' + path: '' + fullPath: '/' + preLoaderRoute: typeof AuthenticatedRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_authenticated/account': { diff --git a/examples/react/view-transitions/package.json b/examples/react/view-transitions/package.json index 0be3c60e8f..08edfa06c1 100644 --- a/examples/react/view-transitions/package.json +++ b/examples/react/view-transitions/package.json @@ -10,21 +10,20 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", + "@tanstack/router-plugin": "^1.167.2", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { "@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" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/react/view-transitions/src/routeTree.gen.ts b/examples/react/view-transitions/src/routeTree.gen.ts index 8982fca68f..20ee76a1a5 100644 --- a/examples/react/view-transitions/src/routeTree.gen.ts +++ b/examples/react/view-transitions/src/routeTree.gen.ts @@ -9,16 +9,16 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as ExploreRouteImport } from './routes/explore' 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 PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const HowItWorksRoute = HowItWorksRouteImport.update({ + id: '/how-it-works', + path: '/how-it-works', 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 { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/how-it-works': { + id: '/how-it-works' + path: '/how-it-works' + fullPath: '/how-it-works' + preLoaderRoute: typeof HowItWorksRouteImport parentRoute: typeof rootRouteImport } '/explore': { @@ -115,13 +115,6 @@ 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' @@ -129,6 +122,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } '/posts/': { id: '/posts/' path: '/' diff --git a/examples/react/view-transitions/src/routes/explore.tsx b/examples/react/view-transitions/src/routes/explore.tsx index b70a6f3bd5..1bb60ed1fc 100644 --- a/examples/react/view-transitions/src/routes/explore.tsx +++ b/examples/react/view-transitions/src/routes/explore.tsx @@ -1,4 +1,5 @@ -import { Link, createFileRoute } from '@tanstack/react-router' +import { createFileRoute } from '@tanstack/react-router' +import { Link } from '@tanstack/react-router' export const Route = createFileRoute('/explore')({ component: RouteComponent, diff --git a/examples/react/view-transitions/src/routes/how-it-works.tsx b/examples/react/view-transitions/src/routes/how-it-works.tsx index ab4dd4c714..3ae9a88d52 100644 --- a/examples/react/view-transitions/src/routes/how-it-works.tsx +++ b/examples/react/view-transitions/src/routes/how-it-works.tsx @@ -1,4 +1,5 @@ -import { Link, createFileRoute } from '@tanstack/react-router' +import { createFileRoute } from '@tanstack/react-router' +import { Link } from '@tanstack/react-router' export const Route = createFileRoute('/how-it-works')({ component: RouteComponent, diff --git a/examples/react/view-transitions/src/routes/index.tsx b/examples/react/view-transitions/src/routes/index.tsx index 132ba18dbb..19f597dc7b 100644 --- a/examples/react/view-transitions/src/routes/index.tsx +++ b/examples/react/view-transitions/src/routes/index.tsx @@ -1,5 +1,6 @@ +import { createFileRoute } from '@tanstack/react-router' import * as React from 'react' -import { Link, createFileRoute } from '@tanstack/react-router' +import { Link } from '@tanstack/react-router' export const Route = createFileRoute('/')({ component: Home, diff --git a/examples/react/view-transitions/src/routes/posts.$postId.tsx b/examples/react/view-transitions/src/routes/posts.$postId.tsx index cded91ef96..956ca50ecd 100644 --- a/examples/react/view-transitions/src/routes/posts.$postId.tsx +++ b/examples/react/view-transitions/src/routes/posts.$postId.tsx @@ -1,5 +1,6 @@ +import { createFileRoute } from '@tanstack/react-router' import * as React from 'react' -import { ErrorComponent, createFileRoute } from '@tanstack/react-router' +import { ErrorComponent } from '@tanstack/react-router' import { fetchPost } from '../posts' import type { ErrorComponentProps } from '@tanstack/react-router' diff --git a/examples/react/view-transitions/src/routes/posts.index.tsx b/examples/react/view-transitions/src/routes/posts.index.tsx index 056433ca0a..c6b65f1892 100644 --- a/examples/react/view-transitions/src/routes/posts.index.tsx +++ b/examples/react/view-transitions/src/routes/posts.index.tsx @@ -1,5 +1,5 @@ -import * as React from 'react' import { createFileRoute } from '@tanstack/react-router' +import * as React from 'react' export const Route = createFileRoute('/posts/')({ component: PostsIndexComponent, diff --git a/examples/react/view-transitions/src/routes/posts.route.tsx b/examples/react/view-transitions/src/routes/posts.route.tsx index 4612ed3d5d..88296c3c54 100644 --- a/examples/react/view-transitions/src/routes/posts.route.tsx +++ b/examples/react/view-transitions/src/routes/posts.route.tsx @@ -1,10 +1,6 @@ +import { createFileRoute } from '@tanstack/react-router' import * as React from 'react' -import { - Link, - Outlet, - createFileRoute, - useRouter, -} from '@tanstack/react-router' +import { Link, Outlet } from '@tanstack/react-router' import { fetchPosts } from '../posts' export const Route = createFileRoute('/posts')({ @@ -14,7 +10,6 @@ export const Route = createFileRoute('/posts')({ function PostsLayoutComponent() { const posts = Route.useLoaderData() - const router = useRouter() return (
@@ -30,30 +25,8 @@ function PostsLayoutComponent() { }} className="block py-1 text-blue-600 hover:opacity-75" activeProps={{ className: 'font-bold underline' }} - // see styles.css for 'warp' and 'warp-backwards' transition - viewTransition={{ - types: ({ fromLocation, toLocation }) => { - const fromRoute = router - .matchRoutes(fromLocation?.pathname ?? '/') - .find((entry) => entry.routeId === '/posts/$postId') - const toRoute = router - .matchRoutes(toLocation?.pathname ?? '/') - .find((entry) => entry.routeId === '/posts/$postId') - - const fromIndex = Number(fromRoute?.params.postId) - const toIndex = Number(toRoute?.params.postId) - - if ( - Number.isNaN(fromIndex) || - Number.isNaN(toIndex) || - fromIndex === toIndex - ) { - return false // no transition - } - - return fromIndex > toIndex ? ['warp-backwards'] : ['warp'] - }, - }} + // see styles.css for 'warp' transition + viewTransition={{ types: ['warp'] }} >
{post.title.substring(0, 20)}
diff --git a/examples/react/view-transitions/src/styles.css b/examples/react/view-transitions/src/styles.css index 502642b383..b51e6e1244 100644 --- a/examples/react/view-transitions/src/styles.css +++ b/examples/react/view-transitions/src/styles.css @@ -87,16 +87,6 @@ html:active-view-transition-type(warp) { } } -html:active-view-transition-type(warp-backwards) { - &::view-transition-old(post) { - animation: 400ms ease-out both warp-out-backwards; - } - - &::view-transition-new(post) { - animation: 400ms ease-out both warp-in-backwards; - } -} - @keyframes warp-out { from { opacity: 1; @@ -122,29 +112,3 @@ html:active-view-transition-type(warp-backwards) { transform: scale(1) rotate(0deg); } } - -@keyframes warp-in-backwards { - from { - opacity: 0; - filter: blur(15px) brightness(1.8); - transform: scale(0.9) rotate(45deg); - } - to { - opacity: 1; - filter: blur(0) brightness(1); - transform: scale(1) rotate(0deg); - } -} - -@keyframes warp-out-backwards { - from { - opacity: 1; - filter: blur(0) brightness(1); - transform: scale(1) rotate(0deg); - } - to { - opacity: 0; - filter: blur(15px) brightness(1.8); - transform: scale(1.1) rotate(-90deg); - } -} diff --git a/examples/react/view-transitions/src/vite-env.d.ts b/examples/react/view-transitions/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/view-transitions/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/with-framer-motion/package.json b/examples/react/with-framer-motion/package.json index c606070dfb..f6e42623df 100644 --- a/examples/react/with-framer-motion/package.json +++ b/examples/react/with-framer-motion/package.json @@ -10,21 +10,20 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", "framer-motion": "^11.18.2", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { "@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" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/react/with-framer-motion/src/vite-env.d.ts b/examples/react/with-framer-motion/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/with-framer-motion/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/with-trpc-react-query/package.json b/examples/react/with-trpc-react-query/package.json index 11df7bf03b..03b228b426 100644 --- a/examples/react/with-trpc-react-query/package.json +++ b/examples/react/with-trpc-react-query/package.json @@ -11,27 +11,27 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.102.0", + "@tanstack/react-query": "^5.90.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", + "@tanstack/router-plugin": "^1.167.2", "@trpc/client": "^11.4.3", "@trpc/server": "^11.4.3", "@trpc/tanstack-react-query": "^11.4.3", - "express": "^5.2.1", + "express": "^4.21.2", "react": "^19.1.0", "react-dom": "^19.1.0", "redaxios": "^0.5.1", "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "@types/express": "^5.0.6", + "@types/express": "^4.17.23", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "tsx": "^4.20.3", - "vite": "^8.0.14" + "vite": "^8.0.0" } } diff --git a/examples/react/with-trpc-react-query/src/routeTree.gen.ts b/examples/react/with-trpc-react-query/src/routeTree.gen.ts index 548a4b9e88..b407b58e4c 100644 --- a/examples/react/with-trpc-react-query/src/routeTree.gen.ts +++ b/examples/react/with-trpc-react-query/src/routeTree.gen.ts @@ -9,23 +9,23 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' import { Route as DashboardRouteImport } from './routes/dashboard' +import { Route as IndexRouteImport } from './routes/index' 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 IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const DashboardRoute = DashboardRouteImport.update({ id: '/dashboard', path: '/dashboard', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const DashboardIndexRoute = DashboardIndexRouteImport.update({ id: '/', path: '/', @@ -98,13 +98,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/dashboard': { id: '/dashboard' path: '/dashboard' @@ -112,6 +105,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof DashboardRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } '/dashboard/': { id: '/dashboard/' path: '/' diff --git a/examples/react/with-trpc-react-query/src/server/server.ts b/examples/react/with-trpc-react-query/src/server/server.ts index 0a580d4963..b2b3fd2485 100644 --- a/examples/react/with-trpc-react-query/src/server/server.ts +++ b/examples/react/with-trpc-react-query/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('/{*splat}', async (req, res, next) => { + app.get('*', 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('/{*splat}', (req, res) => { + app.get('*', (req, res) => { res.sendFile(path.resolve(__dirname, '../client', 'index.html')) }) } @@ -78,8 +78,7 @@ export const createServer = async ( if (!isTest) { createServer().then(({ app }) => - app.listen(PORT, (error) => { - if (error) throw error + app.listen(PORT, () => { console.info(`Server available at: http://localhost:${PORT}`) }), ) diff --git a/examples/react/with-trpc-react-query/src/vite-env.d.ts b/examples/react/with-trpc-react-query/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/with-trpc-react-query/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/with-trpc/package.json b/examples/react/with-trpc/package.json index 5612419cae..0861caa138 100644 --- a/examples/react/with-trpc/package.json +++ b/examples/react/with-trpc/package.json @@ -11,24 +11,24 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.168.1", + "@tanstack/react-router-devtools": "^1.166.10", + "@tanstack/router-plugin": "^1.167.2", "@trpc/client": "^11.4.3", "@trpc/server": "^11.4.3", - "express": "^5.2.1", + "express": "^4.21.2", "react": "^19.1.0", "react-dom": "^19.1.0", "redaxios": "^0.5.1", "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "@types/express": "^5.0.6", + "@types/express": "^4.17.23", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "tsx": "^4.20.3", - "vite": "^8.0.14" + "vite": "^8.0.0" } } diff --git a/examples/react/with-trpc/src/routeTree.gen.ts b/examples/react/with-trpc/src/routeTree.gen.ts index 548a4b9e88..b407b58e4c 100644 --- a/examples/react/with-trpc/src/routeTree.gen.ts +++ b/examples/react/with-trpc/src/routeTree.gen.ts @@ -9,23 +9,23 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' import { Route as DashboardRouteImport } from './routes/dashboard' +import { Route as IndexRouteImport } from './routes/index' 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 IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const DashboardRoute = DashboardRouteImport.update({ id: '/dashboard', path: '/dashboard', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const DashboardIndexRoute = DashboardIndexRouteImport.update({ id: '/', path: '/', @@ -98,13 +98,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/dashboard': { id: '/dashboard' path: '/dashboard' @@ -112,6 +105,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof DashboardRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } '/dashboard/': { id: '/dashboard/' path: '/' diff --git a/examples/react/with-trpc/src/server/server.ts b/examples/react/with-trpc/src/server/server.ts index 0a580d4963..b2b3fd2485 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('/{*splat}', async (req, res, next) => { + app.get('*', 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('/{*splat}', (req, res) => { + app.get('*', (req, res) => { res.sendFile(path.resolve(__dirname, '../client', 'index.html')) }) } @@ -78,8 +78,7 @@ export const createServer = async ( if (!isTest) { createServer().then(({ app }) => - app.listen(PORT, (error) => { - if (error) throw error + app.listen(PORT, () => { console.info(`Server available at: http://localhost:${PORT}`) }), ) diff --git a/examples/react/with-trpc/src/vite-env.d.ts b/examples/react/with-trpc/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/with-trpc/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/solid/authenticated-routes-firebase/README.md b/examples/solid/authenticated-routes-firebase/README.md index 65d381b34b..893ae83165 100644 --- a/examples/solid/authenticated-routes-firebase/README.md +++ b/examples/solid/authenticated-routes-firebase/README.md @@ -24,14 +24,12 @@ 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 @@ -39,3 +37,4 @@ 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 110b4d2621..cb6d67ff86 100644 --- a/examples/solid/authenticated-routes-firebase/package.json +++ b/examples/solid/authenticated-routes-firebase/package.json @@ -10,20 +10,20 @@ }, "dependencies": { "@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/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", + "@tanstack/router-plugin": "^1.166.14", "firebase": "^11.4.0", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", "redaxios": "^0.5.1", "simple-icons": "^14.9.0", - "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", - "vite-plugin-solid": "^2.11.11" + "vite-plugin-solid": "3.0.0-next.3", + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/solid/authenticated-routes-firebase/src/auth.tsx b/examples/solid/authenticated-routes-firebase/src/auth.tsx index 97337889b7..2c60816e70 100644 --- a/examples/solid/authenticated-routes-firebase/src/auth.tsx +++ b/examples/solid/authenticated-routes-firebase/src/auth.tsx @@ -19,15 +19,16 @@ export function AuthContextProvider(props: { children: Solid.JSX.Element }) { const [isInitialLoading, setIsInitialLoading] = Solid.createSignal(true) const isAuthenticated = () => !!user() - Solid.createEffect(() => { - const unsubscribe = onAuthStateChanged(auth, (user) => { - Solid.batch(() => { + Solid.createEffect( + () => undefined, + () => { + const unsubscribe = onAuthStateChanged(auth, (user) => { setUser(user) setIsInitialLoading(false) }) - }) - return () => unsubscribe() - }) + return () => unsubscribe() + }, + ) const logout = async () => { console.log('Logging out...') @@ -38,18 +39,16 @@ export function AuthContextProvider(props: { children: Solid.JSX.Element }) { const login = async (provider: AuthProvider) => { const result = await signInWithPopup(auth, provider) - Solid.batch(() => { - setUser(result.user) - setIsInitialLoading(false) - }) + setUser(result.user) + setIsInitialLoading(false) } return ( - {props.children} - + ) } diff --git a/examples/solid/authenticated-routes-firebase/src/main.tsx b/examples/solid/authenticated-routes-firebase/src/main.tsx index d8758ea388..7e750f491c 100644 --- a/examples/solid/authenticated-routes-firebase/src/main.tsx +++ b/examples/solid/authenticated-routes-firebase/src/main.tsx @@ -1,4 +1,4 @@ -import { render } from 'solid-js/web' +import { render } from '@solidjs/web' import { RouterProvider, createRouter } from '@tanstack/solid-router' import { routeTree } from './routeTree.gen' diff --git a/examples/solid/authenticated-routes-firebase/src/routeTree.gen.ts b/examples/solid/authenticated-routes-firebase/src/routeTree.gen.ts index 4b98258aea..ff0ae58ad7 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 IndexRouteImport } from './routes/index' -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 AuthRouteImport } from './routes/_auth' +import { Route as IndexRouteImport } from './routes/index' import { Route as AuthInvoicesRouteImport } from './routes/_auth.invoices' +import { Route as AuthDashboardRouteImport } from './routes/_auth.dashboard' import { Route as AuthInvoicesIndexRouteImport } from './routes/_auth.invoices.index' import { Route as AuthInvoicesInvoiceIdRouteImport } from './routes/_auth.invoices.$invoiceId' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const LoginRoute = LoginRouteImport.update({ + id: '/login', + path: '/login', getParentRoute: () => rootRouteImport, } as any) const AuthRoute = AuthRouteImport.update({ id: '/_auth', getParentRoute: () => rootRouteImport, } as any) -const LoginRoute = LoginRouteImport.update({ - id: '/login', - path: '/login', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } 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 AuthDashboardRoute = AuthDashboardRouteImport.update({ + id: '/dashboard', + path: '/dashboard', + getParentRoute: () => AuthRoute, +} as any) const AuthInvoicesIndexRoute = AuthInvoicesIndexRouteImport.update({ id: '/', path: '/', @@ -107,11 +107,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/login': { + id: '/login' + path: '/login' + fullPath: '/login' + preLoaderRoute: typeof LoginRouteImport parentRoute: typeof rootRouteImport } '/_auth': { @@ -121,20 +121,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof AuthRouteImport parentRoute: typeof rootRouteImport } - '/login': { - id: '/login' - path: '/login' - fullPath: '/login' - preLoaderRoute: typeof LoginRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/_auth/dashboard': { - id: '/_auth/dashboard' - path: '/dashboard' - fullPath: '/dashboard' - preLoaderRoute: typeof AuthDashboardRouteImport - parentRoute: typeof AuthRoute - } '/_auth/invoices': { id: '/_auth/invoices' path: '/invoices' @@ -142,6 +135,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof AuthInvoicesRouteImport parentRoute: typeof AuthRoute } + '/_auth/dashboard': { + id: '/_auth/dashboard' + path: '/dashboard' + fullPath: '/dashboard' + preLoaderRoute: typeof AuthDashboardRouteImport + parentRoute: typeof AuthRoute + } '/_auth/invoices/': { id: '/_auth/invoices/' path: '/' diff --git a/examples/solid/authenticated-routes/package.json b/examples/solid/authenticated-routes/package.json index ea7d05c902..ea55dc682c 100644 --- a/examples/solid/authenticated-routes/package.json +++ b/examples/solid/authenticated-routes/package.json @@ -10,18 +10,18 @@ }, "dependencies": { "@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/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", + "@tanstack/router-plugin": "^1.166.14", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", "redaxios": "^0.5.1", - "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", - "vite-plugin-solid": "^2.11.11" + "vite-plugin-solid": "3.0.0-next.3", + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/solid/authenticated-routes/src/auth.tsx b/examples/solid/authenticated-routes/src/auth.tsx index 292835fc1e..f598af2390 100644 --- a/examples/solid/authenticated-routes/src/auth.tsx +++ b/examples/solid/authenticated-routes/src/auth.tsx @@ -43,14 +43,17 @@ export function AuthProvider(props: { children: Solid.JSX.Element }) { setUser(username) } - Solid.createEffect(() => { - setUser(getStoredUser()) - }) + Solid.createEffect( + () => getStoredUser(), + (storedUser) => { + setUser(storedUser) + }, + ) return ( - + {props.children} - + ) } diff --git a/examples/solid/authenticated-routes/src/main.tsx b/examples/solid/authenticated-routes/src/main.tsx index b708360887..7b63807bba 100644 --- a/examples/solid/authenticated-routes/src/main.tsx +++ b/examples/solid/authenticated-routes/src/main.tsx @@ -1,4 +1,4 @@ -import { render } from 'solid-js/web' +import { render } from '@solidjs/web' import { RouterProvider, createRouter } from '@tanstack/solid-router' import { routeTree } from './routeTree.gen' diff --git a/examples/solid/authenticated-routes/src/routeTree.gen.ts b/examples/solid/authenticated-routes/src/routeTree.gen.ts index 4b98258aea..ff0ae58ad7 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 IndexRouteImport } from './routes/index' -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 AuthRouteImport } from './routes/_auth' +import { Route as IndexRouteImport } from './routes/index' import { Route as AuthInvoicesRouteImport } from './routes/_auth.invoices' +import { Route as AuthDashboardRouteImport } from './routes/_auth.dashboard' import { Route as AuthInvoicesIndexRouteImport } from './routes/_auth.invoices.index' import { Route as AuthInvoicesInvoiceIdRouteImport } from './routes/_auth.invoices.$invoiceId' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const LoginRoute = LoginRouteImport.update({ + id: '/login', + path: '/login', getParentRoute: () => rootRouteImport, } as any) const AuthRoute = AuthRouteImport.update({ id: '/_auth', getParentRoute: () => rootRouteImport, } as any) -const LoginRoute = LoginRouteImport.update({ - id: '/login', - path: '/login', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } 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 AuthDashboardRoute = AuthDashboardRouteImport.update({ + id: '/dashboard', + path: '/dashboard', + getParentRoute: () => AuthRoute, +} as any) const AuthInvoicesIndexRoute = AuthInvoicesIndexRouteImport.update({ id: '/', path: '/', @@ -107,11 +107,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/login': { + id: '/login' + path: '/login' + fullPath: '/login' + preLoaderRoute: typeof LoginRouteImport parentRoute: typeof rootRouteImport } '/_auth': { @@ -121,20 +121,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof AuthRouteImport parentRoute: typeof rootRouteImport } - '/login': { - id: '/login' - path: '/login' - fullPath: '/login' - preLoaderRoute: typeof LoginRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/_auth/dashboard': { - id: '/_auth/dashboard' - path: '/dashboard' - fullPath: '/dashboard' - preLoaderRoute: typeof AuthDashboardRouteImport - parentRoute: typeof AuthRoute - } '/_auth/invoices': { id: '/_auth/invoices' path: '/invoices' @@ -142,6 +135,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof AuthInvoicesRouteImport parentRoute: typeof AuthRoute } + '/_auth/dashboard': { + id: '/_auth/dashboard' + path: '/dashboard' + fullPath: '/dashboard' + preLoaderRoute: typeof AuthDashboardRouteImport + parentRoute: typeof AuthRoute + } '/_auth/invoices/': { id: '/_auth/invoices/' path: '/' diff --git a/examples/solid/authenticated-routes/src/vite-env.d.ts b/examples/solid/authenticated-routes/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/solid/authenticated-routes/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/solid/basic-default-search-params/package.json b/examples/solid/basic-default-search-params/package.json index 830df7b9cf..796d759d6e 100644 --- a/examples/solid/basic-default-search-params/package.json +++ b/examples/solid/basic-default-search-params/package.json @@ -4,24 +4,24 @@ "type": "module", "scripts": { "dev": "vite --port=3000", - "build": "vite build && tsc --noEmit", + "build": "vite build", "preview": "vite preview", "start": "vite" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-query": "6.0.0-alpha.1", + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", "redaxios": "^0.5.1", - "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", - "vite-plugin-solid": "^2.11.11" + "vite-plugin-solid": "3.0.0-next.3", + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/solid/basic-default-search-params/src/main.tsx b/examples/solid/basic-default-search-params/src/main.tsx index 01d37c57d0..46db430097 100644 --- a/examples/solid/basic-default-search-params/src/main.tsx +++ b/examples/solid/basic-default-search-params/src/main.tsx @@ -1,4 +1,4 @@ -import { render } from 'solid-js/web' +import { render } from '@solidjs/web' import { ErrorComponent, Link, 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 deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/solid/basic-default-search-params/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/solid/basic-devtools-panel/package.json b/examples/solid/basic-devtools-panel/package.json index e7d608f5fe..83f7f485bb 100644 --- a/examples/solid/basic-devtools-panel/package.json +++ b/examples/solid/basic-devtools-panel/package.json @@ -10,16 +10,14 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", "redaxios": "^0.5.1", - "solid-js": "^1.9.10", - "tailwindcss": "^4.2.2" - }, - "devDependencies": { - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", - "vite-plugin-solid": "^2.11.11" + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", + "tailwindcss": "^4.2.2", + "typescript": "^5.7.2", + "vite": "^8.0.0", + "vite-plugin-solid": "3.0.0-next.3" } } diff --git a/examples/solid/basic-devtools-panel/src/main.tsx b/examples/solid/basic-devtools-panel/src/main.tsx index 48d0840660..21b9650396 100644 --- a/examples/solid/basic-devtools-panel/src/main.tsx +++ b/examples/solid/basic-devtools-panel/src/main.tsx @@ -8,7 +8,7 @@ import { createRootRoute, } from '@tanstack/solid-router' import { TanStackRouterDevtoolsPanel } from '@tanstack/solid-router-devtools' -import { render } from 'solid-js/web' +import { render } from '@solidjs/web' const rootRoute = createRootRoute({ component: () => ( diff --git a/examples/solid/basic-file-based/package.json b/examples/solid/basic-file-based/package.json index 867118382e..018cbf1f4a 100644 --- a/examples/solid/basic-file-based/package.json +++ b/examples/solid/basic-file-based/package.json @@ -10,18 +10,18 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", "redaxios": "^0.5.1", - "solid-js": "^1.9.10", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "@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" + "@tanstack/router-plugin": "^1.166.14", + "typescript": "^5.7.2", + "vite": "^8.0.0", + "vite-plugin-solid": "3.0.0-next.3" } } diff --git a/examples/solid/basic-file-based/src/main.tsx b/examples/solid/basic-file-based/src/main.tsx index 8128384193..4bd8c56ef3 100644 --- a/examples/solid/basic-file-based/src/main.tsx +++ b/examples/solid/basic-file-based/src/main.tsx @@ -1,4 +1,4 @@ -import { render } from 'solid-js/web' +import { render } from '@solidjs/web' import { RouterProvider, createRouter } from '@tanstack/solid-router' import { routeTree } from './routeTree.gen' import './styles.css' diff --git a/examples/solid/basic-file-based/src/routeTree.gen.ts b/examples/solid/basic-file-based/src/routeTree.gen.ts index 5942acc907..bde5d68567 100644 --- a/examples/solid/basic-file-based/src/routeTree.gen.ts +++ b/examples/solid/basic-file-based/src/routeTree.gen.ts @@ -9,34 +9,29 @@ // Additionally, you should also exclude this file 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 PostsRouteImport } from './routes/posts' -import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' +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 PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +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' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, } as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +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: '/', @@ -47,11 +42,10 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ path: '/$postId', getParentRoute: () => PostsRoute, } as any) -const PathlessLayoutNestedLayoutRouteARoute = - PathlessLayoutNestedLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, +const PathlessLayoutNestedLayoutRoute = + PathlessLayoutNestedLayoutRouteImport.update({ + id: '/_nested-layout', + getParentRoute: () => PathlessLayoutRoute, } as any) const PathlessLayoutNestedLayoutRouteBRoute = PathlessLayoutNestedLayoutRouteBRouteImport.update({ @@ -59,6 +53,12 @@ const PathlessLayoutNestedLayoutRouteBRoute = path: '/route-b', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) +const PathlessLayoutNestedLayoutRouteARoute = + PathlessLayoutNestedLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + } as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -117,11 +117,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } '/_pathlessLayout': { @@ -131,19 +131,12 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutRouteImport parentRoute: typeof rootRouteImport } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' - path: '' + '/': { + id: '/' + path: '/' fullPath: '/' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport } '/posts/': { id: '/posts/' @@ -159,12 +152,12 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRoute } - '/_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': { + id: '/_pathlessLayout/_nested-layout' + path: '' + fullPath: '/' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -173,6 +166,13 @@ 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/vite-env.d.ts b/examples/solid/basic-file-based/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/solid/basic-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/solid/basic-non-nested-devtools/package.json b/examples/solid/basic-non-nested-devtools/package.json index c8e00ee43e..d77230a43a 100644 --- a/examples/solid/basic-non-nested-devtools/package.json +++ b/examples/solid/basic-non-nested-devtools/package.json @@ -10,18 +10,18 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", "redaxios": "^0.5.1", - "solid-js": "^1.9.10", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", "tailwindcss": "^4.2.2" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", - "vite-plugin-solid": "^2.11.11" + "typescript": "^5.7.2", + "vite": "^8.0.0", + "vite-plugin-solid": "3.0.0-next.3" } } diff --git a/examples/solid/basic-non-nested-devtools/src/main.tsx b/examples/solid/basic-non-nested-devtools/src/main.tsx index 1ee0345cc9..bc9b56cd90 100644 --- a/examples/solid/basic-non-nested-devtools/src/main.tsx +++ b/examples/solid/basic-non-nested-devtools/src/main.tsx @@ -1,4 +1,4 @@ -import { render } from 'solid-js/web' +import { render } from '@solidjs/web' import { ErrorComponent, Link, 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 deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/solid/basic-non-nested-devtools/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/solid/basic-solid-query-file-based/package.json b/examples/solid/basic-solid-query-file-based/package.json index fdb5f05f52..a4cd8331ef 100644 --- a/examples/solid/basic-solid-query-file-based/package.json +++ b/examples/solid/basic-solid-query-file-based/package.json @@ -5,26 +5,26 @@ "scripts": { "dev": "vite --port 3000", "dev:e2e": "vite", - "build": "vite build && tsc --noEmit", + "build": "vite build", "preview": "vite preview", "start": "vite" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-query-devtools": "^5.90.0", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-query": "6.0.0-alpha.1", + "@tanstack/solid-query-devtools": "6.0.0-alpha.1", + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", "redaxios": "^0.5.1", - "solid-js": "^1.9.10", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "@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" + "@tanstack/router-plugin": "^1.166.14", + "typescript": "^5.7.2", + "vite": "^8.0.0", + "vite-plugin-solid": "3.0.0-next.3" } } diff --git a/examples/solid/basic-solid-query-file-based/src/main.tsx b/examples/solid/basic-solid-query-file-based/src/main.tsx index 7f1d2165f1..6f64a152de 100644 --- a/examples/solid/basic-solid-query-file-based/src/main.tsx +++ b/examples/solid/basic-solid-query-file-based/src/main.tsx @@ -1,4 +1,4 @@ -import { render } from 'solid-js/web' +import { render } from '@solidjs/web' import { RouterProvider, createRouter } from '@tanstack/solid-router' import { QueryClient, QueryClientProvider } from '@tanstack/solid-query' import { routeTree } from './routeTree.gen' 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 5942acc907..bde5d68567 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,34 +9,29 @@ // Additionally, you should also exclude this file 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 PostsRouteImport } from './routes/posts' -import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' +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 PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +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' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, } as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +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: '/', @@ -47,11 +42,10 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ path: '/$postId', getParentRoute: () => PostsRoute, } as any) -const PathlessLayoutNestedLayoutRouteARoute = - PathlessLayoutNestedLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, +const PathlessLayoutNestedLayoutRoute = + PathlessLayoutNestedLayoutRouteImport.update({ + id: '/_nested-layout', + getParentRoute: () => PathlessLayoutRoute, } as any) const PathlessLayoutNestedLayoutRouteBRoute = PathlessLayoutNestedLayoutRouteBRouteImport.update({ @@ -59,6 +53,12 @@ const PathlessLayoutNestedLayoutRouteBRoute = path: '/route-b', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) +const PathlessLayoutNestedLayoutRouteARoute = + PathlessLayoutNestedLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + } as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -117,11 +117,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } '/_pathlessLayout': { @@ -131,19 +131,12 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutRouteImport parentRoute: typeof rootRouteImport } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' - path: '' + '/': { + id: '/' + path: '/' fullPath: '/' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport } '/posts/': { id: '/posts/' @@ -159,12 +152,12 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRoute } - '/_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': { + id: '/_pathlessLayout/_nested-layout' + path: '' + fullPath: '/' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -173,6 +166,13 @@ 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/vite-env.d.ts b/examples/solid/basic-solid-query-file-based/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/solid/basic-solid-query-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/solid/basic-solid-query/package.json b/examples/solid/basic-solid-query/package.json index 7b132b11a1..b5a52e6254 100644 --- a/examples/solid/basic-solid-query/package.json +++ b/examples/solid/basic-solid-query/package.json @@ -4,25 +4,25 @@ "type": "module", "scripts": { "dev": "vite --port 3000", - "build": "vite build && tsc --noEmit", + "build": "vite build", "preview": "vite preview", "start": "vite" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-query-devtools": "^5.90.0", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-query": "6.0.0-alpha.1", + "@tanstack/solid-query-devtools": "6.0.0-alpha.1", + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", "redaxios": "^0.5.1", - "solid-js": "^1.9.10", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", "tailwindcss": "^4.2.2" }, "devDependencies": { - "@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" + "@tanstack/router-plugin": "^1.166.14", + "typescript": "^5.7.2", + "vite": "^8.0.0", + "vite-plugin-solid": "3.0.0-next.3" } } diff --git a/examples/solid/basic-solid-query/src/main.tsx b/examples/solid/basic-solid-query/src/main.tsx index 73a4a672b5..0b51d60c01 100644 --- a/examples/solid/basic-solid-query/src/main.tsx +++ b/examples/solid/basic-solid-query/src/main.tsx @@ -15,7 +15,7 @@ import { useQuery, } from '@tanstack/solid-query' import './styles.css' -import { render } from 'solid-js/web' +import { render } from '@solidjs/web' import { SolidQueryDevtools } from '@tanstack/solid-query-devtools' import { createEffect, createMemo } from 'solid-js' import { TanStackRouterDevtools } from '@tanstack/solid-router-devtools' diff --git a/examples/solid/basic-solid-query/src/vite-env.d.ts b/examples/solid/basic-solid-query/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/solid/basic-solid-query/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/solid/basic-ssr-file-based/package.json b/examples/solid/basic-ssr-file-based/package.json index e3699970a9..ebc35efd75 100644 --- a/examples/solid/basic-ssr-file-based/package.json +++ b/examples/solid/basic-ssr-file-based/package.json @@ -11,20 +11,20 @@ "debug": "node --inspect-brk server" }, "dependencies": { - "@tanstack/solid-router": "^1.170.43", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/router-plugin": "^1.166.14", "compression": "^1.8.0", - "express": "^5.2.1", + "express": "^4.21.2", "get-port": "^7.1.0", "node-fetch": "^3.3.2", - "solid-js": "^1.9.10" + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4" }, "devDependencies": { - "@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" + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", + "@types/express": "^4.17.23", + "vite-plugin-solid": "3.0.0-next.3", + "typescript": "^5.8.3", + "vite": "^8.0.0" } } diff --git a/examples/solid/basic-ssr-file-based/server.js b/examples/solid/basic-ssr-file-based/server.js index 6d060a19f0..5686edc048 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('/{*splat}', async (req, res) => { + app.use('*', async (req, res) => { try { const url = req.originalUrl @@ -97,8 +97,7 @@ export async function createServer( if (!isTest) { createServer().then(async ({ app }) => - app.listen(await getPort({ port: portNumbers(3000, 3100) }), (error) => { - if (error) throw error + app.listen(await getPort({ port: portNumbers(3000, 3100) }), () => { console.info('Client Server: http://localhost:3000') }), ) diff --git a/examples/solid/basic-ssr-file-based/src/entry-client.tsx b/examples/solid/basic-ssr-file-based/src/entry-client.tsx index 8cbc879670..c7dae8d650 100644 --- a/examples/solid/basic-ssr-file-based/src/entry-client.tsx +++ b/examples/solid/basic-ssr-file-based/src/entry-client.tsx @@ -1,5 +1,5 @@ import { RouterClient } from '@tanstack/solid-router/ssr/client' -import { hydrate } from 'solid-js/web' +import { hydrate } from '@solidjs/web' import { createRouter } from './router' const router = createRouter() 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 fc6a3e4377..26eb09e67f 100644 --- a/examples/solid/basic-ssr-file-based/src/routeTree.gen.ts +++ b/examples/solid/basic-ssr-file-based/src/routeTree.gen.ts @@ -9,17 +9,12 @@ // Additionally, you should also exclude this file 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', @@ -30,6 +25,11 @@ 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,13 +78,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/error': { id: '/error' path: '/error' @@ -99,6 +92,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } '/posts/': { id: '/posts/' path: '/' diff --git a/examples/solid/basic-ssr-streaming-file-based/package.json b/examples/solid/basic-ssr-streaming-file-based/package.json index 92367442fc..516eacdd63 100644 --- a/examples/solid/basic-ssr-streaming-file-based/package.json +++ b/examples/solid/basic-ssr-streaming-file-based/package.json @@ -12,23 +12,23 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", "compression": "^1.8.0", - "express": "^5.2.1", + "express": "^4.21.2", "get-port": "^7.1.0", "node-fetch": "^3.3.2", "redaxios": "^0.5.1", - "solid-js": "^1.9.10", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "@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" + "@tanstack/router-plugin": "^1.166.14", + "@types/express": "^4.17.23", + "typescript": "^5.7.2", + "vite": "^8.0.0", + "vite-plugin-solid": "3.0.0-next.3" } } diff --git a/examples/solid/basic-ssr-streaming-file-based/server.js b/examples/solid/basic-ssr-streaming-file-based/server.js index 4369c0028b..1fb56e8ef7 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('/{*splat}', async (req, res) => { + app.use('*', async (req, res) => { try { const url = req.originalUrl @@ -97,8 +97,7 @@ export async function createServer( if (!isTest) { createServer().then(async ({ app }) => - app.listen(await getPort({ port: portNumbers(3000, 3100) }), (error) => { - if (error) throw error + app.listen(await getPort({ port: portNumbers(3000, 3100) }), () => { console.info('Client Server: http://localhost:3000') }), ) diff --git a/examples/solid/basic-ssr-streaming-file-based/src/entry-client.tsx b/examples/solid/basic-ssr-streaming-file-based/src/entry-client.tsx index 8cbc879670..c7dae8d650 100644 --- a/examples/solid/basic-ssr-streaming-file-based/src/entry-client.tsx +++ b/examples/solid/basic-ssr-streaming-file-based/src/entry-client.tsx @@ -1,5 +1,5 @@ import { RouterClient } from '@tanstack/solid-router/ssr/client' -import { hydrate } from 'solid-js/web' +import { hydrate } from '@solidjs/web' import { createRouter } from './router' const router = createRouter() 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 0161f550f0..be2ed5b18d 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,23 +9,19 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 CounterRouteImport } from './routes/counter' +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 PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +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' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) const CounterRoute = CounterRouteImport.update({ @@ -33,16 +29,15 @@ const CounterRoute = CounterRouteImport.update({ path: '/counter', getParentRoute: () => rootRouteImport, } as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ + id: '/_pathlessLayout', + 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: '/', @@ -53,11 +48,10 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ path: '/$postId', getParentRoute: () => PostsRoute, } as any) -const PathlessLayoutNestedLayoutRouteARoute = - PathlessLayoutNestedLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, +const PathlessLayoutNestedLayoutRoute = + PathlessLayoutNestedLayoutRouteImport.update({ + id: '/_nested-layout', + getParentRoute: () => PathlessLayoutRoute, } as any) const PathlessLayoutNestedLayoutRouteBRoute = PathlessLayoutNestedLayoutRouteBRouteImport.update({ @@ -65,6 +59,12 @@ const PathlessLayoutNestedLayoutRouteBRoute = path: '/route-b', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) +const PathlessLayoutNestedLayoutRouteARoute = + PathlessLayoutNestedLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + } as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -129,18 +129,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_pathlessLayout': { - id: '/_pathlessLayout' - path: '' - fullPath: '/' - preLoaderRoute: typeof PathlessLayoutRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } '/counter': { @@ -150,19 +143,19 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof CounterRouteImport parentRoute: typeof rootRouteImport } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' + '/_pathlessLayout': { + id: '/_pathlessLayout' path: '' fullPath: '/' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute + preLoaderRoute: typeof PathlessLayoutRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport } '/posts/': { id: '/posts/' @@ -178,12 +171,12 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRoute } - '/_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': { + id: '/_pathlessLayout/_nested-layout' + path: '' + fullPath: '/' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -192,6 +185,13 @@ 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/routes/index.tsx b/examples/solid/basic-ssr-streaming-file-based/src/routes/index.tsx index e0bddc5969..d4ef02bc24 100644 --- a/examples/solid/basic-ssr-streaming-file-based/src/routes/index.tsx +++ b/examples/solid/basic-ssr-streaming-file-based/src/routes/index.tsx @@ -1,5 +1,5 @@ import { Await, createFileRoute } from '@tanstack/solid-router' -import { Suspense } from 'solid-js' +import { Loading } from 'solid-js' export const Route = createFileRoute('/')({ loader: () => ({ @@ -18,11 +18,11 @@ function Home() {

Welcome Home!

Data: {data().date.getDate()}

- Loading...
}> + Loading...
}> {(data) =>

Deferred: {new Date(data.date).getDate()}

}
- +
) } 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 deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/solid/basic-ssr-streaming-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/solid/basic-virtual-file-based/package.json b/examples/solid/basic-virtual-file-based/package.json index 801b452192..be20fc9be9 100644 --- a/examples/solid/basic-virtual-file-based/package.json +++ b/examples/solid/basic-virtual-file-based/package.json @@ -10,19 +10,19 @@ }, "dependencies": { "@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", + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", + "@tanstack/router-plugin": "^1.166.14", + "@tanstack/virtual-file-routes": "^1.161.7", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", "redaxios": "^0.5.1", - "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", - "vite-plugin-solid": "^2.11.11" + "vite-plugin-solid": "3.0.0-next.3", + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/solid/basic-virtual-file-based/src/main.tsx b/examples/solid/basic-virtual-file-based/src/main.tsx index 8128384193..4bd8c56ef3 100644 --- a/examples/solid/basic-virtual-file-based/src/main.tsx +++ b/examples/solid/basic-virtual-file-based/src/main.tsx @@ -1,4 +1,4 @@ -import { render } from 'solid-js/web' +import { render } from '@solidjs/web' import { RouterProvider, createRouter } from '@tanstack/solid-router' import { routeTree } from './routeTree.gen' import './styles.css' 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 c41eda86bf..8a3c6c7091 100644 --- a/examples/solid/basic-virtual-file-based/src/routeTree.gen.ts +++ b/examples/solid/basic-virtual-file-based/src/routeTree.gen.ts @@ -8,78 +8,80 @@ // 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 homeRouteImport } from './routes/home' -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 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 ClassicHelloUniverseRouteImport } from './routes/file-based-subtree/hello/universe' -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' +import type { CreateFileRoute, FileRoutesByPath } from '@tanstack/solid-router' -const homeRoute = homeRouteImport.update({ - id: '/', - path: '/', +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 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 aRouteImport } from './routes/a' + +const postsPostsRoute = postsPostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) const layoutFirstLayoutRoute = layoutFirstLayoutRouteImport.update({ id: '/_first', getParentRoute: () => rootRouteImport, } as any) -const postsPostsRoute = postsPostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) -const layoutSecondLayoutRoute = layoutSecondLayoutRouteImport.update({ - id: '/_second-layout', - getParentRoute: () => layoutFirstLayoutRoute, -} as any) -const ClassicHelloRouteRoute = ClassicHelloRouteRouteImport.update({ - id: '/classic/hello', - path: '/classic/hello', - getParentRoute: () => rootRouteImport, -} as any) -const postsPostsHomeRoute = postsPostsHomeRouteImport.update({ +const homeRoute = homeRouteImport.update({ id: '/', path: '/', - getParentRoute: () => postsPostsRoute, + 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 ClassicHelloIndexRoute = ClassicHelloIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => ClassicHelloRouteRoute, } as any) -const ClassicHelloUniverseRoute = ClassicHelloUniverseRouteImport.update({ - id: '/universe', - path: '/universe', - getParentRoute: () => ClassicHelloRouteRoute, -} as any) 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, +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, } as any) +const aRoute = aRouteImport.update({ + id: '/route-without-file/layout-a', + path: '/route-without-file/layout-a', + getParentRoute: () => layoutSecondLayoutRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof homeRoute @@ -166,11 +168,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof homeRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof postsPostsRouteImport parentRoute: typeof rootRouteImport } '/_first': { @@ -180,33 +182,12 @@ declare module '@tanstack/solid-router' { 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: '/' - preLoaderRoute: typeof layoutSecondLayoutRouteImport - parentRoute: typeof layoutFirstLayoutRoute - } - '/classic/hello': { - id: '/classic/hello' - path: '/classic/hello' - fullPath: '/classic/hello' - preLoaderRoute: typeof ClassicHelloRouteRouteImport - parentRoute: typeof rootRouteImport - } - '/posts/': { - id: '/posts/' + '/': { + id: '/' path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof postsPostsHomeRouteImport - parentRoute: typeof postsPostsRoute + fullPath: '/' + preLoaderRoute: typeof homeRouteImport + parentRoute: typeof rootRouteImport } '/posts/$postId': { id: '/posts/$postId' @@ -215,6 +196,27 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof postsPostsDetailRouteImport parentRoute: typeof postsPostsRoute } + '/_first/_second-layout': { + id: '/_first/_second-layout' + path: '' + 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' + fullPath: '/classic/hello' + preLoaderRoute: typeof ClassicHelloRouteRouteImport + parentRoute: typeof rootRouteImport + } '/classic/hello/': { id: '/classic/hello/' path: '/' @@ -222,13 +224,6 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof ClassicHelloIndexRouteImport parentRoute: typeof ClassicHelloRouteRoute } - '/classic/hello/universe': { - id: '/classic/hello/universe' - path: '/universe' - fullPath: '/classic/hello/universe' - preLoaderRoute: typeof ClassicHelloUniverseRouteImport - parentRoute: typeof ClassicHelloRouteRoute - } '/classic/hello/world': { id: '/classic/hello/world' path: '/world' @@ -236,12 +231,12 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof ClassicHelloWorldRouteImport parentRoute: typeof ClassicHelloRouteRoute } - '/_first/_second-layout/route-without-file/layout-a': { - id: '/_first/_second-layout/route-without-file/layout-a' - path: '/route-without-file/layout-a' - fullPath: '/route-without-file/layout-a' - preLoaderRoute: typeof aRouteImport - parentRoute: typeof layoutSecondLayoutRoute + '/classic/hello/universe': { + id: '/classic/hello/universe' + path: '/universe' + fullPath: '/classic/hello/universe' + preLoaderRoute: typeof ClassicHelloUniverseRouteImport + parentRoute: typeof ClassicHelloRouteRoute } '/_first/_second-layout/route-without-file/layout-b': { id: '/_first/_second-layout/route-without-file/layout-b' @@ -250,9 +245,125 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof bRouteImport parentRoute: typeof layoutSecondLayoutRoute } + '/_first/_second-layout/route-without-file/layout-a': { + id: '/_first/_second-layout/route-without-file/layout-a' + path: '/route-without-file/layout-a' + fullPath: '/route-without-file/layout-a' + preLoaderRoute: typeof aRouteImport + 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 5b02ca6dcd..a190b24202 100644 --- a/examples/solid/basic-virtual-file-based/src/routes/a.tsx +++ b/examples/solid/basic-virtual-file-based/src/routes/a.tsx @@ -1,7 +1,4 @@ -import { createFileRoute } from '@tanstack/solid-router' -export const Route = createFileRoute( - '/_first/_second-layout/route-without-file/layout-a', -)({ +export const Route = createFileRoute({ 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 014f13c1cc..505f8f6fbf 100644 --- a/examples/solid/basic-virtual-file-based/src/routes/b.tsx +++ b/examples/solid/basic-virtual-file-based/src/routes/b.tsx @@ -1,7 +1,4 @@ -import { createFileRoute } from '@tanstack/solid-router' -export const Route = createFileRoute( - '/_first/_second-layout/route-without-file/layout-b', -)({ +export const Route = createFileRoute({ 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 6cc8bb1a6f..f86335e291 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,4 +1,3 @@ -import { createFileRoute } from '@tanstack/solid-router' -export const Route = createFileRoute('/classic/hello/')({ +export const Route = createFileRoute({ 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 f4f30d8425..5b95eea555 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, createFileRoute } from '@tanstack/solid-router' +import { Link, Outlet } from '@tanstack/solid-router' -export const Route = createFileRoute('/classic/hello')({ +export const Route = createFileRoute({ 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 f250de10c1..20b07c41cc 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,4 +1,3 @@ -import { createFileRoute } from '@tanstack/solid-router' -export const Route = createFileRoute('/classic/hello/universe')({ +export const Route = createFileRoute({ 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 d207a49114..4af11357a2 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,4 +1,3 @@ -import { createFileRoute } from '@tanstack/solid-router' -export const Route = createFileRoute('/classic/hello/world')({ +export const Route = createFileRoute({ 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 3f905db60c..510db79b73 100644 --- a/examples/solid/basic-virtual-file-based/src/routes/home.tsx +++ b/examples/solid/basic-virtual-file-based/src/routes/home.tsx @@ -1,5 +1,4 @@ -import { createFileRoute } from '@tanstack/solid-router' -export const Route = createFileRoute('/')({ +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 5c77421bb2..c549175638 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, createFileRoute } from '@tanstack/solid-router' +import { Outlet } from '@tanstack/solid-router' -export const Route = createFileRoute('/_first')({ +export const Route = createFileRoute({ 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 245a25bafc..b2f544c540 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, createFileRoute } from '@tanstack/solid-router' +import { Link, Outlet } from '@tanstack/solid-router' -export const Route = createFileRoute('/_first/_second-layout')({ +export const Route = createFileRoute({ 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 990f473ae8..ef413c1be0 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, createFileRoute } from '@tanstack/solid-router' +import { ErrorComponent } 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('/posts/$postId')({ +export const Route = createFileRoute({ 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 812b581e0a..13529228bb 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,5 +1,4 @@ -import { createFileRoute } from '@tanstack/solid-router' -export const Route = createFileRoute('/posts/')({ +export const Route = createFileRoute({ 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 9ae6dfc747..46203594d1 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, createFileRoute } from '@tanstack/solid-router' +import { Link, Outlet } from '@tanstack/solid-router' import { fetchPosts } from '../../posts' -export const Route = createFileRoute('/posts')({ +export const Route = createFileRoute({ loader: fetchPosts, component: PostsComponent, }) 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 deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/solid/basic-virtual-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/solid/basic-virtual-file-based/vite.config.ts b/examples/solid/basic-virtual-file-based/vite.config.ts index ec379c254d..c13227d733 100644 --- a/examples/solid/basic-virtual-file-based/vite.config.ts +++ b/examples/solid/basic-virtual-file-based/vite.config.ts @@ -10,6 +10,7 @@ export default defineConfig({ tanstackRouter({ target: 'solid', autoCodeSplitting: true, + verboseFileRoutes: false, virtualRouteConfig: './routes.ts', }), solid(), diff --git a/examples/solid/basic-virtual-inside-file-based/package.json b/examples/solid/basic-virtual-inside-file-based/package.json index a9cc6360a5..372ef88fa1 100644 --- a/examples/solid/basic-virtual-inside-file-based/package.json +++ b/examples/solid/basic-virtual-inside-file-based/package.json @@ -10,19 +10,19 @@ }, "dependencies": { "@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", + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", + "@tanstack/router-plugin": "^1.166.14", + "@tanstack/virtual-file-routes": "^1.161.7", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", "redaxios": "^0.5.1", - "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", - "vite-plugin-solid": "^2.11.11" + "vite-plugin-solid": "3.0.0-next.3", + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/solid/basic-virtual-inside-file-based/src/main.tsx b/examples/solid/basic-virtual-inside-file-based/src/main.tsx index 8128384193..4bd8c56ef3 100644 --- a/examples/solid/basic-virtual-inside-file-based/src/main.tsx +++ b/examples/solid/basic-virtual-inside-file-based/src/main.tsx @@ -1,4 +1,4 @@ -import { render } from 'solid-js/web' +import { render } from '@solidjs/web' import { RouterProvider, createRouter } from '@tanstack/solid-router' import { routeTree } from './routeTree.gen' import './styles.css' 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 6117330aa3..03d91a80d6 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,62 +8,64 @@ // 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 PostsRouteImport } from './routes/posts' -import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' -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 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' +import type { CreateFileRoute, FileRoutesByPath } from '@tanstack/solid-router' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +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 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 LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' +import { Route as postsLetsGoDeeperHomeRouteImport } from './routes/posts/lets-go/deeper/home' + +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) const LayoutRoute = LayoutRouteImport.update({ id: '/_layout', getParentRoute: () => rootRouteImport, } as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', 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 PostsDetailsRoute = PostsDetailsRouteImport.update({ - id: '/$postId', - path: '/$postId', +const postsLetsGoIndexRoute = postsLetsGoIndexRouteImport.update({ + id: '/inception/', + path: '/inception/', getParentRoute: () => PostsRoute, } as any) -const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => LayoutLayout2Route, -} as any) const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ id: '/layout-b', path: '/layout-b', getParentRoute: () => LayoutLayout2Route, } as any) -const PostsLetsGoIndexRoute = PostsLetsGoIndexRouteImport.update({ - id: '/inception/', - path: '/inception/', - getParentRoute: () => PostsRoute, +const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => LayoutLayout2Route, } as any) -const PostsLetsGoDeeperHomeRoute = PostsLetsGoDeeperHomeRouteImport.update({ +const postsLetsGoDeeperHomeRoute = postsLetsGoDeeperHomeRouteImport.update({ id: '/inception/deeper/', path: '/inception/deeper/', getParentRoute: () => PostsRoute, @@ -72,34 +74,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 @@ -143,11 +145,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } '/_layout': { @@ -157,13 +159,20 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof LayoutRouteImport parentRoute: typeof rootRouteImport } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof postsDetailsRouteImport + parentRoute: typeof PostsRoute + } '/_layout/_layout-2': { id: '/_layout/_layout-2' path: '' @@ -175,23 +184,16 @@ declare module '@tanstack/solid-router' { id: '/posts/' path: '/' fullPath: '/posts/' - preLoaderRoute: typeof PostsHomeRouteImport + preLoaderRoute: typeof postsHomeRouteImport parentRoute: typeof PostsRoute } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsDetailsRouteImport + '/posts/inception/': { + id: '/posts/inception/' + path: '/inception' + fullPath: '/posts/inception/' + preLoaderRoute: typeof postsLetsGoIndexRouteImport parentRoute: typeof PostsRoute } - '/_layout/_layout-2/layout-a': { - id: '/_layout/_layout-2/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof LayoutLayout2LayoutARouteImport - parentRoute: typeof LayoutLayout2Route - } '/_layout/_layout-2/layout-b': { id: '/_layout/_layout-2/layout-b' path: '/layout-b' @@ -199,23 +201,114 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport parentRoute: typeof LayoutLayout2Route } - '/posts/inception/': { - id: '/posts/inception/' - path: '/inception' - fullPath: '/posts/inception/' - preLoaderRoute: typeof PostsLetsGoIndexRouteImport - parentRoute: typeof PostsRoute + '/_layout/_layout-2/layout-a': { + id: '/_layout/_layout-2/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof LayoutLayout2LayoutARouteImport + parentRoute: typeof LayoutLayout2Route } '/posts/inception/deeper/': { id: '/posts/inception/deeper/' path: '/inception/deeper' fullPath: '/posts/inception/deeper/' - preLoaderRoute: typeof PostsLetsGoDeeperHomeRouteImport + 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 @@ -242,17 +335,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 d43b4ef5f5..c549175638 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, createFileRoute } from '@tanstack/solid-router' +import { Outlet } from '@tanstack/solid-router' -export const Route = createFileRoute('/_layout')({ +export const Route = createFileRoute({ 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 7a5a3623a0..efeca5ce86 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, createFileRoute } from '@tanstack/solid-router' +import { Link, Outlet } from '@tanstack/solid-router' -export const Route = createFileRoute('/_layout/_layout-2')({ +export const Route = createFileRoute({ 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 997e6caf80..a190b24202 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,5 +1,4 @@ -import { createFileRoute } from '@tanstack/solid-router' -export const Route = createFileRoute('/_layout/_layout-2/layout-a')({ +export const Route = createFileRoute({ 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 70135c5809..505f8f6fbf 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,5 +1,4 @@ -import { createFileRoute } from '@tanstack/solid-router' -export const Route = createFileRoute('/_layout/_layout-2/layout-b')({ +export const Route = createFileRoute({ 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 3f905db60c..510db79b73 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,5 +1,4 @@ -import { createFileRoute } from '@tanstack/solid-router' -export const Route = createFileRoute('/')({ +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 11a999f50a..2e28f9beb3 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, createFileRoute } from '@tanstack/solid-router' +import { Link, Outlet } from '@tanstack/solid-router' import { fetchPosts } from '../posts' -export const Route = createFileRoute('/posts')({ +export const Route = createFileRoute({ 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 de4cc4ed80..b01702746d 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, createFileRoute } from '@tanstack/solid-router' +import { ErrorComponent } 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('/posts/$postId')({ +export const Route = createFileRoute({ 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 812b581e0a..13529228bb 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,5 +1,4 @@ -import { createFileRoute } from '@tanstack/solid-router' -export const Route = createFileRoute('/posts/')({ +export const Route = createFileRoute({ 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 166eda4335..f8bc76644a 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,4 +1,3 @@ -import { createFileRoute } from '@tanstack/solid-router' -export const Route = createFileRoute('/posts/inception/deeper/')({ +export const Route = createFileRoute({ 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 49b88f751d..1c7ea68931 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,4 +1,3 @@ -import { createFileRoute } from '@tanstack/solid-router' -export const Route = createFileRoute('/posts/inception/')({ +export const Route = createFileRoute({ component: () =>
Hello /posts/inception/!
, }) 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 deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/solid/basic-virtual-inside-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// 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 79454008ba..b119537544 100644 --- a/examples/solid/basic-virtual-inside-file-based/vite.config.ts +++ b/examples/solid/basic-virtual-inside-file-based/vite.config.ts @@ -10,6 +10,7 @@ export default defineConfig({ tanstackRouter({ target: 'solid', autoCodeSplitting: true, + verboseFileRoutes: false, }), solid(), ], diff --git a/examples/solid/basic/package.json b/examples/solid/basic/package.json index 95ec804011..d32082da1f 100644 --- a/examples/solid/basic/package.json +++ b/examples/solid/basic/package.json @@ -10,18 +10,18 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", "redaxios": "^0.5.1", - "solid-js": "^1.9.10", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", "tailwindcss": "^4.2.2" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", - "vite-plugin-solid": "^2.11.11" + "typescript": "^5.7.2", + "vite": "^8.0.0", + "vite-plugin-solid": "3.0.0-next.3" } } diff --git a/examples/solid/basic/src/main.tsx b/examples/solid/basic/src/main.tsx index 53d9959cc3..b02b0f2206 100644 --- a/examples/solid/basic/src/main.tsx +++ b/examples/solid/basic/src/main.tsx @@ -1,4 +1,4 @@ -import { render } from 'solid-js/web' +import { render } from '@solidjs/web' import { ErrorComponent, Link, diff --git a/examples/solid/basic/src/vite-env.d.ts b/examples/solid/basic/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/solid/basic/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/solid/deferred-data/package.json b/examples/solid/deferred-data/package.json index 56114afd04..3d785422ab 100644 --- a/examples/solid/deferred-data/package.json +++ b/examples/solid/deferred-data/package.json @@ -10,17 +10,17 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", "redaxios": "^0.5.1", - "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", - "vite-plugin-solid": "^2.11.11" + "vite-plugin-solid": "3.0.0-next.3", + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/solid/deferred-data/src/main.tsx b/examples/solid/deferred-data/src/main.tsx index 4dd43fd97b..64dce976bb 100644 --- a/examples/solid/deferred-data/src/main.tsx +++ b/examples/solid/deferred-data/src/main.tsx @@ -1,5 +1,5 @@ -import { render } from 'solid-js/web' -import { Suspense } from 'solid-js' +import { render } from '@solidjs/web' +import { Loading } from 'solid-js' import { Await, ErrorComponent, @@ -207,7 +207,7 @@ function PostComponent() {

{loaderData().post.title}

{loaderData().post.body}
- @@ -235,7 +235,7 @@ function PostComponent() { ) }} - +
) } diff --git a/examples/solid/deferred-data/src/vite-env.d.ts b/examples/solid/deferred-data/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/solid/deferred-data/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/solid/i18n-paraglide/package.json b/examples/solid/i18n-paraglide/package.json index 6493a3c7c8..0f1894fc55 100644 --- a/examples/solid/i18n-paraglide/package.json +++ b/examples/solid/i18n-paraglide/package.json @@ -11,28 +11,15 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/router-plugin": "^1.169.0", - "solid-js": "^1.9.10", - "tailwindcss": "^4.2.2" - }, - "devDependencies": { + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/router-plugin": "^1.166.14", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", + "tailwindcss": "^4.2.2", "@types/node": "^22.18.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", + "vite-plugin-solid": "3.0.0-next.3", + "typescript": "^5.9.2", + "vite": "^8.0.0", "@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/main.tsx b/examples/solid/i18n-paraglide/src/main.tsx index 6847c9cbdc..6f2e51f69e 100644 --- a/examples/solid/i18n-paraglide/src/main.tsx +++ b/examples/solid/i18n-paraglide/src/main.tsx @@ -1,4 +1,4 @@ -import { render } from 'solid-js/web' +import { render } from '@solidjs/web' import { RouterProvider, createRouter } from '@tanstack/solid-router' import './styles.css' // Import the generated route tree diff --git a/examples/solid/i18n-paraglide/src/routeTree.gen.ts b/examples/solid/i18n-paraglide/src/routeTree.gen.ts index 98df1e83d8..333a815c38 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 IndexRouteImport } from './routes/index' import { Route as AboutRouteImport } from './routes/about' +import { Route as IndexRouteImport } from './routes/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const AboutRoute = AboutRouteImport.update({ id: '/about', path: '/about', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/about': { id: '/about' path: '/about' @@ -65,6 +58,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof AboutRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/solid/i18n-paraglide/src/vite-env.d.ts b/examples/solid/i18n-paraglide/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/solid/i18n-paraglide/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/solid/i18n-paraglide/tsconfig.json b/examples/solid/i18n-paraglide/tsconfig.json index 9dcde39a0f..f3fadb414f 100644 --- a/examples/solid/i18n-paraglide/tsconfig.json +++ b/examples/solid/i18n-paraglide/tsconfig.json @@ -22,6 +22,7 @@ "noUnusedParameters": true, "noFallthroughCasesInSwitch": true, "noUncheckedSideEffectImports": true, + "baseUrl": ".", "paths": { "@/*": ["./src/*"] } diff --git a/examples/solid/kitchen-sink-file-based/package.json b/examples/solid/kitchen-sink-file-based/package.json index 8cd73e38ff..7c499ae646 100644 --- a/examples/solid/kitchen-sink-file-based/package.json +++ b/examples/solid/kitchen-sink-file-based/package.json @@ -4,25 +4,25 @@ "type": "module", "scripts": { "dev": "vite --port 3000", - "build": "vite build && tsc --noEmit", + "build": "echo 'Skipped: waiting for dependency Solid 2.0 support' && exit 0", "preview": "vite preview", "start": "vite" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", "immer": "^10.1.1", "redaxios": "^0.5.1", - "solid-js": "^1.9.10", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "@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" + "@tanstack/router-plugin": "^1.166.14", + "typescript": "^5.7.2", + "vite": "^8.0.0", + "vite-plugin-solid": "3.0.0-next.3" } } diff --git a/examples/solid/kitchen-sink-file-based/src/main.tsx b/examples/solid/kitchen-sink-file-based/src/main.tsx index 2ebe009eed..8742a88300 100644 --- a/examples/solid/kitchen-sink-file-based/src/main.tsx +++ b/examples/solid/kitchen-sink-file-based/src/main.tsx @@ -9,7 +9,7 @@ import { Spinner } from './components/Spinner' import { routeTree } from './routeTree.gen' import { useSessionStorage } from './hooks/useSessionStorage' import './styles.css' -import { render } from 'solid-js/web' +import { render } from '@solidjs/web' // 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 76bb314a71..f7af0fbf39 100644 --- a/examples/solid/kitchen-sink-file-based/src/routeTree.gen.ts +++ b/examples/solid/kitchen-sink-file-based/src/routeTree.gen.ts @@ -8,224 +8,132 @@ // 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 AuthRouteImport } from './routes/_auth' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' -import { Route as DashboardRouteRouteImport } from './routes/dashboard.route' +// Import Routes + +import { Route as rootRoute } from './routes/__root' 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 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 DashboardUsersRouteRouteImport } from './routes/dashboard.users.route' +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 DashboardInvoicesIndexRouteImport } from './routes/dashboard.invoices.index' -import { Route as DashboardInvoicesInvoiceIdRouteImport } from './routes/dashboard.invoices.$invoiceId' +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 thisFolderIsNotInTheUrlRouteGroupRouteImport } from './routes/(this-folder-is-not-in-the-url)/route-group' +import { Route as DashboardUsersRouteRouteImport } from './routes/dashboard.users.route' +import { Route as DashboardInvoicesRouteRouteImport } from './routes/dashboard.invoices.route' import { Route as DashboardUsersIndexRouteImport } from './routes/dashboard.users.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) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', - getParentRoute: () => rootRouteImport, + getParentRoute: () => rootRoute, } 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 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 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, + +const ExpensiveIndexRoute = ExpensiveIndexRouteImport.update({ + id: '/expensive/', + path: '/expensive/', + getParentRoute: () => rootRoute, } as any) + const DashboardIndexRoute = DashboardIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => DashboardRouteRoute, } as any) -const DashboardInvoicesRouteRoute = DashboardInvoicesRouteRouteImport.update({ - id: '/invoices', - path: '/invoices', - getParentRoute: () => DashboardRouteRoute, + +const PathlessLayoutRouteBRoute = PathlessLayoutRouteBRouteImport.update({ + id: '/route-b', + path: '/route-b', + getParentRoute: () => PathlessLayoutRoute, } as any) + +const PathlessLayoutRouteARoute = PathlessLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutRoute, +} as any) + +const AuthProfileRoute = AuthProfileRouteImport.update({ + id: '/profile', + path: '/profile', + getParentRoute: () => AuthRoute, +} as any) + +const thisFolderIsNotInTheUrlRouteGroupRoute = + thisFolderIsNotInTheUrlRouteGroupRouteImport.update({ + id: '/(this-folder-is-not-in-the-url)/route-group', + path: '/route-group', + getParentRoute: () => rootRoute, + } as any) + const DashboardUsersRouteRoute = DashboardUsersRouteRouteImport.update({ id: '/users', path: '/users', getParentRoute: () => DashboardRouteRoute, } as any) -const ExpensiveIndexRoute = ExpensiveIndexRouteImport.update({ - id: '/expensive/', - path: '/expensive/', - getParentRoute: () => rootRouteImport, + +const DashboardInvoicesRouteRoute = DashboardInvoicesRouteRouteImport.update({ + id: '/invoices', + path: '/invoices', + getParentRoute: () => DashboardRouteRoute, } as any) -const DashboardInvoicesIndexRoute = DashboardInvoicesIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => DashboardInvoicesRouteRoute, -} 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 DashboardInvoicesIndexRoute = DashboardInvoicesIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => DashboardInvoicesRouteRoute, +} as any) + const DashboardUsersUserRoute = DashboardUsersUserRouteImport.update({ id: '/user', path: '/user', getParentRoute: () => DashboardUsersRouteRoute, } as any) -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 -} +const DashboardInvoicesInvoiceIdRoute = + DashboardInvoicesInvoiceIdRouteImport.update({ + id: '/$invoiceId', + path: '/$invoiceId', + getParentRoute: () => DashboardInvoicesRouteRoute, + } as any) + +// Populate the FileRoutesByPath interface declare module '@tanstack/solid-router' { interface FileRoutesByPath { @@ -234,123 +142,125 @@ declare module '@tanstack/solid-router' { path: '/' fullPath: '/' preLoaderRoute: typeof IndexRouteImport - 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 + parentRoute: typeof rootRoute } '/dashboard': { id: '/dashboard' path: '/dashboard' fullPath: '/dashboard' preLoaderRoute: typeof DashboardRouteRouteImport - parentRoute: typeof rootRouteImport + 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 } '/login': { id: '/login' path: '/login' fullPath: '/login' preLoaderRoute: typeof LoginRouteImport - 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 rootRouteImport - } - '/_auth/profile': { - id: '/_auth/profile' - path: '/profile' - fullPath: '/profile' - preLoaderRoute: typeof AuthProfileRouteImport - parentRoute: typeof AuthRoute - } - '/_pathlessLayout/route-a': { - id: '/_pathlessLayout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutRoute - } - '/_pathlessLayout/route-b': { - id: '/_pathlessLayout/route-b' - path: '/route-b' - fullPath: '/route-b' - preLoaderRoute: typeof PathlessLayoutRouteBRouteImport - parentRoute: typeof PathlessLayoutRoute - } - '/dashboard/': { - id: '/dashboard/' - path: '/' - fullPath: '/dashboard/' - preLoaderRoute: typeof DashboardIndexRouteImport - parentRoute: typeof DashboardRouteRoute + parentRoute: typeof rootRoute } '/dashboard/invoices': { id: '/dashboard/invoices' path: '/invoices' fullPath: '/dashboard/invoices' preLoaderRoute: typeof DashboardInvoicesRouteRouteImport - parentRoute: typeof DashboardRouteRoute + parentRoute: typeof DashboardRouteRouteImport } '/dashboard/users': { id: '/dashboard/users' path: '/users' fullPath: '/dashboard/users' preLoaderRoute: typeof DashboardUsersRouteRouteImport - parentRoute: typeof DashboardRouteRoute + parentRoute: typeof DashboardRouteRouteImport + } + '/(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 + } + '/_auth/profile': { + id: '/_auth/profile' + path: '/profile' + fullPath: '/profile' + preLoaderRoute: typeof AuthProfileRouteImport + parentRoute: typeof AuthRouteImport + } + '/_pathlessLayout/route-a': { + id: '/_pathlessLayout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutRouteImport + } + '/_pathlessLayout/route-b': { + id: '/_pathlessLayout/route-b' + path: '/route-b' + fullPath: '/route-b' + preLoaderRoute: typeof PathlessLayoutRouteBRouteImport + parentRoute: typeof PathlessLayoutRouteImport + } + '/dashboard/': { + id: '/dashboard/' + path: '/' + fullPath: '/dashboard/' + preLoaderRoute: typeof DashboardIndexRouteImport + parentRoute: typeof DashboardRouteRouteImport } '/expensive/': { id: '/expensive/' path: '/expensive' - fullPath: '/expensive/' + fullPath: '/expensive' preLoaderRoute: typeof ExpensiveIndexRouteImport - parentRoute: typeof rootRouteImport - } - '/dashboard/invoices/': { - id: '/dashboard/invoices/' - path: '/' - fullPath: '/dashboard/invoices/' - preLoaderRoute: typeof DashboardInvoicesIndexRouteImport - parentRoute: typeof DashboardInvoicesRouteRoute + parentRoute: typeof rootRoute } '/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 DashboardUsersRouteRoute + parentRoute: typeof DashboardInvoicesRouteRouteImport } '/dashboard/users/user': { id: '/dashboard/users/user' path: '/user' fullPath: '/dashboard/users/user' preLoaderRoute: typeof DashboardUsersUserRouteImport - parentRoute: typeof DashboardUsersRouteRoute + parentRoute: typeof DashboardUsersRouteRouteImport + } + '/dashboard/invoices/': { + id: '/dashboard/invoices/' + path: '/' + fullPath: '/dashboard/invoices/' + preLoaderRoute: typeof DashboardInvoicesIndexRouteImport + parentRoute: typeof DashboardInvoicesRouteRouteImport + } + '/dashboard/users/': { + id: '/dashboard/users/' + path: '/' + fullPath: '/dashboard/users/' + preLoaderRoute: typeof DashboardUsersIndexRouteImport + parentRoute: typeof DashboardUsersRouteRouteImport } } } +// Create and export the route tree + interface DashboardInvoicesRouteRouteChildren { DashboardInvoicesInvoiceIdRoute: typeof DashboardInvoicesInvoiceIdRoute DashboardInvoicesIndexRoute: typeof DashboardInvoicesIndexRoute @@ -420,6 +330,128 @@ 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, @@ -430,6 +462,107 @@ const rootRouteChildren: RootRouteChildren = { thisFolderIsNotInTheUrlRouteGroupRoute, ExpensiveIndexRoute: ExpensiveIndexRoute, } -export const routeTree = rootRouteImport + +export const routeTree = rootRoute ._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/vite-env.d.ts b/examples/solid/kitchen-sink-file-based/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/solid/kitchen-sink-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// 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 25a1c29953..78c6566f29 100644 --- a/examples/solid/kitchen-sink-solid-query-file-based/package.json +++ b/examples/solid/kitchen-sink-solid-query-file-based/package.json @@ -10,21 +10,21 @@ }, "dependencies": { "@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.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.166.14", + "@tanstack/solid-query": "6.0.0-alpha.1", + "@tanstack/solid-query-devtools": "6.0.0-alpha.1", + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", "immer": "^10.1.1", "redaxios": "^0.5.1", - "solid-js": "^1.9.10", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", - "vite-plugin-solid": "^2.11.11" + "typescript": "^5.7.2", + "vite": "^8.0.0", + "vite-plugin-solid": "3.0.0-next.3" } } diff --git a/examples/solid/kitchen-sink-solid-query-file-based/src/main.tsx b/examples/solid/kitchen-sink-solid-query-file-based/src/main.tsx index b7b0c1d5d0..5f27f1b774 100644 --- a/examples/solid/kitchen-sink-solid-query-file-based/src/main.tsx +++ b/examples/solid/kitchen-sink-solid-query-file-based/src/main.tsx @@ -1,4 +1,4 @@ -import { render } from 'solid-js/web' +import { render } from '@solidjs/web' import { ErrorComponent, RouterProvider, 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 8235344782..e296846127 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,65 +9,80 @@ // Additionally, you should also exclude this file 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 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 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 DashboardUsersRouteRouteImport } from './routes/dashboard.users.route' +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 DashboardInvoicesIndexRouteImport } from './routes/dashboard.invoices.index' -import { Route as DashboardInvoicesInvoiceIdRouteImport } from './routes/dashboard.invoices.$invoiceId' +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 DashboardUsersRouteRouteImport } from './routes/dashboard.users.route' +import { Route as DashboardInvoicesRouteRouteImport } from './routes/dashboard.invoices.route' import { Route as DashboardUsersIndexRouteImport } from './routes/dashboard.users.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' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const AuthRoute = AuthRouteImport.update({ - id: '/_auth', +const LoginRoute = LoginRouteImport.update({ + id: '/login', + path: '/login', getParentRoute: () => rootRouteImport, } as any) const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, } as any) +const AuthRoute = AuthRouteImport.update({ + id: '/_auth', + getParentRoute: () => rootRouteImport, +} as any) const DashboardRouteRoute = DashboardRouteRouteImport.update({ id: '/dashboard', path: '/dashboard', getParentRoute: () => rootRouteImport, } as any) -const LoginRoute = LoginRouteImport.update({ - id: '/login', - path: '/login', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const AuthProfileRoute = AuthProfileRouteImport.update({ - id: '/profile', - path: '/profile', - getParentRoute: () => AuthRoute, +const ExpensiveIndexRoute = ExpensiveIndexRouteImport.update({ + id: '/expensive/', + path: '/expensive/', + getParentRoute: () => rootRouteImport, } as any) -const PathlessLayoutRouteARoute = PathlessLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutRoute, +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 DashboardIndexRoute = DashboardIndexRouteImport.update({ - id: '/', - path: '/', +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', getParentRoute: () => DashboardRouteRoute, } as any) const DashboardInvoicesRouteRoute = DashboardInvoicesRouteRouteImport.update({ @@ -75,42 +90,27 @@ const DashboardInvoicesRouteRoute = DashboardInvoicesRouteRouteImport.update({ path: '/invoices', getParentRoute: () => DashboardRouteRoute, } as any) -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, +const DashboardUsersIndexRoute = DashboardUsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => DashboardUsersRouteRoute, } as any) const DashboardInvoicesIndexRoute = DashboardInvoicesIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => DashboardInvoicesRouteRoute, } as any) +const DashboardUsersUserRoute = DashboardUsersUserRouteImport.update({ + id: '/user', + path: '/user', + getParentRoute: () => DashboardUsersRouteRoute, +} as any) const DashboardInvoicesInvoiceIdRoute = DashboardInvoicesInvoiceIdRouteImport.update({ id: '/$invoiceId', path: '/$invoiceId', getParentRoute: () => DashboardInvoicesRouteRoute, } as any) -const DashboardUsersIndexRoute = DashboardUsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => DashboardUsersRouteRoute, -} as any) -const DashboardUsersUserRoute = DashboardUsersUserRouteImport.update({ - id: '/user', - path: '/user', - getParentRoute: () => DashboardUsersRouteRoute, -} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -228,18 +228,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_auth': { - id: '/_auth' - path: '' - fullPath: '/' - preLoaderRoute: typeof AuthRouteImport + '/login': { + id: '/login' + path: '/login' + fullPath: '/login' + preLoaderRoute: typeof LoginRouteImport parentRoute: typeof rootRouteImport } '/_pathlessLayout': { @@ -249,6 +242,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutRouteImport parentRoute: typeof rootRouteImport } + '/_auth': { + id: '/_auth' + path: '' + fullPath: '/' + preLoaderRoute: typeof AuthRouteImport + parentRoute: typeof rootRouteImport + } '/dashboard': { id: '/dashboard' path: '/dashboard' @@ -256,26 +256,33 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof DashboardRouteRouteImport parentRoute: typeof rootRouteImport } - '/login': { - id: '/login' - path: '/login' - fullPath: '/login' - preLoaderRoute: typeof LoginRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/_auth/profile': { - id: '/_auth/profile' - path: '/profile' - fullPath: '/profile' - preLoaderRoute: typeof AuthProfileRouteImport - parentRoute: typeof AuthRoute + '/expensive/': { + id: '/expensive/' + path: '/expensive' + fullPath: '/expensive/' + preLoaderRoute: typeof ExpensiveIndexRouteImport + parentRoute: typeof rootRouteImport } - '/_pathlessLayout/route-a': { - id: '/_pathlessLayout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutRoute + '/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' @@ -284,11 +291,25 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutRoute } - '/dashboard/': { - id: '/dashboard/' - path: '/' - fullPath: '/dashboard/' - preLoaderRoute: typeof DashboardIndexRouteImport + '/_pathlessLayout/route-a': { + id: '/_pathlessLayout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutRoute + } + '/_auth/profile': { + id: '/_auth/profile' + path: '/profile' + fullPath: '/profile' + preLoaderRoute: typeof AuthProfileRouteImport + parentRoute: typeof AuthRoute + } + '/dashboard/users': { + id: '/dashboard/users' + path: '/users' + fullPath: '/dashboard/users' + preLoaderRoute: typeof DashboardUsersRouteRouteImport parentRoute: typeof DashboardRouteRoute } '/dashboard/invoices': { @@ -298,26 +319,12 @@ declare module '@tanstack/solid-router' { 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/' - preLoaderRoute: typeof ExpensiveIndexRouteImport - parentRoute: typeof rootRouteImport - } - '/foo/bar': { - id: '/foo/bar' - path: '/foo/bar' - fullPath: '/foo/bar' - preLoaderRoute: typeof FooBarRouteImport - parentRoute: typeof rootRouteImport + '/dashboard/users/': { + id: '/dashboard/users/' + path: '/' + fullPath: '/dashboard/users/' + preLoaderRoute: typeof DashboardUsersIndexRouteImport + parentRoute: typeof DashboardUsersRouteRoute } '/dashboard/invoices/': { id: '/dashboard/invoices/' @@ -326,20 +333,6 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof DashboardInvoicesIndexRouteImport 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 DashboardUsersRouteRoute - } '/dashboard/users/user': { id: '/dashboard/users/user' path: '/user' @@ -347,6 +340,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof DashboardUsersUserRouteImport parentRoute: typeof DashboardUsersRouteRoute } + '/dashboard/invoices/$invoiceId': { + id: '/dashboard/invoices/$invoiceId' + path: '/$invoiceId' + fullPath: '/dashboard/invoices/$invoiceId' + preLoaderRoute: typeof DashboardInvoicesInvoiceIdRouteImport + parentRoute: typeof DashboardInvoicesRouteRoute + } } } 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 deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/solid/kitchen-sink-solid-query-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/solid/kitchen-sink-solid-query/package.json b/examples/solid/kitchen-sink-solid-query/package.json index 7a7dc81025..db7c80a86e 100644 --- a/examples/solid/kitchen-sink-solid-query/package.json +++ b/examples/solid/kitchen-sink-solid-query/package.json @@ -4,26 +4,26 @@ "type": "module", "scripts": { "dev": "vite --port 3000", - "build": "vite build && tsc --noEmit", + "build": "vite build", "preview": "vite preview", "start": "vite" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-query-devtools": "^5.90.0", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-query": "6.0.0-alpha.1", + "@tanstack/solid-query-devtools": "6.0.0-alpha.1", + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", "immer": "^10.1.1", "redaxios": "^0.5.1", - "solid-js": "^1.9.10", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", - "vite-plugin-solid": "^2.11.11" + "typescript": "^5.7.2", + "vite": "^8.0.0", + "vite-plugin-solid": "3.0.0-next.3" } } diff --git a/examples/solid/kitchen-sink-solid-query/src/main.tsx b/examples/solid/kitchen-sink-solid-query/src/main.tsx index f8790b4a22..aaca5b2091 100644 --- a/examples/solid/kitchen-sink-solid-query/src/main.tsx +++ b/examples/solid/kitchen-sink-solid-query/src/main.tsx @@ -1,6 +1,6 @@ /* eslint-disable @typescript-eslint/no-unnecessary-condition */ import * as Solid from 'solid-js' -import { render } from 'solid-js/web' +import { render } from '@solidjs/web' import { ErrorComponent, Link, 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 deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/solid/kitchen-sink-solid-query/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/solid/kitchen-sink/package.json b/examples/solid/kitchen-sink/package.json index 08ad918a60..dff3bc237a 100644 --- a/examples/solid/kitchen-sink/package.json +++ b/examples/solid/kitchen-sink/package.json @@ -10,18 +10,18 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", "immer": "^10.1.1", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", "redaxios": "^0.5.1", - "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", - "vite-plugin-solid": "^2.11.11" + "vite-plugin-solid": "3.0.0-next.3", + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/solid/kitchen-sink/src/main.tsx b/examples/solid/kitchen-sink/src/main.tsx index 03e8379e40..882d981dbf 100644 --- a/examples/solid/kitchen-sink/src/main.tsx +++ b/examples/solid/kitchen-sink/src/main.tsx @@ -1,5 +1,5 @@ /* eslint-disable @typescript-eslint/no-unnecessary-condition */ -import { render } from 'solid-js/web' +import { render } from '@solidjs/web' import { ErrorComponent, Link, @@ -23,7 +23,6 @@ import { createMemo, createRenderEffect, createSignal, - on, } from 'solid-js' import { z } from 'zod' import { @@ -346,18 +345,16 @@ function InvoiceComponent() { onSuccess: () => router.invalidate(), }) const [notes, setNotes] = createSignal(search().notes ?? '') - createEffect( - on(notes, () => { - navigate({ - search: (old) => ({ - ...old, - notes: notes() ? notes() : undefined, - }), - params: true, - replace: true, - }) - }), - ) + createEffect(notes, () => { + navigate({ + search: (old) => ({ + ...old, + notes: notes() ? notes() : undefined, + }), + params: true, + replace: true, + }) + }) return (
filterBy, - () => { - setFilterDraft(filterBy ?? '') - }, - ), + () => filterBy, + () => { + setFilterDraft(filterBy ?? '') + }, ) const sortedUsers = createMemo(() => { @@ -508,22 +503,20 @@ function UsersLayoutComponent() { replace: true, }) - createEffect( - on(filterDraft, () => { - navigate({ - search: (old) => { - return { - ...old, - usersView: { - ...old.usersView, - filterBy: filterDraft() || undefined, - }, - } - }, - replace: true, - }) - }), - ) + createEffect(filterDraft, () => { + navigate({ + search: (old) => { + return { + ...old, + usersView: { + ...old.usersView, + filterBy: filterDraft() || undefined, + }, + } + }, + replace: true, + }) + }) return (
@@ -727,12 +720,13 @@ function LoginComponent() { // Ah, the subtle nuances of client side auth. 🙄 createRenderEffect( - on([() => routeContext().status, () => search().redirect], () => { + () => [routeContext().status, search().redirect], + () => { const redirect = search().redirect if (routeContext().status === 'loggedIn' && redirect) { router.history.push(redirect) } - }), + }, ) return routeContext().status === 'loggedIn' ? ( @@ -1021,11 +1015,9 @@ function useSessionStorage(key: string, initialValue: T) { })(), ) - createEffect( - on(state, () => { - sessionStorage.setItem(key, JSON.stringify(state())) - }), - ) + createEffect(state, () => { + sessionStorage.setItem(key, JSON.stringify(state())) + }) return [state, setState] as const } diff --git a/examples/solid/kitchen-sink/src/vite-env.d.ts b/examples/solid/kitchen-sink/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/solid/kitchen-sink/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/solid/large-file-based/package.json b/examples/solid/large-file-based/package.json index cd758ab704..32823ef30d 100644 --- a/examples/solid/large-file-based/package.json +++ b/examples/solid/large-file-based/package.json @@ -4,7 +4,7 @@ "type": "module", "scripts": { "dev": "vite --port 3000", - "build": "vite build && tsc --noEmit", + "build": "vite build", "preview": "vite preview", "start": "vite", "gen": "node ./src/createRoutes.mjs", @@ -12,19 +12,19 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/router-plugin": "^1.169.0", - "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-query": "6.0.0-alpha.1", + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", + "@tanstack/router-plugin": "^1.166.14", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", "redaxios": "^0.5.1", - "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", - "vite-plugin-solid": "^2.11.11" + "vite-plugin-solid": "3.0.0-next.3", + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/solid/large-file-based/src/main.tsx b/examples/solid/large-file-based/src/main.tsx index 07b1d8be85..c93206359d 100644 --- a/examples/solid/large-file-based/src/main.tsx +++ b/examples/solid/large-file-based/src/main.tsx @@ -1,4 +1,4 @@ -import { render } from 'solid-js/web' +import { render } from '@solidjs/web' import { RouterProvider, createRouter } from '@tanstack/solid-router' import { QueryClient } from '@tanstack/solid-query' import { routeTree } from './routeTree.gen' diff --git a/examples/solid/large-file-based/src/routeTree.gen.ts b/examples/solid/large-file-based/src/routeTree.gen.ts index ea7329778c..d345b69acf 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 IndexRouteImport } from './routes/index' -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 LinkPropsRouteImport } from './routes/linkProps' +import { Route as AbsoluteRouteImport } from './routes/absolute' import { Route as SearchRouteRouteImport } from './routes/search/route' -import { Route as ParamsParamsPlaceholderRouteImport } from './routes/params/$paramsPlaceholder' +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 ParamsParamsPlaceholderRouteImport } from './routes/params/$paramsPlaceholder' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const AbsoluteRoute = AbsoluteRouteImport.update({ - id: '/absolute', - path: '/absolute', +const RelativeRoute = RelativeRouteImport.update({ + id: '/relative', + path: '/relative', getParentRoute: () => rootRouteImport, } as any) const LinkPropsRoute = LinkPropsRouteImport.update({ @@ -33,14 +28,9 @@ const LinkPropsRoute = LinkPropsRouteImport.update({ path: '/linkProps', getParentRoute: () => rootRouteImport, } as any) -const ParamsRouteRoute = ParamsRouteRouteImport.update({ - id: '/params', - path: '/params', - getParentRoute: () => rootRouteImport, -} as any) -const RelativeRoute = RelativeRouteImport.update({ - id: '/relative', - path: '/relative', +const AbsoluteRoute = AbsoluteRouteImport.update({ + id: '/absolute', + path: '/absolute', getParentRoute: () => rootRouteImport, } as any) const SearchRouteRoute = SearchRouteRouteImport.update({ @@ -48,16 +38,26 @@ const SearchRouteRoute = SearchRouteRouteImport.update({ path: '/search', getParentRoute: () => rootRouteImport, } as any) -const ParamsParamsPlaceholderRoute = ParamsParamsPlaceholderRouteImport.update({ - id: '/$paramsPlaceholder', - path: '/$paramsPlaceholder', - getParentRoute: () => ParamsRouteRoute, +const ParamsRouteRoute = ParamsRouteRouteImport.update({ + id: '/params', + path: '/params', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, } as any) const SearchSearchPlaceholderRoute = SearchSearchPlaceholderRouteImport.update({ id: '/searchPlaceholder', path: '/searchPlaceholder', getParentRoute: () => SearchRouteRoute, } as any) +const ParamsParamsPlaceholderRoute = ParamsParamsPlaceholderRouteImport.update({ + id: '/$paramsPlaceholder', + path: '/$paramsPlaceholder', + getParentRoute: () => ParamsRouteRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -134,18 +134,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/absolute': { - id: '/absolute' - path: '/absolute' - fullPath: '/absolute' - preLoaderRoute: typeof AbsoluteRouteImport + '/relative': { + id: '/relative' + path: '/relative' + fullPath: '/relative' + preLoaderRoute: typeof RelativeRouteImport parentRoute: typeof rootRouteImport } '/linkProps': { @@ -155,18 +148,11 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof LinkPropsRouteImport parentRoute: typeof rootRouteImport } - '/params': { - id: '/params' - path: '/params' - fullPath: '/params' - preLoaderRoute: typeof ParamsRouteRouteImport - parentRoute: typeof rootRouteImport - } - '/relative': { - id: '/relative' - path: '/relative' - fullPath: '/relative' - preLoaderRoute: typeof RelativeRouteImport + '/absolute': { + id: '/absolute' + path: '/absolute' + fullPath: '/absolute' + preLoaderRoute: typeof AbsoluteRouteImport parentRoute: typeof rootRouteImport } '/search': { @@ -176,12 +162,19 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof SearchRouteRouteImport parentRoute: typeof rootRouteImport } - '/params/$paramsPlaceholder': { - id: '/params/$paramsPlaceholder' - path: '/$paramsPlaceholder' - fullPath: '/params/$paramsPlaceholder' - preLoaderRoute: typeof ParamsParamsPlaceholderRouteImport - parentRoute: typeof ParamsRouteRoute + '/params': { + id: '/params' + path: '/params' + fullPath: '/params' + preLoaderRoute: typeof ParamsRouteRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport } '/search/searchPlaceholder': { id: '/search/searchPlaceholder' @@ -190,6 +183,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof SearchSearchPlaceholderRouteImport parentRoute: typeof SearchRouteRoute } + '/params/$paramsPlaceholder': { + id: '/params/$paramsPlaceholder' + path: '/$paramsPlaceholder' + fullPath: '/params/$paramsPlaceholder' + preLoaderRoute: typeof ParamsParamsPlaceholderRouteImport + parentRoute: typeof ParamsRouteRoute + } } } diff --git a/examples/solid/large-file-based/src/vite-env.d.ts b/examples/solid/large-file-based/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/solid/large-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/solid/location-masking/package.json b/examples/solid/location-masking/package.json index 7d2fbb6756..b65df0bb37 100644 --- a/examples/solid/location-masking/package.json +++ b/examples/solid/location-masking/package.json @@ -4,23 +4,23 @@ "type": "module", "scripts": { "dev": "vite --port 3000", - "build": "vite build && tsc --noEmit", + "build": "vite build", "preview": "vite preview", "start": "vite" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "solid-js": "^1.9.10", + "@tanstack/solid-query": "6.0.0-alpha.1", + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", "redaxios": "^0.5.1", "tailwindcss": "^4.2.2" }, "devDependencies": { - "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-solid": "3.0.0-next.3", + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/solid/location-masking/src/main.tsx b/examples/solid/location-masking/src/main.tsx index ed090265b9..7ee20a252e 100644 --- a/examples/solid/location-masking/src/main.tsx +++ b/examples/solid/location-masking/src/main.tsx @@ -1,5 +1,5 @@ import type { JSX } from 'solid-js' -import { render } from 'solid-js/web' +import { render } from '@solidjs/web' import { ErrorComponent, Link, diff --git a/examples/solid/location-masking/src/vite-env.d.ts b/examples/solid/location-masking/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/solid/location-masking/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/solid/navigation-blocking/package.json b/examples/solid/navigation-blocking/package.json index 2338d32305..ea22f31456 100644 --- a/examples/solid/navigation-blocking/package.json +++ b/examples/solid/navigation-blocking/package.json @@ -4,23 +4,23 @@ "type": "module", "scripts": { "dev": "vite --port 3000", - "build": "vite build && tsc --noEmit", + "build": "vite build", "preview": "vite preview", "start": "vite" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "solid-js": "^1.9.10", + "@tanstack/solid-query": "6.0.0-alpha.1", + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", "redaxios": "^0.5.1", "tailwindcss": "^4.2.2" }, "devDependencies": { - "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-solid": "3.0.0-next.3", + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/solid/navigation-blocking/src/main.tsx b/examples/solid/navigation-blocking/src/main.tsx index 81a4028604..3b8c3031b3 100644 --- a/examples/solid/navigation-blocking/src/main.tsx +++ b/examples/solid/navigation-blocking/src/main.tsx @@ -1,5 +1,5 @@ import { createSignal } from 'solid-js' -import { render } from 'solid-js/web' +import { render } from '@solidjs/web' import { Link, Outlet, diff --git a/examples/solid/navigation-blocking/src/vite-env.d.ts b/examples/solid/navigation-blocking/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/solid/navigation-blocking/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/solid/quickstart-esbuild-file-based/build.js b/examples/solid/quickstart-esbuild-file-based/build.js index af5e01b4cd..7952dc5d4e 100644 --- a/examples/solid/quickstart-esbuild-file-based/build.js +++ b/examples/solid/quickstart-esbuild-file-based/build.js @@ -14,7 +14,10 @@ const ctx = await esbuild.context({ target: ['esnext'], sourcemap: true, conditions: ['style'], - plugins: [solidPlugin(), tanstackRouter({ target: 'solid' })], + plugins: [ + solidPlugin({ solid: { moduleName: '@solidjs/web' } }), + tanstackRouter({ target: 'solid', autoCodeSplitting: true }), + ], }) if (isDev) { diff --git a/examples/solid/quickstart-esbuild-file-based/package.json b/examples/solid/quickstart-esbuild-file-based/package.json index 9bcc9a08d0..cf2749048c 100644 --- a/examples/solid/quickstart-esbuild-file-based/package.json +++ b/examples/solid/quickstart-esbuild-file-based/package.json @@ -9,13 +9,14 @@ "start": "dev" }, "dependencies": { - "@tanstack/router-plugin": "^1.169.0", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.166.14", + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", "redaxios": "^0.5.1", - "solid-js": "^1.9.10", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { "esbuild": "^0.27.4", diff --git a/examples/solid/quickstart-esbuild-file-based/src/main.tsx b/examples/solid/quickstart-esbuild-file-based/src/main.tsx index 58c2fcf308..45eeb1f759 100644 --- a/examples/solid/quickstart-esbuild-file-based/src/main.tsx +++ b/examples/solid/quickstart-esbuild-file-based/src/main.tsx @@ -1,4 +1,4 @@ -import { render } from 'solid-js/web' +import { render } from '@solidjs/web' import { RouterProvider, createRouter } from '@tanstack/solid-router' import { routeTree } from './routeTree.gen' import './styles.css' 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 deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/solid/quickstart-esbuild-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/solid/quickstart-file-based/package.json b/examples/solid/quickstart-file-based/package.json index 920154566d..f9cd81f4cc 100644 --- a/examples/solid/quickstart-file-based/package.json +++ b/examples/solid/quickstart-file-based/package.json @@ -10,18 +10,18 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", "redaxios": "^0.5.1", - "solid-js": "^1.9.10", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "@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" + "@tanstack/router-plugin": "^1.166.14", + "typescript": "^5.7.2", + "vite": "^8.0.0", + "vite-plugin-solid": "3.0.0-next.3" } } diff --git a/examples/solid/quickstart-file-based/src/main.tsx b/examples/solid/quickstart-file-based/src/main.tsx index 8128384193..4bd8c56ef3 100644 --- a/examples/solid/quickstart-file-based/src/main.tsx +++ b/examples/solid/quickstart-file-based/src/main.tsx @@ -1,4 +1,4 @@ -import { render } from 'solid-js/web' +import { render } from '@solidjs/web' import { RouterProvider, createRouter } from '@tanstack/solid-router' import { routeTree } from './routeTree.gen' import './styles.css' diff --git a/examples/solid/quickstart-file-based/src/routeTree.gen.ts b/examples/solid/quickstart-file-based/src/routeTree.gen.ts index 98df1e83d8..333a815c38 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 IndexRouteImport } from './routes/index' import { Route as AboutRouteImport } from './routes/about' +import { Route as IndexRouteImport } from './routes/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const AboutRoute = AboutRouteImport.update({ id: '/about', path: '/about', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/about': { id: '/about' path: '/about' @@ -65,6 +58,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof AboutRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/solid/quickstart-file-based/src/vite-env.d.ts b/examples/solid/quickstart-file-based/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/solid/quickstart-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/solid/quickstart-rspack-file-based/package.json b/examples/solid/quickstart-rspack-file-based/package.json index 2d9c886ac3..344a69f43a 100644 --- a/examples/solid/quickstart-rspack-file-based/package.json +++ b/examples/solid/quickstart-rspack-file-based/package.json @@ -9,18 +9,18 @@ }, "dependencies": { "@tailwindcss/postcss": "^4.2.2", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", "postcss": "^8.5.1", - "solid-js": "^1.9.10", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", "tailwindcss": "^4.2.2" }, "devDependencies": { - "@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" + "@rsbuild/core": "^1.2.4", + "@rsbuild/plugin-babel": "^1.0.6", + "@rsbuild/plugin-solid": "^1.0.6", + "@tanstack/router-plugin": "^1.166.14", + "typescript": "^5.6.2" } } diff --git a/examples/solid/quickstart-rspack-file-based/rsbuild.config.ts b/examples/solid/quickstart-rspack-file-based/rsbuild.config.ts index 6cf2622e65..57dfa42e0b 100644 --- a/examples/solid/quickstart-rspack-file-based/rsbuild.config.ts +++ b/examples/solid/quickstart-rspack-file-based/rsbuild.config.ts @@ -8,11 +8,20 @@ export default defineConfig({ pluginBabel({ include: /\.(?:jsx|tsx)$/, }), - pluginSolid(), + pluginSolid({ + solidPresetOptions: { + moduleName: '@solidjs/web', + }, + }), ], tools: { rspack: { plugins: [tanstackRouter({ target: 'solid', autoCodeSplitting: true })], + resolve: { + alias: { + 'solid-js/web': '@solidjs/web', + }, + }, }, }, }) diff --git a/examples/solid/quickstart-rspack-file-based/src/index.tsx b/examples/solid/quickstart-rspack-file-based/src/index.tsx index 782382dcfd..c29380ee41 100644 --- a/examples/solid/quickstart-rspack-file-based/src/index.tsx +++ b/examples/solid/quickstart-rspack-file-based/src/index.tsx @@ -1,4 +1,4 @@ -import { render } from 'solid-js/web' +import { render } from '@solidjs/web' import App from './app' const rootElement = document.getElementById('root')! 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 98df1e83d8..333a815c38 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 IndexRouteImport } from './routes/index' import { Route as AboutRouteImport } from './routes/about' +import { Route as IndexRouteImport } from './routes/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const AboutRoute = AboutRouteImport.update({ id: '/about', path: '/about', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/about': { id: '/about' path: '/about' @@ -65,6 +58,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof AboutRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } } } 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 deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/solid/quickstart-rspack-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/solid/quickstart-webpack-file-based/package.json b/examples/solid/quickstart-webpack-file-based/package.json index 16167be207..1939740318 100644 --- a/examples/solid/quickstart-webpack-file-based/package.json +++ b/examples/solid/quickstart-webpack-file-based/package.json @@ -7,26 +7,26 @@ "build": "webpack build && tsc --noEmit" }, "dependencies": { - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "solid-js": "^1.9.10", + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", "tailwindcss": "^4.2.2" }, "devDependencies": { "@babel/core": "^7.28.5", "@babel/preset-typescript": "^7.27.1", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/router-plugin": "^1.166.14", "babel-loader": "^10.0.0", - "babel-preset-solid": "^1.9.10", + "babel-preset-solid": "2.0.0-beta.4", "css-loader": "^7.1.2", "html-webpack-plugin": "^5.6.3", "postcss": "^8.5.6", "postcss-loader": "^8.2.0", "style-loader": "^4.0.0", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", + "typescript": "^5.7.2", "webpack": "^5.97.1", "webpack-cli": "^5.1.4", - "webpack-dev-server": "^5.2.4" + "webpack-dev-server": "^5.2.0" } } diff --git a/examples/solid/quickstart-webpack-file-based/src/index.tsx b/examples/solid/quickstart-webpack-file-based/src/index.tsx index 545d22a618..8e142a714d 100644 --- a/examples/solid/quickstart-webpack-file-based/src/index.tsx +++ b/examples/solid/quickstart-webpack-file-based/src/index.tsx @@ -1,4 +1,4 @@ -import { render } from 'solid-js/web' +import { render } from '@solidjs/web' import App from './app' import './styles.css' 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 98df1e83d8..333a815c38 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 IndexRouteImport } from './routes/index' import { Route as AboutRouteImport } from './routes/about' +import { Route as IndexRouteImport } from './routes/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const AboutRoute = AboutRouteImport.update({ id: '/about', path: '/about', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/about': { id: '/about' path: '/about' @@ -65,6 +58,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof AboutRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } } } 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 deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/solid/quickstart-webpack-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/solid/quickstart/package.json b/examples/solid/quickstart/package.json index 454382e8cc..7e709f18b9 100644 --- a/examples/solid/quickstart/package.json +++ b/examples/solid/quickstart/package.json @@ -10,15 +10,13 @@ }, "dependencies": { "@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.2.2" - }, - "devDependencies": { - "vite-plugin-solid": "^2.11.11", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", + "tailwindcss": "^4.2.2", + "vite-plugin-solid": "3.0.0-next.3", + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/solid/quickstart/src/main.tsx b/examples/solid/quickstart/src/main.tsx index 79daf132e3..3ed73749d2 100644 --- a/examples/solid/quickstart/src/main.tsx +++ b/examples/solid/quickstart/src/main.tsx @@ -1,4 +1,4 @@ -import { render } from 'solid-js/web' +import { render } from '@solidjs/web' import { Link, Outlet, diff --git a/examples/solid/quickstart/src/vite-env.d.ts b/examples/solid/quickstart/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/solid/quickstart/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/solid/router-monorepo-simple-lazy/package.json b/examples/solid/router-monorepo-simple-lazy/package.json index 1d60ab2765..022413039e 100644 --- a/examples/solid/router-monorepo-simple-lazy/package.json +++ b/examples/solid/router-monorepo-simple-lazy/package.json @@ -8,18 +8,18 @@ "dev": "pnpm router build && pnpm post-feature build && pnpm app dev" }, "dependencies": { - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", - "solid-js": "^1.9.10", + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", + "@tanstack/router-plugin": "^1.166.14", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", "redaxios": "^0.5.1" }, "devDependencies": { "@types/node": "^22.7.4", - "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-solid": "3.0.0-next.3", + "typescript": "^5.7.2", + "vite": "^8.0.0", "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 a2e018fa96..1fb91e08cd 100644 --- a/examples/solid/router-monorepo-simple-lazy/packages/app/package.json +++ b/examples/solid/router-monorepo-simple-lazy/packages/app/package.json @@ -18,11 +18,10 @@ "@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", - "@tanstack/solid-router-devtools": "^1.167.3", + "typescript": "^5.7.2", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", "tailwindcss": "^4.2.2", - "vite": "^8.0.14", + "vite": "^8.0.0", "vite-plugin-dts": "^4.5.4", "@tailwindcss/vite": "^4.2.2" }, diff --git a/examples/solid/router-monorepo-simple-lazy/packages/app/src/main.tsx b/examples/solid/router-monorepo-simple-lazy/packages/app/src/main.tsx index 91ee95bd38..46aebbe69f 100644 --- a/examples/solid/router-monorepo-simple-lazy/packages/app/src/main.tsx +++ b/examples/solid/router-monorepo-simple-lazy/packages/app/src/main.tsx @@ -1,4 +1,4 @@ -import { render } from 'solid-js/web' +import { render } from '@solidjs/web' import { RouterProvider } from '@tanstack/solid-router' import { router } from '@router-solid-mono-simple-lazy/router' import { RootComponent } from './rootComponent' 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 849be06ce6..4cd9ad6378 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 @@ -16,15 +16,15 @@ } }, "dependencies": { - "@tanstack/solid-query": "^5.90.9", + "@tanstack/solid-query": "6.0.0-alpha.1", "@router-solid-mono-simple-lazy/router": "workspace:*", - "solid-js": "^1.9.10" + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4" }, "devDependencies": { - "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-solid": "3.0.0-next.3", + "typescript": "^5.7.2", + "vite": "^8.0.0", "vite-plugin-dts": "^4.5.4" } } diff --git a/examples/solid/router-monorepo-simple-lazy/packages/router/package.json b/examples/solid/router-monorepo-simple-lazy/packages/router/package.json index 0672c42931..3fbd99c510 100644 --- a/examples/solid/router-monorepo-simple-lazy/packages/router/package.json +++ b/examples/solid/router-monorepo-simple-lazy/packages/router/package.json @@ -8,18 +8,18 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "dependencies": { - "@tanstack/history": "^1.162.5", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/history": "^1.161.6", + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/router-plugin": "^1.166.14", "redaxios": "^0.5.1", - "zod": "^4.4.3", - "solid-js": "^1.9.10" + "zod": "^3.24.2", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4" }, "devDependencies": { - "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-solid": "3.0.0-next.3", + "typescript": "^5.7.2", + "vite": "^8.0.0", "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 8760312d24..e8f1a5370b 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 IndexRouteImport } from './routes/index' import { Route as PostIdRouteImport } from './routes/$postId' +import { Route as IndexRouteImport } from './routes/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const PostIdRoute = PostIdRouteImport.update({ id: '/$postId', path: '/$postId', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/$postId': { id: '/$postId' path: '/$postId' @@ -65,6 +58,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PostIdRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + 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 018ebfd3d5..fd99b4b7de 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 @@ -31,7 +31,7 @@ export default defineConfig({ }, rolldownOptions: { // External packages that should not be bundled into your library. - external: ['solid-js', 'solid-js/web', '@tanstack/solid-router'], + external: ['solid-js', '@solidjs/web', '@tanstack/solid-router'], }, }, }) diff --git a/examples/solid/router-monorepo-simple/package.json b/examples/solid/router-monorepo-simple/package.json index 3770256692..01ad7bb9b7 100644 --- a/examples/solid/router-monorepo-simple/package.json +++ b/examples/solid/router-monorepo-simple/package.json @@ -8,18 +8,18 @@ "dev": "pnpm router build && pnpm post-feature build && pnpm app dev" }, "dependencies": { - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", - "solid-js": "^1.9.10", + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", + "@tanstack/router-plugin": "^1.166.14", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", "redaxios": "^0.5.1" }, "devDependencies": { "@types/node": "^22.7.4", - "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-solid": "3.0.0-next.3", + "typescript": "^5.7.2", + "vite": "^8.0.0", "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 61234ac455..a67b4f69bf 100644 --- a/examples/solid/router-monorepo-simple/packages/app/package.json +++ b/examples/solid/router-monorepo-simple/packages/app/package.json @@ -11,14 +11,14 @@ "dependencies": { "@router-solid-mono-simple/post-feature": "workspace:*", "@router-solid-mono-simple/router": "workspace:*", - "solid-js": "^1.9.10" + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4" }, "devDependencies": { - "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", + "vite-plugin-solid": "3.0.0-next.3", + "typescript": "^5.7.2", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", + "vite": "^8.0.0", "tailwindcss": "^4.2.2", "vite-plugin-dts": "^4.5.4", "@tailwindcss/vite": "^4.2.2" diff --git a/examples/solid/router-monorepo-simple/packages/app/src/main.tsx b/examples/solid/router-monorepo-simple/packages/app/src/main.tsx index d50c77774f..bad3c369fa 100644 --- a/examples/solid/router-monorepo-simple/packages/app/src/main.tsx +++ b/examples/solid/router-monorepo-simple/packages/app/src/main.tsx @@ -1,4 +1,4 @@ -import { render } from 'solid-js/web' +import { render } from '@solidjs/web' import { RouterProvider } from '@tanstack/solid-router' import { Outlet, router } from '@router-solid-mono-simple/router' import { 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 eb8005b953..b43a5dd31b 100644 --- a/examples/solid/router-monorepo-simple/packages/post-feature/package.json +++ b/examples/solid/router-monorepo-simple/packages/post-feature/package.json @@ -9,13 +9,13 @@ "types": "./dist/index.d.ts", "dependencies": { "@router-solid-mono-simple/router": "workspace:*", - "solid-js": "^1.9.10" + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4" }, "devDependencies": { - "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-solid": "3.0.0-next.3", + "typescript": "^5.7.2", + "vite": "^8.0.0", "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 6593e68056..fec43f1332 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 @@ -33,7 +33,7 @@ export default defineConfig({ // External packages that should not be bundled into your library. external: [ 'solid-js', - 'solid-js/web', + '@solidjs/web', '@tanstack/solid-router', '@router-solid-mono-simple/post-feature', '@router-solid-mono-simple/router', diff --git a/examples/solid/router-monorepo-simple/packages/router/package.json b/examples/solid/router-monorepo-simple/packages/router/package.json index ca08511d3e..fff70dce24 100644 --- a/examples/solid/router-monorepo-simple/packages/router/package.json +++ b/examples/solid/router-monorepo-simple/packages/router/package.json @@ -8,18 +8,18 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "dependencies": { - "@tanstack/history": "^1.162.5", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/history": "^1.161.6", + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/router-plugin": "^1.166.14", "redaxios": "^0.5.1", - "zod": "^4.4.3", - "solid-js": "^1.9.10" + "zod": "^3.24.2", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4" }, "devDependencies": { - "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-solid": "3.0.0-next.3", + "typescript": "^5.7.2", + "vite": "^8.0.0", "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 8760312d24..e8f1a5370b 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 IndexRouteImport } from './routes/index' import { Route as PostIdRouteImport } from './routes/$postId' +import { Route as IndexRouteImport } from './routes/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const PostIdRoute = PostIdRouteImport.update({ id: '/$postId', path: '/$postId', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/$postId': { id: '/$postId' path: '/$postId' @@ -65,6 +58,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PostIdRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + 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 018ebfd3d5..fd99b4b7de 100644 --- a/examples/solid/router-monorepo-simple/packages/router/vite.config.ts +++ b/examples/solid/router-monorepo-simple/packages/router/vite.config.ts @@ -31,7 +31,7 @@ export default defineConfig({ }, rolldownOptions: { // External packages that should not be bundled into your library. - external: ['solid-js', 'solid-js/web', '@tanstack/solid-router'], + external: ['solid-js', '@solidjs/web', '@tanstack/solid-router'], }, }, }) diff --git a/examples/solid/router-monorepo-solid-query/package.json b/examples/solid/router-monorepo-solid-query/package.json index 3d9fd2e2d0..fb477f4de6 100644 --- a/examples/solid/router-monorepo-solid-query/package.json +++ b/examples/solid/router-monorepo-solid-query/package.json @@ -10,20 +10,20 @@ "dev": "pnpm post-query build && pnpm router build && pnpm post-feature build && pnpm app dev" }, "dependencies": { - "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-query-devtools": "^5.90.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", + "@tanstack/solid-query": "6.0.0-alpha.1", + "@tanstack/solid-query-devtools": "6.0.0-alpha.1", + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", + "@tanstack/router-plugin": "^1.166.14", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", "redaxios": "^0.5.1" }, "devDependencies": { "@types/node": "^22.10.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite-plugin-solid": "^2.11.11", - "vite": "^8.0.14", + "typescript": "^5.7.2", + "vite-plugin-solid": "3.0.0-next.3", + "vite": "^8.0.0", "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 76bb059de5..88dffc215a 100644 --- a/examples/solid/router-monorepo-solid-query/packages/app/package.json +++ b/examples/solid/router-monorepo-solid-query/packages/app/package.json @@ -9,18 +9,18 @@ "start": "vite" }, "dependencies": { - "@tanstack/solid-query": "^5.90.9", + "@tanstack/solid-query": "6.0.0-alpha.1", "@router-solid-mono-solid-query/post-feature": "workspace:*", "@router-solid-mono-solid-query/router": "workspace:*", - "solid-js": "^1.9.10" + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4" }, "devDependencies": { - "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-plugin-solid": "3.0.0-next.3", + "typescript": "^5.7.2", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", "tailwindcss": "^4.2.2", - "vite": "^8.0.14", + "vite": "^8.0.0", "vite-plugin-dts": "^4.5.4", "@tailwindcss/vite": "^4.2.2" }, diff --git a/examples/solid/router-monorepo-solid-query/packages/app/src/main.tsx b/examples/solid/router-monorepo-solid-query/packages/app/src/main.tsx index 8740ce06a7..fe84daf44f 100644 --- a/examples/solid/router-monorepo-solid-query/packages/app/src/main.tsx +++ b/examples/solid/router-monorepo-solid-query/packages/app/src/main.tsx @@ -1,4 +1,4 @@ -import { render } from 'solid-js/web' +import { render } from '@solidjs/web' import { RouterProvider } from '@tanstack/solid-router' import { QueryClientProvider } from '@tanstack/solid-query' import { queryClient, router } from '@router-solid-mono-solid-query/router' 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 39b57c7dfa..a12376a8ed 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 @@ -8,16 +8,16 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "dependencies": { - "@tanstack/solid-query": "^5.90.9", + "@tanstack/solid-query": "6.0.0-alpha.1", "@router-solid-mono-solid-query/post-query": "workspace:*", "@router-solid-mono-solid-query/router": "workspace:*", - "solid-js": "^1.9.10" + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4" }, "devDependencies": { - "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-solid": "3.0.0-next.3", + "typescript": "^5.7.2", + "vite": "^8.0.0", "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 28a231eb39..58bcbd81a0 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 @@ -33,7 +33,7 @@ export default defineConfig({ // External packages that should not be bundled into your library. external: [ 'solid-js', - 'solid-js/web', + '@solidjs/web', '@tanstack/solid-query', '@tanstack/solid-router', '@router-solid-mono-solid-query/post-query', 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 8e3a4b0e71..e3a548b079 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 @@ -8,14 +8,13 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "dependencies": { - "@tanstack/solid-query": "^5.90.9", + "@tanstack/solid-query": "6.0.0-alpha.1", "redaxios": "^0.5.1", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "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-solid": "3.0.0-next.3", + "typescript": "^5.7.2", + "vite": "^8.0.0" } } 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 0176645332..c05653db7d 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 @@ -31,7 +31,7 @@ export default defineConfig({ // External packages that should not be bundled into your library. external: [ 'solid-js', - 'solid-js/web', + '@solidjs/web', '@tanstack/solid-query', 'redaxios', ], 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 93943a1df8..b18efef0e5 100644 --- a/examples/solid/router-monorepo-solid-query/packages/router/package.json +++ b/examples/solid/router-monorepo-solid-query/packages/router/package.json @@ -8,20 +8,20 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "dependencies": { - "@tanstack/history": "^1.162.5", - "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/history": "^1.161.6", + "@tanstack/solid-query": "6.0.0-alpha.1", + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/router-plugin": "^1.166.14", "@router-solid-mono-solid-query/post-query": "workspace:*", "redaxios": "^0.5.1", - "zod": "^4.4.3", - "solid-js": "^1.9.10" + "zod": "^3.24.2", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4" }, "devDependencies": { - "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-solid": "3.0.0-next.3", + "typescript": "^5.7.2", + "vite": "^8.0.0", "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 8760312d24..e8f1a5370b 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 IndexRouteImport } from './routes/index' import { Route as PostIdRouteImport } from './routes/$postId' +import { Route as IndexRouteImport } from './routes/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const PostIdRoute = PostIdRouteImport.update({ id: '/$postId', path: '/$postId', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/$postId': { id: '/$postId' path: '/$postId' @@ -65,6 +58,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PostIdRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + 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 99874f49e5..6153a54a8b 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,3 +1,4 @@ +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 7d65f1b5f5..49d522530d 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 @@ -35,7 +35,7 @@ export default defineConfig({ // External packages that should not be bundled into your library. external: [ 'solid-js', - 'solid-js/web', + '@solidjs/web', '@tanstack/solid-query', '@tanstack/solid-router', '@router-solid-mono-solid-query/post-query', diff --git a/examples/solid/scroll-restoration/package.json b/examples/solid/scroll-restoration/package.json index eaa5a5aaea..4b35a5fd85 100644 --- a/examples/solid/scroll-restoration/package.json +++ b/examples/solid/scroll-restoration/package.json @@ -4,22 +4,20 @@ "type": "module", "scripts": { "dev": "vite --port 3000", - "build": "vite build && tsc --noEmit", + "build": "echo 'Skipped: waiting for dependency Solid 2.0 support' && exit 0", "preview": "vite preview", "start": "vite" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", "@tanstack/solid-virtual": "^3.13.0", - "solid-js": "^1.9.10", - "tailwindcss": "^4.2.2" - }, - "devDependencies": { - "vite-plugin-solid": "^2.11.11", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", + "tailwindcss": "^4.2.2", + "vite-plugin-solid": "3.0.0-next.3", + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/solid/scroll-restoration/src/main.tsx b/examples/solid/scroll-restoration/src/main.tsx index c33017ca7e..b514a45228 100644 --- a/examples/solid/scroll-restoration/src/main.tsx +++ b/examples/solid/scroll-restoration/src/main.tsx @@ -1,4 +1,4 @@ -import { render } from 'solid-js/web' +import { render } from '@solidjs/web' import { Link, Outlet, diff --git a/examples/solid/scroll-restoration/src/vite-env.d.ts b/examples/solid/scroll-restoration/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/solid/scroll-restoration/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/solid/search-validator-adapters/package.json b/examples/solid/search-validator-adapters/package.json index 59991edb36..6b55b6b6df 100644 --- a/examples/solid/search-validator-adapters/package.json +++ b/examples/solid/search-validator-adapters/package.json @@ -4,34 +4,32 @@ "type": "module", "scripts": { "dev": "vite --port 3000", - "build": "vite build && NODE_OPTIONS=--max-old-space-size=4096 tsc --noEmit", + "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", "test:unit": "vitest" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/arktype-adapter": "^1.167.0", - "@tanstack/solid-query": "^5.90.9", - "@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", + "@tanstack/arktype-adapter": "^1.166.9", + "@tanstack/solid-query": "6.0.0-alpha.1", + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", + "@tanstack/router-plugin": "^1.166.14", + "@tanstack/valibot-adapter": "^1.166.9", + "@tanstack/zod-adapter": "^1.166.9", "arktype": "^2.1.7", - "solid-js": "^1.9.10", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", "tailwindcss": "^4.2.2", "valibot": "1.0.0-beta.15", "zod": "^3.24.2" }, "devDependencies": { - "@testing-library/jest-dom": "^7.0.1", + "@testing-library/jest-dom": "^6.6.3", "@solidjs/testing-library": "^0.8.10", - "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" + "vite-plugin-solid": "3.0.0-next.3", + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/solid/search-validator-adapters/src/main.tsx b/examples/solid/search-validator-adapters/src/main.tsx index 0d3d2e1b42..be9e28bcb0 100644 --- a/examples/solid/search-validator-adapters/src/main.tsx +++ b/examples/solid/search-validator-adapters/src/main.tsx @@ -1,4 +1,4 @@ -import { render } from 'solid-js/web' +import { render } from '@solidjs/web' import { RouterProvider, createRouter } from '@tanstack/solid-router' import { QueryClient, QueryClientProvider } from '@tanstack/solid-query' import { routeTree } from './routeTree.gen' diff --git a/examples/solid/search-validator-adapters/src/routeTree.gen.ts b/examples/solid/search-validator-adapters/src/routeTree.gen.ts index 4cb97b08e9..d7aab61324 100644 --- a/examples/solid/search-validator-adapters/src/routeTree.gen.ts +++ b/examples/solid/search-validator-adapters/src/routeTree.gen.ts @@ -8,20 +8,22 @@ // 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 UsersArktypeIndexRouteImport } from './routes/users/arktype.index' -import { Route as UsersValibotIndexRouteImport } from './routes/users/valibot.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' const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const UsersArktypeIndexRoute = UsersArktypeIndexRouteImport.update({ - id: '/users/arktype/', - path: '/users/arktype/', +const UsersZodIndexRoute = UsersZodIndexRouteImport.update({ + id: '/users/zod/', + path: '/users/zod/', getParentRoute: () => rootRouteImport, } as any) const UsersValibotIndexRoute = UsersValibotIndexRouteImport.update({ @@ -29,9 +31,9 @@ const UsersValibotIndexRoute = UsersValibotIndexRouteImport.update({ path: '/users/valibot/', getParentRoute: () => rootRouteImport, } as any) -const UsersZodIndexRoute = UsersZodIndexRouteImport.update({ - id: '/users/zod/', - path: '/users/zod/', +const UsersArktypeIndexRoute = UsersArktypeIndexRouteImport.update({ + id: '/users/arktype/', + path: '/users/arktype/', getParentRoute: () => rootRouteImport, } as any) @@ -78,11 +80,11 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport 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 } '/users/valibot/': { @@ -92,16 +94,53 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof UsersValibotIndexRouteImport 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 } } } +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 33041cecaf..9a47bda715 100644 --- a/examples/solid/search-validator-adapters/src/routes/index.tsx +++ b/examples/solid/search-validator-adapters/src/routes/index.tsx @@ -1,4 +1,3 @@ -import { createFileRoute } from '@tanstack/solid-router' import { Header } from '../components/Header' import { Content } from '../components/Content' @@ -11,6 +10,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 560354627c..1a1c8cd9e6 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,6 +1,6 @@ -import { useNavigate, createFileRoute } from '@tanstack/solid-router' +import { useNavigate } from '@tanstack/solid-router' import { type } from 'arktype' -import { Suspense } from 'solid-js' +import { Loading } from 'solid-js' import { Header } from '../../components/Header' import { Users, usersQueryOptions } from '../../components/Users' import { Content } from '../../components/Content' @@ -18,9 +18,9 @@ const ArkType = () => { search={search().search} onChange={(search) => navigate({ search: { search }, replace: true })} /> - + - + ) @@ -30,7 +30,7 @@ const search = type({ search: 'string = ""', }) -export const Route = createFileRoute('/users/arktype/')({ +export const Route = createFileRoute({ 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 f9041c6126..feecf4470b 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,6 +1,6 @@ -import { useNavigate, createFileRoute } from '@tanstack/solid-router' +import { useNavigate } from '@tanstack/solid-router' import * as v from 'valibot' -import { Suspense } from 'solid-js' +import { Loading } from 'solid-js' import { Header } from '../../components/Header' import { Users, usersQueryOptions } from '../../components/Users' import { Content } from '../../components/Content' @@ -18,15 +18,15 @@ const Valibot = () => { search={search().search} onChange={(search) => navigate({ search: { search }, replace: true })} /> - + - + ) } -export const Route = createFileRoute('/users/valibot/')({ +export const Route = createFileRoute({ 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 8568476756..44dcf5c80b 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,17 +1,12 @@ -import { useNavigate, createFileRoute } from '@tanstack/solid-router' +import { useNavigate } from '@tanstack/solid-router' import { fallback, zodValidator } from '@tanstack/zod-adapter' import { z } from 'zod' -import { Suspense } from 'solid-js' +import { Loading } from 'solid-js' import { Header } from '../../components/Header' 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 ?? '', @@ -26,18 +21,18 @@ const Zod = () => { search={search()} onChange={(search) => navigate({ search: { search }, replace: true })} /> - + - + ) } -export const Route = createFileRoute('/users/zod/')({ +export const Route = createFileRoute({ validateSearch: zodValidator( z.object({ - search: fallbackString(z.string(), '').default(''), + search: fallback(z.string().optional(), undefined), }), ), loaderDeps: (opt) => ({ search: opt.search }), diff --git a/examples/solid/search-validator-adapters/src/vite-env.d.ts b/examples/solid/search-validator-adapters/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/solid/search-validator-adapters/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/solid/search-validator-adapters/tests/arktype.test.tsx b/examples/solid/search-validator-adapters/tests/arktype.test.tsx index f22a359995..4ec555fc7b 100644 --- a/examples/solid/search-validator-adapters/tests/arktype.test.tsx +++ b/examples/solid/search-validator-adapters/tests/arktype.test.tsx @@ -8,6 +8,7 @@ import { createRouter, } from '@tanstack/solid-router' +import '@testing-library/jest-dom/vitest' import { type } from 'arktype' test('can navigate to the route', async () => { diff --git a/examples/solid/search-validator-adapters/tests/jest-dom.setup.ts b/examples/solid/search-validator-adapters/tests/jest-dom.setup.ts deleted file mode 100644 index 8f7cbf15be..0000000000 --- a/examples/solid/search-validator-adapters/tests/jest-dom.setup.ts +++ /dev/null @@ -1,18 +0,0 @@ -import * as jestDomMatchers from '@testing-library/jest-dom/matchers' -import { expect } from 'vitest' -import type { TestingLibraryMatchers } from '@testing-library/jest-dom/matchers' - -// Workaround for Vitest 5: remove once testing-library/jest-dom#742 is merged -// and released, and go back to `import '@testing-library/jest-dom/vitest'`. -// That entry imports `vitest` from its own install location, which can resolve -// a different Vitest copy than the one running these tests, and its types -// augment Vitest 4's `Assertion` instead of Vitest 5's `Matchers`. -// Keep `jest-dom` in this file name: vite-plugin-solid only skips injecting -// `@testing-library/jest-dom/vitest` when a setup file path contains it. -expect.extend(jestDomMatchers) - -declare module 'vitest' { - // Type parameter names must match Vitest's declaration for the interfaces to merge. - // eslint-disable-next-line @typescript-eslint/naming-convention - interface Matchers extends TestingLibraryMatchers {} -} diff --git a/examples/solid/search-validator-adapters/tests/valibot.test.tsx b/examples/solid/search-validator-adapters/tests/valibot.test.tsx index 8594c1cb29..cd4545397c 100644 --- a/examples/solid/search-validator-adapters/tests/valibot.test.tsx +++ b/examples/solid/search-validator-adapters/tests/valibot.test.tsx @@ -8,6 +8,7 @@ import { createRouter, } from '@tanstack/solid-router' import * as v from 'valibot' +import '@testing-library/jest-dom/vitest' test('can navigate to the route', async () => { const rootRoute = createRootRoute() diff --git a/examples/solid/search-validator-adapters/vite.config.ts b/examples/solid/search-validator-adapters/vite.config.ts index 4e05d81e75..75a6d85b3f 100644 --- a/examples/solid/search-validator-adapters/vite.config.ts +++ b/examples/solid/search-validator-adapters/vite.config.ts @@ -5,13 +5,21 @@ import packageJson from './package.json' import tailwindcss from '@tailwindcss/vite' export default defineConfig({ + ...(process.env.VITEST && { + resolve: { + conditions: ['development'], + alias: { + 'solid-js/web': '@solidjs/web', + '@solidjs/signals': 'solid-js', + }, + }, + }), test: { name: packageJson.name, dir: './tests', watch: false, environment: 'jsdom', typecheck: { enabled: true }, - setupFiles: ['./tests/jest-dom.setup.ts'], server: { deps: { inline: [/@solidjs/, /@tanstack\/solid-store/], @@ -23,6 +31,7 @@ export default defineConfig({ tanstackRouter({ target: 'solid', autoCodeSplitting: true, + verboseFileRoutes: false, }), solid(), ], diff --git a/examples/solid/start-basic-auth/README.md b/examples/solid/start-basic-auth/README.md index 313c930051..90cba4aac1 100644 --- a/examples/solid/start-basic-auth/README.md +++ b/examples/solid/start-basic-auth/README.md @@ -70,13 +70,3 @@ 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 d686fdf616..4b02d68dbc 100644 --- a/examples/solid/start-basic-auth/package.json +++ b/examples/solid/start-basic-auth/package.json @@ -14,13 +14,13 @@ "@libsql/client": "^0.15.15", "@prisma/adapter-libsql": "^7.0.0", "@prisma/client": "^7.0.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", + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", + "@tanstack/solid-start": "^2.0.0-alpha.7", "redaxios": "^0.5.1", - "solid-js": "^1.9.10", - "tailwind-merge": "^3.6.0" + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", + "tailwind-merge": "^2.6.0" }, "devDependencies": { "@tailwindcss/vite": "^4.2.2", @@ -28,9 +28,9 @@ "dotenv": "^17.2.3", "prisma": "^7.0.0", "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" + "typescript": "^5.7.2", + "vite": "^8.0.0", + "vite-plugin-solid": "3.0.0-next.3", + "vite-tsconfig-paths": "^5.1.4" } } diff --git a/examples/solid/start-basic-auth/src/components/DefaultCatchBoundary.tsx b/examples/solid/start-basic-auth/src/components/DefaultCatchBoundary.tsx index f44db955a0..2c0d464a06 100644 --- a/examples/solid/start-basic-auth/src/components/DefaultCatchBoundary.tsx +++ b/examples/solid/start-basic-auth/src/components/DefaultCatchBoundary.tsx @@ -1,15 +1,17 @@ import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, useRouter, } from '@tanstack/solid-router' import type { ErrorComponentProps } from '@tanstack/solid-router' export function DefaultCatchBoundary({ error }: ErrorComponentProps) { const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, }) console.error(error) diff --git a/examples/solid/start-basic-auth/src/routeTree.gen.ts b/examples/solid/start-basic-auth/src/routeTree.gen.ts index 07924d102a..bad0f1b074 100644 --- a/examples/solid/start-basic-auth/src/routeTree.gen.ts +++ b/examples/solid/start-basic-auth/src/routeTree.gen.ts @@ -9,27 +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 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 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 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 IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const AuthedRoute = AuthedRouteImport.update({ - id: '/_authed', - getParentRoute: () => rootRouteImport, -} as any) -const LoginRoute = LoginRouteImport.update({ - id: '/login', - path: '/login', +const SignupRoute = SignupRouteImport.update({ + id: '/signup', + path: '/signup', getParentRoute: () => rootRouteImport, } as any) const LogoutRoute = LogoutRouteImport.update({ @@ -37,9 +28,18 @@ const LogoutRoute = LogoutRouteImport.update({ path: '/logout', getParentRoute: () => rootRouteImport, } as any) -const SignupRoute = SignupRouteImport.update({ - id: '/signup', - path: '/signup', +const LoginRoute = LoginRouteImport.update({ + id: '/login', + path: '/login', + getParentRoute: () => rootRouteImport, +} as any) +const AuthedRoute = AuthedRouteImport.update({ + id: '/_authed', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AuthedPostsRouteRoute = AuthedPostsRouteRouteImport.update({ @@ -120,25 +120,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_authed': { - id: '/_authed' - path: '' - fullPath: '/' - preLoaderRoute: typeof AuthedRouteImport - parentRoute: typeof rootRouteImport - } - '/login': { - id: '/login' - path: '/login' - fullPath: '/login' - preLoaderRoute: typeof LoginRouteImport + '/signup': { + id: '/signup' + path: '/signup' + fullPath: '/signup' + preLoaderRoute: typeof SignupRouteImport parentRoute: typeof rootRouteImport } '/logout': { @@ -148,11 +134,25 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof LogoutRouteImport parentRoute: typeof rootRouteImport } - '/signup': { - id: '/signup' - path: '/signup' - fullPath: '/signup' - preLoaderRoute: typeof SignupRouteImport + '/login': { + id: '/login' + path: '/login' + fullPath: '/login' + preLoaderRoute: typeof LoginRouteImport + parentRoute: typeof rootRouteImport + } + '/_authed': { + id: '/_authed' + path: '' + fullPath: '/' + preLoaderRoute: typeof AuthedRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport 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 05ad0d298a..8951a86f55 100644 --- a/examples/solid/start-basic-auth/src/routes/__root.tsx +++ b/examples/solid/start-basic-auth/src/routes/__root.tsx @@ -8,24 +8,24 @@ import { } from '@tanstack/solid-router' import { TanStackRouterDevtools } from '@tanstack/solid-router-devtools' import { createServerFn } from '@tanstack/solid-start' -import { HydrationScript } from 'solid-js/web' +import { HydrationScript } from '@solidjs/web' import type * as Solid from 'solid-js' import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary.js' import { NotFound } from '~/components/NotFound.js' import appCss from '~/styles/app.css?url' import { seo } from '~/utils/seo.js' -import { getAppSession } from '~/utils/session.js' +import { useAppSession } from '~/utils/session.js' const fetchUser = createServerFn({ method: 'GET' }).handler(async () => { // We need to auth on the server so we have access to secure cookies - const session = await getAppSession() + const session = await useAppSession() - if (!session.userEmail) { + if (!session.data.userEmail) { return null } return { - email: session.userEmail, + email: session.data.userEmail, } }) diff --git a/examples/solid/start-basic-auth/src/routes/_authed.tsx b/examples/solid/start-basic-auth/src/routes/_authed.tsx index cded7ca880..3caa846b22 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 { getAppSession } from '~/utils/session' +import { useAppSession } from '~/utils/session' export const loginFn = createServerFn({ method: 'POST' }) - .validator((d: { email: string; password: string }) => d) + .inputValidator((d: { email: string; password: string }) => d) .handler(async ({ data }) => { // Find the user const user = await prismaClient.user.findUnique({ @@ -33,10 +33,13 @@ export const loginFn = createServerFn({ method: 'POST' }) } } + // Create a session + const session = await useAppSession() + // Store the user's email in the session - const session = await getAppSession() - session.userEmail = user.email - await session.save() + await session.update({ + userEmail: user.email, + }) }) export const Route = createFileRoute('/_authed')({ diff --git a/examples/solid/start-basic-auth/src/routes/logout.tsx b/examples/solid/start-basic-auth/src/routes/logout.tsx index 56cd70cbc2..f7d624ff15 100644 --- a/examples/solid/start-basic-auth/src/routes/logout.tsx +++ b/examples/solid/start-basic-auth/src/routes/logout.tsx @@ -1,10 +1,11 @@ import { createFileRoute, redirect } from '@tanstack/solid-router' import { createServerFn } from '@tanstack/solid-start' -import { getAppSession } from '~/utils/session' +import { useAppSession } from '~/utils/session' const logoutFn = createServerFn().handler(async () => { - const session = await getAppSession() - session.destroy() + const session = await useAppSession() + + session.clear() throw redirect({ href: '/', diff --git a/examples/solid/start-basic-auth/src/routes/signup.tsx b/examples/solid/start-basic-auth/src/routes/signup.tsx index b8d6bf89fa..020e07c029 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 { getAppSession } from '~/utils/session' +import { useAppSession } from '~/utils/session' export const signupFn = createServerFn({ method: 'POST' }) - .validator( + .inputValidator( (d: { email: string; password: string; redirectUrl?: string }) => d, ) .handler(async ({ data }) => { @@ -20,6 +20,9 @@ export const signupFn = createServerFn({ method: 'POST' }) // Encrypt the password using Sha256 into plaintext const password = await hashPassword(data.password) + // Create a session + const session = await useAppSession() + if (found) { if (found.password !== password) { return { @@ -30,9 +33,9 @@ export const signupFn = createServerFn({ method: 'POST' }) } // Store the user's email in the session - const session = await getAppSession() - session.userEmail = found.email - await session.save() + await session.update({ + userEmail: found.email, + }) // Redirect to the prev page stored in the "redirect" search param throw redirect({ @@ -49,9 +52,9 @@ export const signupFn = createServerFn({ method: 'POST' }) }) // Store the user's email in the session - const session = await getAppSession() - session.userEmail = user.email - await session.save() + await session.update({ + userEmail: user.email, + }) // Redirect to the prev page stored in the "redirect" search param throw redirect({ diff --git a/examples/solid/start-basic-auth/src/utils/posts.ts b/examples/solid/start-basic-auth/src/utils/posts.ts index f62670517f..5c2e34c98d 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' }) - .validator((postId: string) => postId) + .inputValidator((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 4577764d28..120a410b60 100644 --- a/examples/solid/start-basic-auth/src/utils/session.ts +++ b/examples/solid/start-basic-auth/src/utils/session.ts @@ -1,29 +1,13 @@ -import { getIronSession } from 'iron-session' -import { getCookie, setCookie } from '@tanstack/solid-start/server' +// src/services/session.server.ts +import { useSession } from '@tanstack/solid-start/server' import type { User } from '@prisma/client' type SessionUser = { userEmail: User['email'] } -export function getAppSession() { - const password = process.env.SESSION_PASSWORD - if (!password || password.length < 32) { - throw new Error('Set SESSION_PASSWORD to at least 32 characters') - } - - return getIronSession( - { read: getCookie, write: setCookie }, - { - cookieName: 'app-session', - password, - ttl: 7 * 24 * 60 * 60, - cookieOptions: { - httpOnly: true, - sameSite: 'lax', - secure: process.env.NODE_ENV === 'production', - path: '/', - }, - }, - ) +export function useAppSession() { + return useSession({ + password: 'ChangeThisBeforeShippingToProdOrYouWillBeFired', + }) } diff --git a/examples/solid/start-basic-auth/tsconfig.json b/examples/solid/start-basic-auth/tsconfig.json index ff0556e7a8..a40235b863 100644 --- a/examples/solid/start-basic-auth/tsconfig.json +++ b/examples/solid/start-basic-auth/tsconfig.json @@ -14,6 +14,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/solid/start-basic-authjs/package.json b/examples/solid/start-basic-authjs/package.json index 2c910663bd..ee3e956943 100644 --- a/examples/solid/start-basic-authjs/package.json +++ b/examples/solid/start-basic-authjs/package.json @@ -11,20 +11,21 @@ }, "dependencies": { "@auth/core": "^0.41.1", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "@tanstack/solid-start": "^1.169.6", - "solid-js": "^1.9.10", + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", + "@tanstack/solid-start": "^2.0.0-alpha.7", "start-authjs": "^1.0.0", - "tailwind-merge": "^3.6.0" + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", + "tailwind-merge": "^2.6.0" }, "devDependencies": { "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.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" + "typescript": "^5.7.2", + "vite": "^8.0.0", + "vite-plugin-solid": "3.0.0-next.3", + "vite-tsconfig-paths": "^5.1.4" } } diff --git a/examples/solid/start-basic-authjs/src/components/DefaultCatchBoundary.tsx b/examples/solid/start-basic-authjs/src/components/DefaultCatchBoundary.tsx index beff7bc210..1ae7a0cf94 100644 --- a/examples/solid/start-basic-authjs/src/components/DefaultCatchBoundary.tsx +++ b/examples/solid/start-basic-authjs/src/components/DefaultCatchBoundary.tsx @@ -1,15 +1,17 @@ import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, useRouter, } from '@tanstack/solid-router' import type { ErrorComponentProps } from '@tanstack/solid-router' export function DefaultCatchBoundary({ error }: ErrorComponentProps) { const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, }) 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 7cc6d28cf7..e772ba9c3e 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 IndexRouteImport } from './routes/index' -import { Route as LoginRouteImport } from './routes/login' import { Route as ProtectedRouteImport } from './routes/protected' +import { Route as LoginRouteImport } from './routes/login' +import { Route as IndexRouteImport } from './routes/index' import { Route as ApiAuthSplatRouteImport } from './routes/api/auth/$' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const ProtectedRoute = ProtectedRouteImport.update({ + id: '/protected', + path: '/protected', getParentRoute: () => rootRouteImport, } as any) const LoginRoute = LoginRouteImport.update({ @@ -24,9 +24,9 @@ const LoginRoute = LoginRouteImport.update({ path: '/login', getParentRoute: () => rootRouteImport, } as any) -const ProtectedRoute = ProtectedRouteImport.update({ - id: '/protected', - path: '/protected', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const ApiAuthSplatRoute = ApiAuthSplatRouteImport.update({ @@ -71,11 +71,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/protected': { + id: '/protected' + path: '/protected' + fullPath: '/protected' + preLoaderRoute: typeof ProtectedRouteImport parentRoute: typeof rootRouteImport } '/login': { @@ -85,11 +85,11 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof LoginRouteImport parentRoute: typeof rootRouteImport } - '/protected': { - id: '/protected' - path: '/protected' - fullPath: '/protected' - preLoaderRoute: typeof ProtectedRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/api/auth/$': { diff --git a/examples/solid/start-basic-authjs/src/routes/__root.tsx b/examples/solid/start-basic-authjs/src/routes/__root.tsx index 29167dea72..27b90dc391 100644 --- a/examples/solid/start-basic-authjs/src/routes/__root.tsx +++ b/examples/solid/start-basic-authjs/src/routes/__root.tsx @@ -10,7 +10,7 @@ import { import { TanStackRouterDevtools } from '@tanstack/solid-router-devtools' import { createServerFn } from '@tanstack/solid-start' import { getRequest } from '@tanstack/solid-start/server' -import { HydrationScript } from 'solid-js/web' +import { HydrationScript } from '@solidjs/web' import { Show } from 'solid-js' import { getSession } from 'start-authjs' import type { JSX } from 'solid-js' diff --git a/examples/solid/start-basic-authjs/src/routes/login.tsx b/examples/solid/start-basic-authjs/src/routes/login.tsx index 6669e1b5b7..119783ece2 100644 --- a/examples/solid/start-basic-authjs/src/routes/login.tsx +++ b/examples/solid/start-basic-authjs/src/routes/login.tsx @@ -1,5 +1,5 @@ import { createFileRoute, redirect } from '@tanstack/solid-router' -import { createResource, Suspense } from 'solid-js' +import { createMemo, Loading } from 'solid-js' export const Route = createFileRoute('/login')({ beforeLoad: ({ context }) => { @@ -18,14 +18,14 @@ async function getCsrfToken(): Promise { } function Login() { - const [csrfToken] = createResource(getCsrfToken) + const csrfToken = createMemo(getCsrfToken) return (

Sign In

- Loading...
}> + Loading...
}> @@ -39,7 +39,7 @@ function Login() { Continue with Auth0 - +

You'll be redirected to Auth0 to complete the sign-in process. diff --git a/examples/solid/start-basic-authjs/tsconfig.json b/examples/solid/start-basic-authjs/tsconfig.json index 726f20245f..608d3ba5f3 100644 --- a/examples/solid/start-basic-authjs/tsconfig.json +++ b/examples/solid/start-basic-authjs/tsconfig.json @@ -16,6 +16,7 @@ "noUnusedParameters": true, "noFallthroughCasesInSwitch": true, "allowSyntheticDefaultImports": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] } diff --git a/examples/solid/start-basic-cloudflare/package.json b/examples/solid/start-basic-cloudflare/package.json index 7ece143f61..2810658f9b 100644 --- a/examples/solid/start-basic-cloudflare/package.json +++ b/examples/solid/start-basic-cloudflare/package.json @@ -9,23 +9,24 @@ "preview": "vite preview", "deploy": "npm run build && wrangler deploy", "cf-typegen": "wrangler types", - "postinstall": "WRANGLER_LOG=warn npm run --silent cf-typegen" + "postinstall": "npm run cf-typegen" }, "dependencies": { - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "@tanstack/solid-start": "^1.169.6", - "solid-js": "^1.9.10" + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", + "@tanstack/solid-start": "^2.0.0-alpha.7", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4" }, "devDependencies": { "@cloudflare/vite-plugin": "^1.29.0", "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.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", + "typescript": "^5.7.2", + "vite": "^8.0.0", + "vite-plugin-solid": "3.0.0-next.3", + "vite-tsconfig-paths": "^5.1.4", "wrangler": "^4.74.0" } } diff --git a/examples/solid/start-basic-cloudflare/src/components/DefaultCatchBoundary.tsx b/examples/solid/start-basic-cloudflare/src/components/DefaultCatchBoundary.tsx index beff7bc210..1ae7a0cf94 100644 --- a/examples/solid/start-basic-cloudflare/src/components/DefaultCatchBoundary.tsx +++ b/examples/solid/start-basic-cloudflare/src/components/DefaultCatchBoundary.tsx @@ -1,15 +1,17 @@ import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, useRouter, } from '@tanstack/solid-router' import type { ErrorComponentProps } from '@tanstack/solid-router' export function DefaultCatchBoundary({ error }: ErrorComponentProps) { const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, }) 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 7cba7e8958..c3f6976d03 100644 --- a/examples/solid/start-basic-cloudflare/src/routeTree.gen.ts +++ b/examples/solid/start-basic-cloudflare/src/routeTree.gen.ts @@ -9,46 +9,27 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as 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 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 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 PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as ApiUsersRouteImport } from './routes/api/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 PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' -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', +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', getParentRoute: () => rootRouteImport, } as any) const RedirectRoute = RedirectRouteImport.update({ @@ -56,9 +37,53 @@ const RedirectRoute = RedirectRouteImport.update({ path: '/redirect', getParentRoute: () => rootRouteImport, } as any) -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', + getParentRoute: () => rootRouteImport, +} as any) +const DeferredRoute = DeferredRouteImport.update({ + id: '/deferred', + path: '/deferred', + getParentRoute: () => rootRouteImport, +} as any) +const CustomScriptDotjsRoute = CustomScriptDotjsRouteImport.update({ + id: '/customScript.js', + path: '/customScript.js', + 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 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', getParentRoute: () => rootRouteImport, } as any) const PathlessLayoutNestedLayoutRoute = @@ -66,53 +91,28 @@ const PathlessLayoutNestedLayoutRoute = id: '/_nested-layout', getParentRoute: () => PathlessLayoutRoute, } as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', 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({ +const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ id: '/$userId', path: '/$userId', - getParentRoute: () => UsersRoute, + getParentRoute: () => ApiUsersRoute, } 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) +const PathlessLayoutNestedLayoutRouteARoute = + PathlessLayoutNestedLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + } as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -234,39 +234,11 @@ 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 - } - '/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 + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport parentRoute: typeof rootRouteImport } '/redirect': { @@ -276,11 +248,74 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof RedirectRouteImport parentRoute: typeof rootRouteImport } - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport + parentRoute: typeof rootRouteImport + } + '/customScript.js': { + id: '/customScript.js' + path: '/customScript.js' + fullPath: '/customScript.js' + preLoaderRoute: typeof CustomScriptDotjsRouteImport + parentRoute: typeof rootRouteImport + } + '/_pathlessLayout': { + id: '/_pathlessLayout' + 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 + } + '/api/users': { + id: '/api/users' + path: '/api/users' + fullPath: '/api/users' + preLoaderRoute: typeof ApiUsersRouteImport parentRoute: typeof rootRouteImport } '/_pathlessLayout/_nested-layout': { @@ -290,55 +325,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport parentRoute: typeof PathlessLayoutRoute } - '/api/users': { - id: '/api/users' - path: '/api/users' - fullPath: '/api/users' - preLoaderRoute: typeof ApiUsersRouteImport + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport parentRoute: typeof rootRouteImport } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute - } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute - } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRoute - } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } - '/_pathlessLayout/_nested-layout/route-b': { - id: '/_pathlessLayout/_nested-layout/route-b' - path: '/route-b' - fullPath: '/route-b' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } '/api/users/$userId': { id: '/api/users/$userId' path: '/$userId' @@ -346,12 +339,19 @@ declare module '@tanstack/solid-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 + '/_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 } } } diff --git a/examples/solid/start-basic-cloudflare/src/routes/__root.tsx b/examples/solid/start-basic-cloudflare/src/routes/__root.tsx index a8b324f1b3..883104183d 100644 --- a/examples/solid/start-basic-cloudflare/src/routes/__root.tsx +++ b/examples/solid/start-basic-cloudflare/src/routes/__root.tsx @@ -6,7 +6,7 @@ import { createRootRoute, } from '@tanstack/solid-router' import { TanStackRouterDevtools } from '@tanstack/solid-router-devtools' -import { HydrationScript } from 'solid-js/web' +import { HydrationScript } from '@solidjs/web' import type * as Solid from 'solid-js' import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary' import { NotFound } from '~/components/NotFound' diff --git a/examples/solid/start-basic-cloudflare/src/routes/deferred.tsx b/examples/solid/start-basic-cloudflare/src/routes/deferred.tsx index 1633369b20..54d334ebc6 100644 --- a/examples/solid/start-basic-cloudflare/src/routes/deferred.tsx +++ b/examples/solid/start-basic-cloudflare/src/routes/deferred.tsx @@ -1,15 +1,15 @@ import { Await, createFileRoute } from '@tanstack/solid-router' import { createServerFn } from '@tanstack/solid-start' -import { Suspense, createSignal } from 'solid-js' +import { Loading, createSignal } from 'solid-js' const personServerFn = createServerFn({ method: 'GET' }) - .validator((d: string) => d) + .inputValidator((d: string) => d) .handler(({ data: name }) => { return { name, randomNumber: Math.floor(Math.random() * 100) } }) const slowServerFn = createServerFn({ method: 'GET' }) - .validator((d: string) => d) + .inputValidator((d: string) => d) .handler(async ({ data: name }) => { await new Promise((r) => setTimeout(r, 1000)) return { name, randomNumber: Math.floor(Math.random() * 100) } @@ -37,7 +37,7 @@ function Deferred() {

{loaderData().person.name} - {loaderData().person.randomNumber}
- Loading person...
}> + Loading person...
}> ( @@ -46,13 +46,13 @@ function Deferred() {
)} /> - - Loading stuff...
}> + + Loading stuff...
}>

{data}

} /> - +
Count: {count()}
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 d2aeeb448c..ffd624dcce 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 '../components/NotFound' -import { UserErrorComponent } from '../components/UserError' +import { NotFound } from 'src/components/NotFound' +import { UserErrorComponent } from 'src/components/UserError' import type { User } from '../utils/users' export const Route = createFileRoute('/users/$userId')({ diff --git a/examples/solid/start-basic-cloudflare/src/utils/posts.tsx b/examples/solid/start-basic-cloudflare/src/utils/posts.tsx index d94aa88ece..609b78965e 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' }) - .validator((d: string) => d) + .inputValidator((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 ff0556e7a8..a40235b863 100644 --- a/examples/solid/start-basic-cloudflare/tsconfig.json +++ b/examples/solid/start-basic-cloudflare/tsconfig.json @@ -14,6 +14,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/solid/start-basic-netlify/package.json b/examples/solid/start-basic-netlify/package.json index 69299cdb79..3af7128c35 100644 --- a/examples/solid/start-basic-netlify/package.json +++ b/examples/solid/start-basic-netlify/package.json @@ -9,19 +9,20 @@ "preview": "vite preview" }, "dependencies": { - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "@tanstack/solid-start": "^1.169.6", - "solid-js": "^1.9.10" + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", + "@tanstack/solid-start": "^2.0.0-alpha.7", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4" }, "devDependencies": { - "@netlify/vite-plugin-tanstack-start": "^1.3.19", + "@netlify/vite-plugin-tanstack-start": "^1.1.4", "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.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" + "typescript": "^5.7.2", + "vite": "^8.0.0", + "vite-plugin-solid": "3.0.0-next.3", + "vite-tsconfig-paths": "^5.1.4" } } diff --git a/examples/solid/start-basic-netlify/src/components/DefaultCatchBoundary.tsx b/examples/solid/start-basic-netlify/src/components/DefaultCatchBoundary.tsx index beff7bc210..1ae7a0cf94 100644 --- a/examples/solid/start-basic-netlify/src/components/DefaultCatchBoundary.tsx +++ b/examples/solid/start-basic-netlify/src/components/DefaultCatchBoundary.tsx @@ -1,15 +1,17 @@ import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, useRouter, } from '@tanstack/solid-router' import type { ErrorComponentProps } from '@tanstack/solid-router' export function DefaultCatchBoundary({ error }: ErrorComponentProps) { const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, }) 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 7cba7e8958..c3f6976d03 100644 --- a/examples/solid/start-basic-netlify/src/routeTree.gen.ts +++ b/examples/solid/start-basic-netlify/src/routeTree.gen.ts @@ -9,46 +9,27 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as 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 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 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 PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as ApiUsersRouteImport } from './routes/api/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 PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' -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', +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', getParentRoute: () => rootRouteImport, } as any) const RedirectRoute = RedirectRouteImport.update({ @@ -56,9 +37,53 @@ const RedirectRoute = RedirectRouteImport.update({ path: '/redirect', getParentRoute: () => rootRouteImport, } as any) -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', + getParentRoute: () => rootRouteImport, +} as any) +const DeferredRoute = DeferredRouteImport.update({ + id: '/deferred', + path: '/deferred', + getParentRoute: () => rootRouteImport, +} as any) +const CustomScriptDotjsRoute = CustomScriptDotjsRouteImport.update({ + id: '/customScript.js', + path: '/customScript.js', + 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 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', getParentRoute: () => rootRouteImport, } as any) const PathlessLayoutNestedLayoutRoute = @@ -66,53 +91,28 @@ const PathlessLayoutNestedLayoutRoute = id: '/_nested-layout', getParentRoute: () => PathlessLayoutRoute, } as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', 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({ +const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ id: '/$userId', path: '/$userId', - getParentRoute: () => UsersRoute, + getParentRoute: () => ApiUsersRoute, } 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) +const PathlessLayoutNestedLayoutRouteARoute = + PathlessLayoutNestedLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + } as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -234,39 +234,11 @@ 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 - } - '/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 + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport parentRoute: typeof rootRouteImport } '/redirect': { @@ -276,11 +248,74 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof RedirectRouteImport parentRoute: typeof rootRouteImport } - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport + parentRoute: typeof rootRouteImport + } + '/customScript.js': { + id: '/customScript.js' + path: '/customScript.js' + fullPath: '/customScript.js' + preLoaderRoute: typeof CustomScriptDotjsRouteImport + parentRoute: typeof rootRouteImport + } + '/_pathlessLayout': { + id: '/_pathlessLayout' + 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 + } + '/api/users': { + id: '/api/users' + path: '/api/users' + fullPath: '/api/users' + preLoaderRoute: typeof ApiUsersRouteImport parentRoute: typeof rootRouteImport } '/_pathlessLayout/_nested-layout': { @@ -290,55 +325,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport parentRoute: typeof PathlessLayoutRoute } - '/api/users': { - id: '/api/users' - path: '/api/users' - fullPath: '/api/users' - preLoaderRoute: typeof ApiUsersRouteImport + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport parentRoute: typeof rootRouteImport } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute - } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute - } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRoute - } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } - '/_pathlessLayout/_nested-layout/route-b': { - id: '/_pathlessLayout/_nested-layout/route-b' - path: '/route-b' - fullPath: '/route-b' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } '/api/users/$userId': { id: '/api/users/$userId' path: '/$userId' @@ -346,12 +339,19 @@ declare module '@tanstack/solid-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 + '/_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 } } } diff --git a/examples/solid/start-basic-netlify/src/routes/__root.tsx b/examples/solid/start-basic-netlify/src/routes/__root.tsx index a8b324f1b3..883104183d 100644 --- a/examples/solid/start-basic-netlify/src/routes/__root.tsx +++ b/examples/solid/start-basic-netlify/src/routes/__root.tsx @@ -6,7 +6,7 @@ import { createRootRoute, } from '@tanstack/solid-router' import { TanStackRouterDevtools } from '@tanstack/solid-router-devtools' -import { HydrationScript } from 'solid-js/web' +import { HydrationScript } from '@solidjs/web' import type * as Solid from 'solid-js' import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary' import { NotFound } from '~/components/NotFound' diff --git a/examples/solid/start-basic-netlify/src/routes/deferred.tsx b/examples/solid/start-basic-netlify/src/routes/deferred.tsx index 1633369b20..54d334ebc6 100644 --- a/examples/solid/start-basic-netlify/src/routes/deferred.tsx +++ b/examples/solid/start-basic-netlify/src/routes/deferred.tsx @@ -1,15 +1,15 @@ import { Await, createFileRoute } from '@tanstack/solid-router' import { createServerFn } from '@tanstack/solid-start' -import { Suspense, createSignal } from 'solid-js' +import { Loading, createSignal } from 'solid-js' const personServerFn = createServerFn({ method: 'GET' }) - .validator((d: string) => d) + .inputValidator((d: string) => d) .handler(({ data: name }) => { return { name, randomNumber: Math.floor(Math.random() * 100) } }) const slowServerFn = createServerFn({ method: 'GET' }) - .validator((d: string) => d) + .inputValidator((d: string) => d) .handler(async ({ data: name }) => { await new Promise((r) => setTimeout(r, 1000)) return { name, randomNumber: Math.floor(Math.random() * 100) } @@ -37,7 +37,7 @@ function Deferred() {
{loaderData().person.name} - {loaderData().person.randomNumber}
- Loading person...
}> + Loading person...
}> ( @@ -46,13 +46,13 @@ function Deferred() {
)} /> - - Loading stuff...
}> + + Loading stuff...
}>

{data}

} /> - +
Count: {count()}
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 d2aeeb448c..ffd624dcce 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 '../components/NotFound' -import { UserErrorComponent } from '../components/UserError' +import { NotFound } from 'src/components/NotFound' +import { UserErrorComponent } from 'src/components/UserError' import type { User } from '../utils/users' export const Route = createFileRoute('/users/$userId')({ diff --git a/examples/solid/start-basic-netlify/src/utils/posts.tsx b/examples/solid/start-basic-netlify/src/utils/posts.tsx index d94aa88ece..609b78965e 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' }) - .validator((d: string) => d) + .inputValidator((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 ff0556e7a8..a40235b863 100644 --- a/examples/solid/start-basic-netlify/tsconfig.json +++ b/examples/solid/start-basic-netlify/tsconfig.json @@ -14,6 +14,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/solid/start-basic-nitro/package.json b/examples/solid/start-basic-nitro/package.json index 2c0dc7dad6..d8e9dee224 100644 --- a/examples/solid/start-basic-nitro/package.json +++ b/examples/solid/start-basic-nitro/package.json @@ -9,19 +9,20 @@ "preview": "vite preview" }, "dependencies": { - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "@tanstack/solid-start": "^1.169.6", - "solid-js": "^1.9.10" + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", + "@tanstack/solid-start": "^2.0.0-alpha.7", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4" }, "devDependencies": { "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.4", - "nitro": "^3.0.260903-beta", + "nitro": "^3.0.260311-beta", "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", - "vite-plugin-solid": "^2.11.11" + "typescript": "^5.7.2", + "vite": "^8.0.0", + "vite-plugin-solid": "3.0.0-next.3", + "vite-tsconfig-paths": "^5.1.4" } } diff --git a/examples/solid/start-basic-nitro/src/components/DefaultCatchBoundary.tsx b/examples/solid/start-basic-nitro/src/components/DefaultCatchBoundary.tsx index beff7bc210..1ae7a0cf94 100644 --- a/examples/solid/start-basic-nitro/src/components/DefaultCatchBoundary.tsx +++ b/examples/solid/start-basic-nitro/src/components/DefaultCatchBoundary.tsx @@ -1,15 +1,17 @@ import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, useRouter, } from '@tanstack/solid-router' import type { ErrorComponentProps } from '@tanstack/solid-router' export function DefaultCatchBoundary({ error }: ErrorComponentProps) { const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, }) 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 7cba7e8958..c3f6976d03 100644 --- a/examples/solid/start-basic-nitro/src/routeTree.gen.ts +++ b/examples/solid/start-basic-nitro/src/routeTree.gen.ts @@ -9,46 +9,27 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as 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 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 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 PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as ApiUsersRouteImport } from './routes/api/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 PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' -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', +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', getParentRoute: () => rootRouteImport, } as any) const RedirectRoute = RedirectRouteImport.update({ @@ -56,9 +37,53 @@ const RedirectRoute = RedirectRouteImport.update({ path: '/redirect', getParentRoute: () => rootRouteImport, } as any) -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', + getParentRoute: () => rootRouteImport, +} as any) +const DeferredRoute = DeferredRouteImport.update({ + id: '/deferred', + path: '/deferred', + getParentRoute: () => rootRouteImport, +} as any) +const CustomScriptDotjsRoute = CustomScriptDotjsRouteImport.update({ + id: '/customScript.js', + path: '/customScript.js', + 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 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', getParentRoute: () => rootRouteImport, } as any) const PathlessLayoutNestedLayoutRoute = @@ -66,53 +91,28 @@ const PathlessLayoutNestedLayoutRoute = id: '/_nested-layout', getParentRoute: () => PathlessLayoutRoute, } as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', 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({ +const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ id: '/$userId', path: '/$userId', - getParentRoute: () => UsersRoute, + getParentRoute: () => ApiUsersRoute, } 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) +const PathlessLayoutNestedLayoutRouteARoute = + PathlessLayoutNestedLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + } as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -234,39 +234,11 @@ 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 - } - '/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 + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport parentRoute: typeof rootRouteImport } '/redirect': { @@ -276,11 +248,74 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof RedirectRouteImport parentRoute: typeof rootRouteImport } - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport + parentRoute: typeof rootRouteImport + } + '/customScript.js': { + id: '/customScript.js' + path: '/customScript.js' + fullPath: '/customScript.js' + preLoaderRoute: typeof CustomScriptDotjsRouteImport + parentRoute: typeof rootRouteImport + } + '/_pathlessLayout': { + id: '/_pathlessLayout' + 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 + } + '/api/users': { + id: '/api/users' + path: '/api/users' + fullPath: '/api/users' + preLoaderRoute: typeof ApiUsersRouteImport parentRoute: typeof rootRouteImport } '/_pathlessLayout/_nested-layout': { @@ -290,55 +325,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport parentRoute: typeof PathlessLayoutRoute } - '/api/users': { - id: '/api/users' - path: '/api/users' - fullPath: '/api/users' - preLoaderRoute: typeof ApiUsersRouteImport + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport parentRoute: typeof rootRouteImport } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute - } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute - } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRoute - } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } - '/_pathlessLayout/_nested-layout/route-b': { - id: '/_pathlessLayout/_nested-layout/route-b' - path: '/route-b' - fullPath: '/route-b' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } '/api/users/$userId': { id: '/api/users/$userId' path: '/$userId' @@ -346,12 +339,19 @@ declare module '@tanstack/solid-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 + '/_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 } } } diff --git a/examples/solid/start-basic-nitro/src/routes/__root.tsx b/examples/solid/start-basic-nitro/src/routes/__root.tsx index a8b324f1b3..883104183d 100644 --- a/examples/solid/start-basic-nitro/src/routes/__root.tsx +++ b/examples/solid/start-basic-nitro/src/routes/__root.tsx @@ -6,7 +6,7 @@ import { createRootRoute, } from '@tanstack/solid-router' import { TanStackRouterDevtools } from '@tanstack/solid-router-devtools' -import { HydrationScript } from 'solid-js/web' +import { HydrationScript } from '@solidjs/web' import type * as Solid from 'solid-js' import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary' import { NotFound } from '~/components/NotFound' diff --git a/examples/solid/start-basic-nitro/src/routes/deferred.tsx b/examples/solid/start-basic-nitro/src/routes/deferred.tsx index 1633369b20..54d334ebc6 100644 --- a/examples/solid/start-basic-nitro/src/routes/deferred.tsx +++ b/examples/solid/start-basic-nitro/src/routes/deferred.tsx @@ -1,15 +1,15 @@ import { Await, createFileRoute } from '@tanstack/solid-router' import { createServerFn } from '@tanstack/solid-start' -import { Suspense, createSignal } from 'solid-js' +import { Loading, createSignal } from 'solid-js' const personServerFn = createServerFn({ method: 'GET' }) - .validator((d: string) => d) + .inputValidator((d: string) => d) .handler(({ data: name }) => { return { name, randomNumber: Math.floor(Math.random() * 100) } }) const slowServerFn = createServerFn({ method: 'GET' }) - .validator((d: string) => d) + .inputValidator((d: string) => d) .handler(async ({ data: name }) => { await new Promise((r) => setTimeout(r, 1000)) return { name, randomNumber: Math.floor(Math.random() * 100) } @@ -37,7 +37,7 @@ function Deferred() {
{loaderData().person.name} - {loaderData().person.randomNumber}
- Loading person...
}> + Loading person...
}> ( @@ -46,13 +46,13 @@ function Deferred() {
)} /> - - Loading stuff...
}> + + Loading stuff...

}>

{data}

} /> - +
Count: {count()}
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 d2aeeb448c..ffd624dcce 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 '../components/NotFound' -import { UserErrorComponent } from '../components/UserError' +import { NotFound } from 'src/components/NotFound' +import { UserErrorComponent } from 'src/components/UserError' import type { User } from '../utils/users' export const Route = createFileRoute('/users/$userId')({ diff --git a/examples/solid/start-basic-nitro/src/utils/posts.tsx b/examples/solid/start-basic-nitro/src/utils/posts.tsx index d94aa88ece..609b78965e 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' }) - .validator((d: string) => d) + .inputValidator((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 ff0556e7a8..a40235b863 100644 --- a/examples/solid/start-basic-nitro/tsconfig.json +++ b/examples/solid/start-basic-nitro/tsconfig.json @@ -14,6 +14,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/solid/start-basic-solid-query/package.json b/examples/solid/start-basic-solid-query/package.json index ddbb7d8764..facffdb5e2 100644 --- a/examples/solid/start-basic-solid-query/package.json +++ b/examples/solid/start-basic-solid-query/package.json @@ -5,28 +5,29 @@ "type": "module", "scripts": { "dev": "vite dev", - "build": "vite build && tsc --noEmit", + "build": "vite build", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-query-devtools": "^5.90.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/solid-query": "6.0.0-alpha.1", + "@tanstack/solid-query-devtools": "6.0.0-alpha.1", + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", + "@tanstack/solid-router-ssr-query": "^2.0.0-alpha.6", + "@tanstack/solid-start": "^2.0.0-alpha.7", "redaxios": "^0.5.1", - "solid-js": "^1.9.10", - "tailwind-merge": "^3.6.0" + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", + "tailwind-merge": "^2.6.0" }, "devDependencies": { "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.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" + "typescript": "^5.7.2", + "vite": "^8.0.0", + "vite-plugin-solid": "3.0.0-next.3", + "vite-tsconfig-paths": "^5.1.4" } } 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 f44db955a0..2c0d464a06 100644 --- a/examples/solid/start-basic-solid-query/src/components/DefaultCatchBoundary.tsx +++ b/examples/solid/start-basic-solid-query/src/components/DefaultCatchBoundary.tsx @@ -1,15 +1,17 @@ import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, useRouter, } from '@tanstack/solid-router' import type { ErrorComponentProps } from '@tanstack/solid-router' export function DefaultCatchBoundary({ error }: ErrorComponentProps) { const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, }) 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 4a1747ae36..226b599b8c 100644 --- a/examples/solid/start-basic-solid-query/src/routeTree.gen.ts +++ b/examples/solid/start-basic-solid-query/src/routeTree.gen.ts @@ -9,30 +9,26 @@ // Additionally, you should also exclude this file 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 DeferredRouteImport } from './routes/deferred' -import { Route as PostsRouteRouteImport } from './routes/posts.route' 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 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 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 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 PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as ApiUsersRouteImport } from './routes/api/users' +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 PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', +const RedirectRoute = RedirectRouteImport.update({ + id: '/redirect', + path: '/redirect', getParentRoute: () => rootRouteImport, } as any) const DeferredRoute = DeferredRouteImport.update({ @@ -40,14 +36,8 @@ const DeferredRoute = DeferredRouteImport.update({ path: '/deferred', getParentRoute: () => rootRouteImport, } as any) -const PostsRouteRoute = PostsRouteRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) -const RedirectRoute = RedirectRouteImport.update({ - id: '/redirect', - path: '/redirect', +const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ + id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, } as any) const UsersRouteRoute = UsersRouteRouteImport.update({ @@ -55,58 +45,68 @@ const UsersRouteRoute = UsersRouteRouteImport.update({ 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', +const PostsRouteRoute = PostsRouteRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ +const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', - getParentRoute: () => PostsRouteRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRouteRoute, + 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 PathlessLayoutNestedLayoutRouteARoute = - PathlessLayoutNestedLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRouteRoute, +} as any) +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/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, +} 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 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 PathlessLayoutNestedLayoutRouteARoute = + PathlessLayoutNestedLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + } as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -221,18 +221,11 @@ 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 + '/redirect': { + id: '/redirect' + path: '/redirect' + fullPath: '/redirect' + preLoaderRoute: typeof RedirectRouteImport parentRoute: typeof rootRouteImport } '/deferred': { @@ -242,18 +235,11 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof DeferredRouteImport parentRoute: typeof rootRouteImport } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteRouteImport - parentRoute: typeof rootRouteImport - } - '/redirect': { - id: '/redirect' - path: '/redirect' - fullPath: '/redirect' - preLoaderRoute: typeof RedirectRouteImport + '/_pathlessLayout': { + id: '/_pathlessLayout' + path: '' + fullPath: '/' + preLoaderRoute: typeof PathlessLayoutRouteImport parentRoute: typeof rootRouteImport } '/users': { @@ -263,33 +249,19 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof UsersRouteRouteImport 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 + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } - '/posts/': { - id: '/posts/' + '/': { + id: '/' path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRouteRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRouteRoute + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport } '/users/': { id: '/users/' @@ -298,6 +270,13 @@ declare module '@tanstack/solid-router' { 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' @@ -305,19 +284,33 @@ declare module '@tanstack/solid-router' { 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 + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRouteRoute } - '/_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': { + id: '/api/users' + path: '/api/users' + fullPath: '/api/users' + preLoaderRoute: typeof ApiUsersRouteImport + parentRoute: typeof rootRouteImport + } + '/_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 } '/api/users/$id': { id: '/api/users/$id' @@ -326,12 +319,19 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof ApiUsersIdRouteImport parentRoute: typeof ApiUsersRoute } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport - parentRoute: typeof rootRouteImport + '/_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 } } } diff --git a/examples/solid/start-basic-solid-query/src/routes/__root.tsx b/examples/solid/start-basic-solid-query/src/routes/__root.tsx index 584d35be30..3f4957f154 100644 --- a/examples/solid/start-basic-solid-query/src/routes/__root.tsx +++ b/examples/solid/start-basic-solid-query/src/routes/__root.tsx @@ -8,7 +8,7 @@ import { } from '@tanstack/solid-router' import { SolidQueryDevtools } from '@tanstack/solid-query-devtools' import { TanStackRouterDevtools } from '@tanstack/solid-router-devtools' -import { HydrationScript } from 'solid-js/web' +import { HydrationScript } from '@solidjs/web' import type * as Solid from 'solid-js' import type { QueryClient } from '@tanstack/solid-query' import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary' diff --git a/examples/solid/start-basic-solid-query/src/routes/deferred.tsx b/examples/solid/start-basic-solid-query/src/routes/deferred.tsx index 782d49bf43..1c7a5b5379 100644 --- a/examples/solid/start-basic-solid-query/src/routes/deferred.tsx +++ b/examples/solid/start-basic-solid-query/src/routes/deferred.tsx @@ -1,6 +1,6 @@ import { createFileRoute } from '@tanstack/solid-router' import { queryOptions, useQuery } from '@tanstack/solid-query' -import { Suspense, createSignal } from 'solid-js' +import { Loading, createSignal } from 'solid-js' const deferredQueryOptions = () => queryOptions({ @@ -28,9 +28,9 @@ function Deferred() { return (
- + - +
Count: {count()}
@@ -41,13 +41,17 @@ function Deferred() { function DeferredQuery() { const deferredQuery = useQuery(() => deferredQueryOptions()) - return (

Deferred Query

-
Status: {deferredQuery.data?.status}
-
Message: {deferredQuery.data?.message}
-
Time: {deferredQuery.data?.time.toISOString()}
+
Status: {deferredQuery.data?.status ?? 'loading...'}
+
Message: {deferredQuery.data?.message ?? ''}
+
+ Time:{' '} + {deferredQuery.data + ? new Date(deferredQuery.data.time).toISOString() + : ''} +
) } 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 84091f451a..528dd449d7 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' }) - .validator((d: string) => d) + .inputValidator((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 ff0556e7a8..a40235b863 100644 --- a/examples/solid/start-basic-solid-query/tsconfig.json +++ b/examples/solid/start-basic-solid-query/tsconfig.json @@ -14,6 +14,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/solid/start-basic-static/package.json b/examples/solid/start-basic-static/package.json index 8b639da68a..b548e4cfa5 100644 --- a/examples/solid/start-basic-static/package.json +++ b/examples/solid/start-basic-static/package.json @@ -10,21 +10,22 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@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", + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", + "@tanstack/solid-start": "^2.0.0-alpha.7", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", + "@tanstack/start-static-server-functions": "^1.166.15", "redaxios": "^0.5.1", - "solid-js": "^1.9.10", - "tailwind-merge": "^3.6.0" + "tailwind-merge": "^2.6.0" }, "devDependencies": { - "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.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" + "typescript": "^5.6.2", + "vite": "^8.0.0", + "vite-tsconfig-paths": "^5.1.3", + "vite-plugin-solid": "3.0.0-next.3", + "@tailwindcss/vite": "^4.2.2" } } diff --git a/examples/solid/start-basic-static/src/components/DefaultCatchBoundary.tsx b/examples/solid/start-basic-static/src/components/DefaultCatchBoundary.tsx index db574e0f90..0dff3919fd 100644 --- a/examples/solid/start-basic-static/src/components/DefaultCatchBoundary.tsx +++ b/examples/solid/start-basic-static/src/components/DefaultCatchBoundary.tsx @@ -1,15 +1,17 @@ import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, useRouter, } from '@tanstack/solid-router' import type { ErrorComponentProps } from '@tanstack/solid-router' export function DefaultCatchBoundary({ error }: ErrorComponentProps) { const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, }) 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 a94e0fcf2e..7cad5523aa 100644 --- a/examples/solid/start-basic-static/src/routeTree.gen.ts +++ b/examples/solid/start-basic-static/src/routeTree.gen.ts @@ -9,38 +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 IndexRouteImport } from './routes/index' -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 PostsIndexRouteImport } from './routes/posts.index' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +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 PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +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 IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', - getParentRoute: () => rootRouteImport, -} as any) -const DeferredRoute = DeferredRouteImport.update({ - id: '/deferred', - path: '/deferred', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', getParentRoute: () => rootRouteImport, } as any) const RedirectRoute = RedirectRouteImport.update({ @@ -48,53 +34,67 @@ const RedirectRoute = RedirectRouteImport.update({ path: '/redirect', getParentRoute: () => rootRouteImport, } as any) -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +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({ +const DeferredRoute = DeferredRouteImport.update({ + id: '/deferred', + path: '/deferred', + getParentRoute: () => rootRouteImport, +} as any) +const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ + id: '/_pathlessLayout', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', - getParentRoute: () => PostsRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, + 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 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, +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 @@ -196,32 +196,11 @@ 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 - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport parentRoute: typeof rootRouteImport } '/redirect': { @@ -231,33 +210,33 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof RedirectRouteImport parentRoute: typeof rootRouteImport } - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport + parentRoute: typeof rootRouteImport + } + '/_pathlessLayout': { + id: '/_pathlessLayout' path: '' fullPath: '/' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute + preLoaderRoute: typeof PathlessLayoutRouteImport + parentRoute: typeof rootRouteImport } - '/posts/': { - id: '/posts/' + '/': { + id: '/' 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 + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport } '/users/': { id: '/users/' @@ -266,6 +245,13 @@ declare module '@tanstack/solid-router' { 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' @@ -273,12 +259,26 @@ declare module '@tanstack/solid-router' { 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 + '/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' @@ -287,12 +287,12 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutNestedLayoutRoute } - '/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-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute } } } diff --git a/examples/solid/start-basic-static/src/routes/__root.tsx b/examples/solid/start-basic-static/src/routes/__root.tsx index fd827e635a..71c461816d 100644 --- a/examples/solid/start-basic-static/src/routes/__root.tsx +++ b/examples/solid/start-basic-static/src/routes/__root.tsx @@ -7,7 +7,7 @@ import { createRootRoute, } from '@tanstack/solid-router' import { TanStackRouterDevtools } from '@tanstack/solid-router-devtools' -import { HydrationScript } from 'solid-js/web' +import { HydrationScript } from '@solidjs/web' import type * as Solid from 'solid-js' import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary' import { NotFound } from '~/components/NotFound' diff --git a/examples/solid/start-basic-static/src/routes/deferred.tsx b/examples/solid/start-basic-static/src/routes/deferred.tsx index 17ea8b7400..3630c4ac5d 100644 --- a/examples/solid/start-basic-static/src/routes/deferred.tsx +++ b/examples/solid/start-basic-static/src/routes/deferred.tsx @@ -1,18 +1,18 @@ import { Await, createFileRoute } from '@tanstack/solid-router' import { createServerFn } from '@tanstack/solid-start' -import { Suspense, createSignal } from 'solid-js' +import { Loading, createSignal } from 'solid-js' import { staticFunctionMiddleware } from '@tanstack/start-static-server-functions' const personServerFn = createServerFn({ method: 'GET' }) .middleware([staticFunctionMiddleware]) - .validator((d: string) => d) + .inputValidator((d: string) => d) .handler(({ data: name }) => { return { name, randomNumber: Math.floor(Math.random() * 100) } }) const slowServerFn = createServerFn({ method: 'GET' }) .middleware([staticFunctionMiddleware]) - .validator((d: string) => d) + .inputValidator((d: string) => d) .handler(async ({ data: name }) => { await new Promise((r) => setTimeout(r, 1000)) return { name, randomNumber: Math.floor(Math.random() * 100) } @@ -40,7 +40,7 @@ function Deferred() {
{loaderData().person.name} - {loaderData().person.randomNumber}
- Loading person...
}> + Loading person...
}> ( @@ -49,13 +49,13 @@ function Deferred() {
)} /> - - Loading stuff...
}> + + Loading stuff...
}>

{data}

} /> - +
Count: {count()}
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 2c667b8ceb..1b0a2e84b8 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]) - .validator((d: string) => d) + .inputValidator((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/utils/posts.tsx b/examples/solid/start-basic-static/src/utils/posts.tsx index 01a6673569..166c1787c8 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]) - .validator((d: string) => d) + .inputValidator((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/tsconfig.json b/examples/solid/start-basic-static/tsconfig.json index ff0556e7a8..a40235b863 100644 --- a/examples/solid/start-basic-static/tsconfig.json +++ b/examples/solid/start-basic-static/tsconfig.json @@ -14,6 +14,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/solid/start-basic/package.json b/examples/solid/start-basic/package.json index 758815b669..4b4fc40b1d 100644 --- a/examples/solid/start-basic/package.json +++ b/examples/solid/start-basic/package.json @@ -10,21 +10,22 @@ "start": "node .output/server/index.mjs" }, "dependencies": { - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "@tanstack/solid-start": "^1.169.6", + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", + "@tanstack/solid-start": "^2.0.0-alpha.7", "redaxios": "^0.5.1", - "solid-js": "^1.9.10", - "tailwind-merge": "^3.6.0" + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", + "tailwind-merge": "^2.6.0" }, "devDependencies": { "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.4", - "nitro": "^3.0.260903-beta", + "nitro": "^3.0.260311-beta", "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", - "vite-plugin-solid": "^2.11.11" + "typescript": "^5.7.2", + "vite": "^8.0.0", + "vite-plugin-solid": "3.0.0-next.3", + "vite-tsconfig-paths": "^5.1.4" } } diff --git a/examples/solid/start-basic/src/components/DefaultCatchBoundary.tsx b/examples/solid/start-basic/src/components/DefaultCatchBoundary.tsx index beff7bc210..1ae7a0cf94 100644 --- a/examples/solid/start-basic/src/components/DefaultCatchBoundary.tsx +++ b/examples/solid/start-basic/src/components/DefaultCatchBoundary.tsx @@ -1,15 +1,17 @@ import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, useRouter, } from '@tanstack/solid-router' import type { ErrorComponentProps } from '@tanstack/solid-router' export function DefaultCatchBoundary({ error }: ErrorComponentProps) { const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, }) 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 8d6c8ffc2b..722133b41e 100644 --- a/examples/solid/start-basic/src/routeTree.gen.ts +++ b/examples/solid/start-basic/src/routeTree.gen.ts @@ -9,40 +9,26 @@ // Additionally, you should also exclude this file 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 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 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 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 PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as ApiUsersRouteImport } from './routes/api/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 PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', - getParentRoute: () => rootRouteImport, -} as any) -const DeferredRoute = DeferredRouteImport.update({ - id: '/deferred', - path: '/deferred', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', getParentRoute: () => rootRouteImport, } as any) const RedirectRoute = RedirectRouteImport.update({ @@ -50,9 +36,48 @@ const RedirectRoute = RedirectRouteImport.update({ path: '/redirect', getParentRoute: () => rootRouteImport, } as any) -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', + getParentRoute: () => rootRouteImport, +} as any) +const DeferredRoute = DeferredRouteImport.update({ + id: '/deferred', + path: '/deferred', + 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 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', getParentRoute: () => rootRouteImport, } as any) const PathlessLayoutNestedLayoutRoute = @@ -60,53 +85,28 @@ const PathlessLayoutNestedLayoutRoute = id: '/_nested-layout', getParentRoute: () => PathlessLayoutRoute, } as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', 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({ +const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ id: '/$userId', path: '/$userId', - getParentRoute: () => UsersRoute, + getParentRoute: () => ApiUsersRoute, } 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) +const PathlessLayoutNestedLayoutRouteARoute = + PathlessLayoutNestedLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + } as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -221,32 +221,11 @@ 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 - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport parentRoute: typeof rootRouteImport } '/redirect': { @@ -256,11 +235,67 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof RedirectRouteImport parentRoute: typeof rootRouteImport } - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport + parentRoute: typeof rootRouteImport + } + '/_pathlessLayout': { + id: '/_pathlessLayout' + 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 + } + '/api/users': { + id: '/api/users' + path: '/api/users' + fullPath: '/api/users' + preLoaderRoute: typeof ApiUsersRouteImport parentRoute: typeof rootRouteImport } '/_pathlessLayout/_nested-layout': { @@ -270,55 +305,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport parentRoute: typeof PathlessLayoutRoute } - '/api/users': { - id: '/api/users' - path: '/api/users' - fullPath: '/api/users' - preLoaderRoute: typeof ApiUsersRouteImport + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport parentRoute: typeof rootRouteImport } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute - } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute - } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRoute - } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } - '/_pathlessLayout/_nested-layout/route-b': { - id: '/_pathlessLayout/_nested-layout/route-b' - path: '/route-b' - fullPath: '/route-b' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } '/api/users/$userId': { id: '/api/users/$userId' path: '/$userId' @@ -326,12 +319,19 @@ declare module '@tanstack/solid-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 + '/_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 } } } diff --git a/examples/solid/start-basic/src/routes/__root.tsx b/examples/solid/start-basic/src/routes/__root.tsx index cec570e7a4..641084c8ee 100644 --- a/examples/solid/start-basic/src/routes/__root.tsx +++ b/examples/solid/start-basic/src/routes/__root.tsx @@ -6,7 +6,7 @@ import { createRootRoute, } from '@tanstack/solid-router' import { TanStackRouterDevtools } from '@tanstack/solid-router-devtools' -import { HydrationScript } from 'solid-js/web' +import { HydrationScript } from '@solidjs/web' import type * as Solid from 'solid-js' import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary' import { NotFound } from '~/components/NotFound' diff --git a/examples/solid/start-basic/src/routes/deferred.tsx b/examples/solid/start-basic/src/routes/deferred.tsx index 1633369b20..54d334ebc6 100644 --- a/examples/solid/start-basic/src/routes/deferred.tsx +++ b/examples/solid/start-basic/src/routes/deferred.tsx @@ -1,15 +1,15 @@ import { Await, createFileRoute } from '@tanstack/solid-router' import { createServerFn } from '@tanstack/solid-start' -import { Suspense, createSignal } from 'solid-js' +import { Loading, createSignal } from 'solid-js' const personServerFn = createServerFn({ method: 'GET' }) - .validator((d: string) => d) + .inputValidator((d: string) => d) .handler(({ data: name }) => { return { name, randomNumber: Math.floor(Math.random() * 100) } }) const slowServerFn = createServerFn({ method: 'GET' }) - .validator((d: string) => d) + .inputValidator((d: string) => d) .handler(async ({ data: name }) => { await new Promise((r) => setTimeout(r, 1000)) return { name, randomNumber: Math.floor(Math.random() * 100) } @@ -37,7 +37,7 @@ function Deferred() {
{loaderData().person.name} - {loaderData().person.randomNumber}
- Loading person...
}> + Loading person...
}> ( @@ -46,13 +46,13 @@ function Deferred() {
}> + + Loading stuff...
}>

{data}

} /> - +
Count: {count()}
diff --git a/examples/solid/start-basic/src/routes/users.$userId.tsx b/examples/solid/start-basic/src/routes/users.$userId.tsx index 489abd1d3d..74279aa20e 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 '../components/NotFound' -import { UserErrorComponent } from '../components/UserError' +import { NotFound } from 'src/components/NotFound' +import { UserErrorComponent } from 'src/components/UserError' export const Route = createFileRoute('/users/$userId')({ loader: async ({ params: { userId } }) => { diff --git a/examples/solid/start-basic/src/utils/posts.tsx b/examples/solid/start-basic/src/utils/posts.tsx index 22db5ebb5f..78c7f7d44a 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' }) - .validator((d: string) => d) + .inputValidator((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 ff0556e7a8..a40235b863 100644 --- a/examples/solid/start-basic/tsconfig.json +++ b/examples/solid/start-basic/tsconfig.json @@ -14,6 +14,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/solid/start-bun/package.json b/examples/solid/start-bun/package.json index d1ad9a9563..01eb85ecf8 100644 --- a/examples/solid/start-bun/package.json +++ b/examples/solid/start-bun/package.json @@ -5,7 +5,7 @@ "scripts": { "dev": "vite dev --port 3000", "start": "bun run server.ts", - "build": "vite build", + "build": "echo 'Skipped: waiting for dependency Solid 2.0 support' && exit 0", "preview": "vite preview", "test": "vitest run", "lint": "eslint", @@ -15,13 +15,15 @@ "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/solid-devtools": "^0.7.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.2.2" + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", + "@tanstack/solid-router-ssr-query": "^2.0.0-alpha.6", + "@tanstack/solid-start": "^2.0.0-alpha.7", + "@tanstack/router-plugin": "^1.166.14", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", + "tailwindcss": "^4.2.2", + "vite-tsconfig-paths": "^5.1.4" }, "devDependencies": { "@tanstack/eslint-config": "^0.3.2", @@ -29,13 +31,12 @@ "@solidjs/testing-library": "^0.8.10", "@types/bun": "^1.2.22", "@types/node": "22.10.2", - "vite-plugin-solid": "^2.11.11", + "vite-plugin-solid": "3.0.0-next.3", "jsdom": "^27.0.0", "prettier": "^3.6.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", - "vitest": "^5.0.4", + "typescript": "^5.9.2", + "vite": "^8.0.0", + "vitest": "^3.2.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 353db2cd02..19009b2f5b 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 DemoStartApiRequestRouteImport } from './routes/demo.start.api-request' import { Route as DemoStartServerFuncsRouteImport } from './routes/demo.start.server-funcs' +import { Route as DemoStartApiRequestRouteImport } from './routes/demo.start.api-request' const IndexRoute = IndexRouteImport.update({ id: '/', @@ -24,16 +24,16 @@ const ApiDemoNamesRoute = ApiDemoNamesRouteImport.update({ path: '/api/demo-names', 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) +const DemoStartApiRequestRoute = DemoStartApiRequestRouteImport.update({ + id: '/demo/start/api-request', + path: '/demo/start/api-request', + 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/api-request': { - id: '/demo/start/api-request' - path: '/demo/start/api-request' - fullPath: '/demo/start/api-request' - preLoaderRoute: typeof DemoStartApiRequestRouteImport - parentRoute: typeof rootRouteImport - } '/demo/start/server-funcs': { id: '/demo/start/server-funcs' path: '/demo/start/server-funcs' @@ -112,6 +105,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof DemoStartServerFuncsRouteImport parentRoute: typeof rootRouteImport } + '/demo/start/api-request': { + id: '/demo/start/api-request' + path: '/demo/start/api-request' + fullPath: '/demo/start/api-request' + preLoaderRoute: typeof DemoStartApiRequestRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/solid/start-bun/src/routes/__root.tsx b/examples/solid/start-bun/src/routes/__root.tsx index 99c515ded4..7c5ce8bd6c 100644 --- a/examples/solid/start-bun/src/routes/__root.tsx +++ b/examples/solid/start-bun/src/routes/__root.tsx @@ -2,7 +2,7 @@ import { TanStackDevtools } from '@tanstack/solid-devtools' import { HeadContent, Scripts, createRootRoute } from '@tanstack/solid-router' import { TanStackRouterDevtoolsPanel } from '@tanstack/solid-router-devtools' -import { HydrationScript } from 'solid-js/web' +import { HydrationScript } from '@solidjs/web' import Header from '../components/Header' import appCss from '../styles.css?url' 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 eb9e575747..65bc7aa96f 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' }) - .validator((d: string) => d) + .inputValidator((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/vite-env.d.ts b/examples/solid/start-bun/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/solid/start-bun/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/solid/start-bun/tsconfig.json b/examples/solid/start-bun/tsconfig.json index 7d5e1c1aaf..70c9888dea 100644 --- a/examples/solid/start-bun/tsconfig.json +++ b/examples/solid/start-bun/tsconfig.json @@ -28,6 +28,7 @@ "noUnusedParameters": true, "noFallthroughCasesInSwitch": true, "noUncheckedSideEffectImports": true, + "baseUrl": ".", "paths": { "@/*": ["./src/*"] } diff --git a/examples/solid/start-convex-better-auth/convex/auth.ts b/examples/solid/start-convex-better-auth/convex/auth.ts index 7509818aac..e9c2cdb499 100644 --- a/examples/solid/start-convex-better-auth/convex/auth.ts +++ b/examples/solid/start-convex-better-auth/convex/auth.ts @@ -4,7 +4,6 @@ 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! @@ -17,7 +16,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 ea13a1c1e3..e946aa519f 100644 --- a/examples/solid/start-convex-better-auth/package.json +++ b/examples/solid/start-convex-better-auth/package.json @@ -6,32 +6,33 @@ "scripts": { "dev": "vite dev", "convex:dev": "convex dev", - "build": "vite build && tsc --noEmit", + "build": "echo 'Skipped: waiting for dependency Solid 2.0 support' && exit 0", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { "@convex-dev/better-auth": "^0.9.7", "@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", + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", + "@tanstack/solid-start": "^2.0.0-alpha.7", + "better-auth": "^1.3.27", "clsx": "^2.1.1", "convex": "^1.28.2", "convex-solidjs": "^0.0.3", "redaxios": "^0.5.1", - "solid-js": "^1.9.10", - "tailwind-merge": "^3.6.0", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", + "tailwind-merge": "^2.6.0", "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { "@types/node": "^22.10.2", "combinate": "^1.1.11", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", - "vite-plugin-solid": "^2.11.11" + "typescript": "^5.7.2", + "vite": "^8.0.0", + "vite-plugin-solid": "3.0.0-next.3", + "vite-tsconfig-paths": "^5.1.4" } } 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 90dfd5ee28..4f60bbdbfd 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) { - throw new Error('missing envar CONVEX_URL') + console.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 d2307d1277..27dc0ca88c 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 IndexRouteImport } from './routes/index' -import { Route as AuthedRouteImport } from './routes/_authed' import { Route as AboutRouteImport } from './routes/about' +import { Route as AuthedRouteImport } from './routes/_authed' +import { Route as IndexRouteImport } from './routes/index' import { Route as AuthedDashboardRouteImport } from './routes/_authed/dashboard' import { Route as ApiAuthSplatRouteImport } from './routes/api/auth/$' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', getParentRoute: () => rootRouteImport, } as any) const AuthedRoute = AuthedRouteImport.update({ id: '/_authed', getParentRoute: () => rootRouteImport, } as any) -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AuthedDashboardRoute = AuthedDashboardRouteImport.update({ @@ -83,11 +83,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport parentRoute: typeof rootRouteImport } '/_authed': { @@ -97,11 +97,11 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof AuthedRouteImport parentRoute: typeof rootRouteImport } - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_authed/dashboard': { diff --git a/examples/solid/start-convex-better-auth/src/routes/__root.tsx b/examples/solid/start-convex-better-auth/src/routes/__root.tsx index 34e24068d3..ef1258ed4c 100644 --- a/examples/solid/start-convex-better-auth/src/routes/__root.tsx +++ b/examples/solid/start-convex-better-auth/src/routes/__root.tsx @@ -1,6 +1,6 @@ /// import { HeadContent, Scripts, createRootRoute } from '@tanstack/solid-router' -import { HydrationScript, Suspense } from 'solid-js/web' +import { HydrationScript, Suspense } from '@solidjs/web' import { TanStackRouterDevtools } from '@tanstack/solid-router-devtools' import type * as Solid from 'solid-js' import appCss from '~/styles/app.css?url' diff --git a/examples/solid/start-convex-better-auth/tsconfig.json b/examples/solid/start-convex-better-auth/tsconfig.json index 4b77b70bcf..57ea27b286 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/*"], - "convex/*": ["./convex/*"] + "~/*": ["./src/*"] }, "noEmit": true } diff --git a/examples/solid/start-counter/package.json b/examples/solid/start-counter/package.json index 8b49c516bd..b732963c55 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.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "@tanstack/solid-start": "^1.169.6", + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", + "@tanstack/solid-start": "^2.0.0-alpha.7", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", "redaxios": "^0.5.1", - "solid-js": "^1.9.10", - "tailwind-merge": "^3.6.0", - "zod": "^4.4.3" + "tailwind-merge": "^2.6.0", + "zod": "^3.24.2" }, "devDependencies": { "@types/node": "^22.10.2", + "vite-plugin-solid": "3.0.0-next.3", "combinate": "^1.1.11", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", - "vite-plugin-solid": "^2.11.11" + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/solid/start-counter/src/routeTree.gen.ts b/examples/solid/start-counter/src/routeTree.gen.ts index 7495244535..3cc45c071e 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 IndexRouteImport } from './routes/index' import { Route as AboutRouteImport } from './routes/about' +import { Route as IndexRouteImport } from './routes/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const AboutRoute = AboutRouteImport.update({ id: '/about', path: '/about', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/about': { id: '/about' path: '/about' @@ -65,6 +58,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof AboutRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/solid/start-counter/src/routes/__root.tsx b/examples/solid/start-counter/src/routes/__root.tsx index 7b340ba2ce..0fa315d04f 100644 --- a/examples/solid/start-counter/src/routes/__root.tsx +++ b/examples/solid/start-counter/src/routes/__root.tsx @@ -5,7 +5,7 @@ import { Scripts, createRootRoute, } from '@tanstack/solid-router' -import { HydrationScript } from 'solid-js/web' +import { HydrationScript } from '@solidjs/web' import { TanStackRouterDevtools } from '@tanstack/solid-router-devtools' import type * as Solid from 'solid-js' import appCss from '~/styles/app.css?url' diff --git a/examples/solid/start-counter/tsconfig.json b/examples/solid/start-counter/tsconfig.json index 508ace2e17..57ea27b286 100644 --- a/examples/solid/start-counter/tsconfig.json +++ b/examples/solid/start-counter/tsconfig.json @@ -14,6 +14,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/solid/start-i18n-paraglide/package.json b/examples/solid/start-i18n-paraglide/package.json index 076c9b41dc..475b4f3593 100644 --- a/examples/solid/start-i18n-paraglide/package.json +++ b/examples/solid/start-i18n-paraglide/package.json @@ -5,35 +5,22 @@ "scripts": { "dev": "vite dev --port 3000", "start": "node .output/server/index.mjs", - "build": "vite build", + "build": "echo 'Skipped: waiting for dependency Solid 2.0 support' && exit 0", "preview": "vite preview" }, "dependencies": { "@tanstack/solid-devtools": "^0.7.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": { + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", + "@tanstack/solid-start": "^2.0.0-alpha.7", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", "@types/node": "^22.18.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", + "vite-plugin-solid": "3.0.0-next.3", + "typescript": "^5.9.2", + "vite": "^8.0.0", "@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 7495244535..3cc45c071e 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 IndexRouteImport } from './routes/index' import { Route as AboutRouteImport } from './routes/about' +import { Route as IndexRouteImport } from './routes/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const AboutRoute = AboutRouteImport.update({ id: '/about', path: '/about', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/about': { id: '/about' path: '/about' @@ -65,6 +58,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof AboutRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/solid/start-i18n-paraglide/src/routes/__root.tsx b/examples/solid/start-i18n-paraglide/src/routes/__root.tsx index 39875ee9fe..6b281a271e 100644 --- a/examples/solid/start-i18n-paraglide/src/routes/__root.tsx +++ b/examples/solid/start-i18n-paraglide/src/routes/__root.tsx @@ -6,7 +6,7 @@ import { } from '@tanstack/solid-router' import { TanStackRouterDevtoolsPanel } from '@tanstack/solid-router-devtools' import { TanStackDevtools } from '@tanstack/solid-devtools' -import { HydrationScript } from 'solid-js/web' +import { HydrationScript } from '@solidjs/web' import styles from '../styles.css?url' import type { JSX } from 'solid-js/jsx-runtime' import { getLocale, locales, setLocale } from '@/paraglide/runtime' diff --git a/examples/solid/start-i18n-paraglide/src/routes/index.tsx b/examples/solid/start-i18n-paraglide/src/routes/index.tsx index e08d2ed0f8..48f092c754 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() - .validator((emoji: string) => emoji) + .inputValidator((emoji: string) => emoji) .handler((ctx) => { return m.server_message({ emoji: ctx.data }) }) diff --git a/examples/solid/start-i18n-paraglide/src/vite-env.d.ts b/examples/solid/start-i18n-paraglide/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/solid/start-i18n-paraglide/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/solid/start-i18n-paraglide/tsconfig.json b/examples/solid/start-i18n-paraglide/tsconfig.json index 8d23f745d0..522b26852d 100644 --- a/examples/solid/start-i18n-paraglide/tsconfig.json +++ b/examples/solid/start-i18n-paraglide/tsconfig.json @@ -22,6 +22,7 @@ "noUnusedParameters": true, "noFallthroughCasesInSwitch": true, "noUncheckedSideEffectImports": true, + "baseUrl": ".", "paths": { "@/*": ["./src/*"] } diff --git a/examples/solid/start-large/package.json b/examples/solid/start-large/package.json index 83f3589cc2..b6c00c9b74 100644 --- a/examples/solid/start-large/package.json +++ b/examples/solid/start-large/package.json @@ -5,30 +5,30 @@ "type": "module", "scripts": { "dev": "vite dev", - "build": "vite build && tsc --noEmit", + "build": "vite build", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", "gen": "node ./src/createRoutes.mjs", "test:types": "tsc --extendedDiagnostics" }, "dependencies": { - "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "@tanstack/solid-start": "^1.169.6", + "@tanstack/solid-query": "6.0.0-alpha.1", + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", + "@tanstack/solid-start": "^2.0.0-alpha.7", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", "redaxios": "^0.5.1", - "solid-js": "^1.9.10", - "tailwind-merge": "^3.6.0", + "tailwind-merge": "^2.6.0", "valibot": "^1.0.0-beta.15" }, "devDependencies": { "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.4", + "vite-plugin-solid": "3.0.0-next.3", "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" + "typescript": "^5.7.2", + "vite": "^8.0.0" }, "keywords": [], "author": "", diff --git a/examples/solid/start-large/src/routeTree.gen.ts b/examples/solid/start-large/src/routeTree.gen.ts index 1febe90621..3fb99e1aca 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 IndexRouteImport } from './routes/index' -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 LinkPropsRouteImport } from './routes/linkProps' +import { Route as AbsoluteRouteImport } from './routes/absolute' import { Route as SearchRouteRouteImport } from './routes/search/route' -import { Route as ParamsParamsPlaceholderRouteImport } from './routes/params/$paramsPlaceholder' +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 ParamsParamsPlaceholderRouteImport } from './routes/params/$paramsPlaceholder' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const AbsoluteRoute = AbsoluteRouteImport.update({ - id: '/absolute', - path: '/absolute', +const RelativeRoute = RelativeRouteImport.update({ + id: '/relative', + path: '/relative', getParentRoute: () => rootRouteImport, } as any) const LinkPropsRoute = LinkPropsRouteImport.update({ @@ -33,14 +28,9 @@ const LinkPropsRoute = LinkPropsRouteImport.update({ path: '/linkProps', getParentRoute: () => rootRouteImport, } as any) -const ParamsRouteRoute = ParamsRouteRouteImport.update({ - id: '/params', - path: '/params', - getParentRoute: () => rootRouteImport, -} as any) -const RelativeRoute = RelativeRouteImport.update({ - id: '/relative', - path: '/relative', +const AbsoluteRoute = AbsoluteRouteImport.update({ + id: '/absolute', + path: '/absolute', getParentRoute: () => rootRouteImport, } as any) const SearchRouteRoute = SearchRouteRouteImport.update({ @@ -48,16 +38,26 @@ const SearchRouteRoute = SearchRouteRouteImport.update({ path: '/search', getParentRoute: () => rootRouteImport, } as any) -const ParamsParamsPlaceholderRoute = ParamsParamsPlaceholderRouteImport.update({ - id: '/$paramsPlaceholder', - path: '/$paramsPlaceholder', - getParentRoute: () => ParamsRouteRoute, +const ParamsRouteRoute = ParamsRouteRouteImport.update({ + id: '/params', + path: '/params', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, } as any) const SearchSearchPlaceholderRoute = SearchSearchPlaceholderRouteImport.update({ id: '/searchPlaceholder', path: '/searchPlaceholder', getParentRoute: () => SearchRouteRoute, } as any) +const ParamsParamsPlaceholderRoute = ParamsParamsPlaceholderRouteImport.update({ + id: '/$paramsPlaceholder', + path: '/$paramsPlaceholder', + getParentRoute: () => ParamsRouteRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -134,18 +134,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/absolute': { - id: '/absolute' - path: '/absolute' - fullPath: '/absolute' - preLoaderRoute: typeof AbsoluteRouteImport + '/relative': { + id: '/relative' + path: '/relative' + fullPath: '/relative' + preLoaderRoute: typeof RelativeRouteImport parentRoute: typeof rootRouteImport } '/linkProps': { @@ -155,18 +148,11 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof LinkPropsRouteImport parentRoute: typeof rootRouteImport } - '/params': { - id: '/params' - path: '/params' - fullPath: '/params' - preLoaderRoute: typeof ParamsRouteRouteImport - parentRoute: typeof rootRouteImport - } - '/relative': { - id: '/relative' - path: '/relative' - fullPath: '/relative' - preLoaderRoute: typeof RelativeRouteImport + '/absolute': { + id: '/absolute' + path: '/absolute' + fullPath: '/absolute' + preLoaderRoute: typeof AbsoluteRouteImport parentRoute: typeof rootRouteImport } '/search': { @@ -176,12 +162,19 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof SearchRouteRouteImport parentRoute: typeof rootRouteImport } - '/params/$paramsPlaceholder': { - id: '/params/$paramsPlaceholder' - path: '/$paramsPlaceholder' - fullPath: '/params/$paramsPlaceholder' - preLoaderRoute: typeof ParamsParamsPlaceholderRouteImport - parentRoute: typeof ParamsRouteRoute + '/params': { + id: '/params' + path: '/params' + fullPath: '/params' + preLoaderRoute: typeof ParamsRouteRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport } '/search/searchPlaceholder': { id: '/search/searchPlaceholder' @@ -190,6 +183,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof SearchSearchPlaceholderRouteImport parentRoute: typeof SearchRouteRoute } + '/params/$paramsPlaceholder': { + id: '/params/$paramsPlaceholder' + path: '/$paramsPlaceholder' + fullPath: '/params/$paramsPlaceholder' + preLoaderRoute: typeof ParamsParamsPlaceholderRouteImport + parentRoute: typeof ParamsRouteRoute + } } } diff --git a/examples/solid/start-large/src/routes/params/$paramsPlaceholder.tsx b/examples/solid/start-large/src/routes/params/$paramsPlaceholder.tsx index 5c4638851f..d7a62860e5 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' }) - .validator(params) + .inputValidator(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 d61e34357e..0fa857d29c 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' }) - .validator(search) + .inputValidator(search) .client(({ next }) => { const context = { client: { searchPlaceholder: 'searchPlaceholder' } } return next({ diff --git a/examples/solid/start-large/src/typePrimitives.tsx b/examples/solid/start-large/src/typePrimitives.tsx index 2a127d522e..93fdc62f4d 100644 --- a/examples/solid/start-large/src/typePrimitives.tsx +++ b/examples/solid/start-large/src/typePrimitives.tsx @@ -1,5 +1,5 @@ import { Link, redirect, useNavigate } from '@tanstack/solid-router' -import { onMount } from 'solid-js' +import { onSettled } from 'solid-js' import type { RegisteredRouter, ValidateFromPath, @@ -23,7 +23,7 @@ export function useCustomNavigate( export function useCustomNavigate(options: ValidateNavigateOptions): void { const navigate = useNavigate() - onMount(() => { + onSettled(() => { navigate(options) }) } diff --git a/examples/solid/start-large/tsconfig.json b/examples/solid/start-large/tsconfig.json index ff0556e7a8..a40235b863 100644 --- a/examples/solid/start-large/tsconfig.json +++ b/examples/solid/start-large/tsconfig.json @@ -14,6 +14,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, 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 83e0719b39..7690aceae4 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.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "@tanstack/solid-start": "^1.169.6", - "solid-js": "^1.9.10", - "zod": "^4.4.3" + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", + "@tanstack/solid-start": "^2.0.0-alpha.7", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", + "zod": "^3.24.2" }, "devDependencies": { "@types/node": "^22.5.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" + "vite-plugin-solid": "3.0.0-next.3", + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/solid/start-streaming-data-from-server-functions/src/routes/__root.tsx b/examples/solid/start-streaming-data-from-server-functions/src/routes/__root.tsx index 389b99c143..34d006e50c 100644 --- a/examples/solid/start-streaming-data-from-server-functions/src/routes/__root.tsx +++ b/examples/solid/start-streaming-data-from-server-functions/src/routes/__root.tsx @@ -6,7 +6,7 @@ import { Scripts, createRootRoute, } from '@tanstack/solid-router' -import { HydrationScript } from 'solid-js/web' +import { HydrationScript } from '@solidjs/web' import type { JSX } from 'solid-js' import appCss from '~/styles/app.css?url' 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 508ace2e17..57ea27b286 100644 --- a/examples/solid/start-streaming-data-from-server-functions/tsconfig.json +++ b/examples/solid/start-streaming-data-from-server-functions/tsconfig.json @@ -14,6 +14,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/solid/start-supabase-basic/package.json b/examples/solid/start-supabase-basic/package.json index 81ab5cd63c..3838c67977 100644 --- a/examples/solid/start-supabase-basic/package.json +++ b/examples/solid/start-supabase-basic/package.json @@ -12,21 +12,22 @@ "author": "", "license": "ISC", "dependencies": { + "@solidjs/web": "2.0.0-beta.4", "@supabase/ssr": "^0.5.2", "@supabase/supabase-js": "^2.48.1", - "@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" + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", + "@tanstack/solid-start": "^2.0.0-alpha.7", + "redaxios": "^0.5.1", + "solid-js": "2.0.0-beta.4" }, "devDependencies": { "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.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" + "typescript": "^5.7.2", + "vite": "^8.0.0", + "vite-plugin-solid": "3.0.0-next.3", + "vite-tsconfig-paths": "^5.1.4" } } diff --git a/examples/solid/start-supabase-basic/src/components/DefaultCatchBoundary.tsx b/examples/solid/start-supabase-basic/src/components/DefaultCatchBoundary.tsx index 6de1f0b377..32aed20e67 100644 --- a/examples/solid/start-supabase-basic/src/components/DefaultCatchBoundary.tsx +++ b/examples/solid/start-supabase-basic/src/components/DefaultCatchBoundary.tsx @@ -1,15 +1,17 @@ import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, useRouter, } from '@tanstack/solid-router' import type { ErrorComponentProps } from '@tanstack/solid-router' export function DefaultCatchBoundary({ error }: ErrorComponentProps) { const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, }) 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 bbebb19df3..7019a6c21a 100644 --- a/examples/solid/start-supabase-basic/src/routeTree.gen.ts +++ b/examples/solid/start-supabase-basic/src/routeTree.gen.ts @@ -9,27 +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 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 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 AuthedPostsRouteImport } from './routes/_authed/posts' import { Route as AuthedPostsIndexRouteImport } from './routes/_authed/posts.index' import { Route as AuthedPostsPostIdRouteImport } from './routes/_authed/posts.$postId' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const AuthedRoute = AuthedRouteImport.update({ - id: '/_authed', - getParentRoute: () => rootRouteImport, -} as any) -const LoginRoute = LoginRouteImport.update({ - id: '/login', - path: '/login', +const SignupRoute = SignupRouteImport.update({ + id: '/signup', + path: '/signup', getParentRoute: () => rootRouteImport, } as any) const LogoutRoute = LogoutRouteImport.update({ @@ -37,9 +28,18 @@ const LogoutRoute = LogoutRouteImport.update({ path: '/logout', getParentRoute: () => rootRouteImport, } as any) -const SignupRoute = SignupRouteImport.update({ - id: '/signup', - path: '/signup', +const LoginRoute = LoginRouteImport.update({ + id: '/login', + path: '/login', + getParentRoute: () => rootRouteImport, +} as any) +const AuthedRoute = AuthedRouteImport.update({ + id: '/_authed', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AuthedPostsRoute = AuthedPostsRouteImport.update({ @@ -120,25 +120,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_authed': { - id: '/_authed' - path: '' - fullPath: '/' - preLoaderRoute: typeof AuthedRouteImport - parentRoute: typeof rootRouteImport - } - '/login': { - id: '/login' - path: '/login' - fullPath: '/login' - preLoaderRoute: typeof LoginRouteImport + '/signup': { + id: '/signup' + path: '/signup' + fullPath: '/signup' + preLoaderRoute: typeof SignupRouteImport parentRoute: typeof rootRouteImport } '/logout': { @@ -148,11 +134,25 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof LogoutRouteImport parentRoute: typeof rootRouteImport } - '/signup': { - id: '/signup' - path: '/signup' - fullPath: '/signup' - preLoaderRoute: typeof SignupRouteImport + '/login': { + id: '/login' + path: '/login' + fullPath: '/login' + preLoaderRoute: typeof LoginRouteImport + parentRoute: typeof rootRouteImport + } + '/_authed': { + id: '/_authed' + path: '' + fullPath: '/' + preLoaderRoute: typeof AuthedRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_authed/posts': { diff --git a/examples/solid/start-supabase-basic/src/routes/__root.tsx b/examples/solid/start-supabase-basic/src/routes/__root.tsx index 1eb986feee..d1b8daf085 100644 --- a/examples/solid/start-supabase-basic/src/routes/__root.tsx +++ b/examples/solid/start-supabase-basic/src/routes/__root.tsx @@ -8,7 +8,7 @@ import { } from '@tanstack/solid-router' import { TanStackRouterDevtools } from '@tanstack/solid-router-devtools' import { createServerFn } from '@tanstack/solid-start' -import { HydrationScript } from 'solid-js/web' +import { HydrationScript } from '@solidjs/web' import { DefaultCatchBoundary } from '../components/DefaultCatchBoundary' import { NotFound } from '../components/NotFound' import appCss from '../styles/app.css?url' diff --git a/examples/solid/start-supabase-basic/src/routes/_authed.tsx b/examples/solid/start-supabase-basic/src/routes/_authed.tsx index 72e7052f56..72e354a3fe 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' }) - .validator((d: { email: string; password: string }) => d) + .inputValidator((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 ab499b5ec0..129a638c94 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' }) - .validator( + .inputValidator( (d: { email: string; password: string; redirectUrl?: string }) => d, ) .handler(async ({ data }) => { diff --git a/examples/solid/start-supabase-basic/src/utils/posts.ts b/examples/solid/start-supabase-basic/src/utils/posts.ts index f7cc78fec3..290917db65 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' }) - .validator((d: string) => d) + .inputValidator((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 ff0556e7a8..a40235b863 100644 --- a/examples/solid/start-supabase-basic/tsconfig.json +++ b/examples/solid/start-supabase-basic/tsconfig.json @@ -14,6 +14,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/solid/start-tailwind-v4/package.json b/examples/solid/start-tailwind-v4/package.json index 94db6ac790..5898df3f72 100644 --- a/examples/solid/start-tailwind-v4/package.json +++ b/examples/solid/start-tailwind-v4/package.json @@ -10,20 +10,21 @@ "start": "node .output/server/index.mjs" }, "dependencies": { - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "@tanstack/solid-start": "^1.169.6", - "solid-js": "^1.9.10", - "tailwind-merge": "^3.6.0", - "zod": "^4.4.3" + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", + "@tanstack/solid-start": "^2.0.0-alpha.7", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", + "tailwind-merge": "^2.6.0", + "zod": "^3.24.2" }, "devDependencies": { "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.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" + "typescript": "^5.7.2", + "vite": "^8.0.0", + "vite-plugin-solid": "3.0.0-next.3", + "vite-tsconfig-paths": "^5.1.4" } } diff --git a/examples/solid/start-tailwind-v4/src/routes/__root.tsx b/examples/solid/start-tailwind-v4/src/routes/__root.tsx index 489680b739..f83fcd6206 100644 --- a/examples/solid/start-tailwind-v4/src/routes/__root.tsx +++ b/examples/solid/start-tailwind-v4/src/routes/__root.tsx @@ -7,7 +7,8 @@ import { createRootRoute, } from '@tanstack/solid-router' import { TanStackRouterDevtools } from '@tanstack/solid-router-devtools' -import { HydrationScript } from 'solid-js/web' +import * as React from 'react' +import { HydrationScript } from '@solidjs/web' import type { JSX } from 'solid-js' import appCss from '~/styles/app.css?url' diff --git a/examples/solid/start-tailwind-v4/tsconfig.json b/examples/solid/start-tailwind-v4/tsconfig.json index ff0556e7a8..a40235b863 100644 --- a/examples/solid/start-tailwind-v4/tsconfig.json +++ b/examples/solid/start-tailwind-v4/tsconfig.json @@ -14,6 +14,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/solid/view-transitions/package.json b/examples/solid/view-transitions/package.json index 2acb2432bf..4aa3d9e7d5 100644 --- a/examples/solid/view-transitions/package.json +++ b/examples/solid/view-transitions/package.json @@ -10,18 +10,18 @@ }, "dependencies": { "@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/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", + "@tanstack/router-plugin": "^1.166.14", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", "redaxios": "^0.5.1", - "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", - "vite-plugin-solid": "^2.11.11" + "vite-plugin-solid": "3.0.0-next.3", + "typescript": "^5.7.2", + "vite": "^8.0.0" } } diff --git a/examples/solid/view-transitions/src/main.tsx b/examples/solid/view-transitions/src/main.tsx index 740315c011..9abe826c95 100644 --- a/examples/solid/view-transitions/src/main.tsx +++ b/examples/solid/view-transitions/src/main.tsx @@ -1,4 +1,4 @@ -import { render } from 'solid-js/web' +import { render } from '@solidjs/web' import { RouterProvider, createRouter } from '@tanstack/solid-router' import { routeTree } from './routeTree.gen' import './styles.css' diff --git a/examples/solid/view-transitions/src/routeTree.gen.ts b/examples/solid/view-transitions/src/routeTree.gen.ts index 01843027dc..114e34ed9d 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 IndexRouteImport } from './routes/index' -import { Route as ExploreRouteImport } from './routes/explore' 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 PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const HowItWorksRoute = HowItWorksRouteImport.update({ + id: '/how-it-works', + path: '/how-it-works', 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 { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/how-it-works': { + id: '/how-it-works' + path: '/how-it-works' + fullPath: '/how-it-works' + preLoaderRoute: typeof HowItWorksRouteImport parentRoute: typeof rootRouteImport } '/explore': { @@ -115,13 +115,6 @@ 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' @@ -129,6 +122,13 @@ 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/vite-env.d.ts b/examples/solid/view-transitions/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/solid/view-transitions/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/solid/with-framer-motion/package.json b/examples/solid/with-framer-motion/package.json index 449d8a3927..033399785d 100644 --- a/examples/solid/with-framer-motion/package.json +++ b/examples/solid/with-framer-motion/package.json @@ -4,24 +4,24 @@ "type": "module", "scripts": { "dev": "vite --port 3000", - "build": "vite build && tsc --noEmit", + "build": "echo 'Skipped: waiting for dependency Solid 2.0 support' && exit 0", "preview": "vite preview", "start": "vite" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", "redaxios": "^0.5.1", - "solid-js": "^1.9.10", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", "solid-motionone": "^1.0.4", "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", - "vite-plugin-solid": "^2.11.11" + "typescript": "^5.7.2", + "vite": "^8.0.0", + "vite-plugin-solid": "3.0.0-next.3" } } diff --git a/examples/solid/with-framer-motion/src/main.tsx b/examples/solid/with-framer-motion/src/main.tsx index 3015606710..e2f8302305 100644 --- a/examples/solid/with-framer-motion/src/main.tsx +++ b/examples/solid/with-framer-motion/src/main.tsx @@ -1,4 +1,4 @@ -import { render } from 'solid-js/web' +import { render } from '@solidjs/web' import { Motion, Presence } from 'solid-motionone' import { ErrorComponent, diff --git a/examples/solid/with-framer-motion/src/vite-env.d.ts b/examples/solid/with-framer-motion/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/solid/with-framer-motion/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/solid/with-trpc/package.json b/examples/solid/with-trpc/package.json index 46d33436db..e35353ed8e 100644 --- a/examples/solid/with-trpc/package.json +++ b/examples/solid/with-trpc/package.json @@ -11,21 +11,22 @@ }, "dependencies": { "@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/solid-router": "^2.0.0-alpha.6", + "@tanstack/solid-router-devtools": "^2.0.0-alpha.4", + "@tanstack/router-plugin": "^1.166.14", "@trpc/client": "^11.4.3", "@trpc/server": "^11.4.3", - "express": "^5.2.1", + "express": "^4.21.2", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", "redaxios": "^0.5.1", - "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "@types/express": "^5.0.6", + "@types/express": "^4.17.23", + "vite-plugin-solid": "3.0.0-next.3", "tsx": "^4.20.3", - "vite": "^8.0.14", - "vite-plugin-solid": "^2.11.11" + "vite": "^8.0.0" } } diff --git a/examples/solid/with-trpc/src/main.tsx b/examples/solid/with-trpc/src/main.tsx index d99d3054d7..04e801986c 100644 --- a/examples/solid/with-trpc/src/main.tsx +++ b/examples/solid/with-trpc/src/main.tsx @@ -1,4 +1,4 @@ -import { render } from 'solid-js/web' +import { render } from '@solidjs/web' import { RouterProvider, createRouter } from '@tanstack/solid-router' import { trpc } from './trpc' diff --git a/examples/solid/with-trpc/src/routeTree.gen.ts b/examples/solid/with-trpc/src/routeTree.gen.ts index aa08570aca..fd93507694 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 IndexRouteImport } from './routes/index' import { Route as DashboardRouteImport } from './routes/dashboard' +import { Route as IndexRouteImport } from './routes/index' 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 IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const DashboardRoute = DashboardRouteImport.update({ id: '/dashboard', path: '/dashboard', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const DashboardIndexRoute = DashboardIndexRouteImport.update({ id: '/', path: '/', @@ -98,13 +98,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/dashboard': { id: '/dashboard' path: '/dashboard' @@ -112,6 +105,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof DashboardRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } '/dashboard/': { id: '/dashboard/' path: '/' diff --git a/examples/solid/with-trpc/src/routes/dashboard.posts.$postId.tsx b/examples/solid/with-trpc/src/routes/dashboard.posts.$postId.tsx index cc967b0b76..f6055d70d3 100644 --- a/examples/solid/with-trpc/src/routes/dashboard.posts.$postId.tsx +++ b/examples/solid/with-trpc/src/routes/dashboard.posts.$postId.tsx @@ -22,15 +22,13 @@ function DashboardPostsPostIdComponent() { const [notes, setNotes] = Solid.createSignal(search().notes ?? ``) - Solid.createEffect( - Solid.on(notes, () => { - navigate({ - search: (old) => ({ ...old, notes: notes() ? notes() : undefined }), - replace: true, - params: true, - }) - }), - ) + Solid.createEffect(notes, () => { + navigate({ + search: (old) => ({ ...old, notes: notes() ? notes() : undefined }), + replace: true, + params: true, + }) + }) if (!post()) { return
Post not found
diff --git a/examples/solid/with-trpc/src/routes/dashboard.posts.tsx b/examples/solid/with-trpc/src/routes/dashboard.posts.tsx index 3ca324afc1..70cf17f3e7 100644 --- a/examples/solid/with-trpc/src/routes/dashboard.posts.tsx +++ b/examples/solid/with-trpc/src/routes/dashboard.posts.tsx @@ -26,18 +26,18 @@ function DashboardPostsComponent() {
-                    #{post.id} - {post.title.slice(0, 10)}{' '}
+                    #{post().id} - {post().title.slice(0, 10)}{' '}
                     
diff --git a/examples/solid/with-trpc/src/server/server.ts b/examples/solid/with-trpc/src/server/server.ts
index 0a580d4963..b2b3fd2485 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('/{*splat}', async (req, res, next) => {
+    app.get('*', 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('/{*splat}', (req, res) => {
+    app.get('*', (req, res) => {
       res.sendFile(path.resolve(__dirname, '../client', 'index.html'))
     })
   }
@@ -78,8 +78,7 @@ export const createServer = async (
 
 if (!isTest) {
   createServer().then(({ app }) =>
-    app.listen(PORT, (error) => {
-      if (error) throw error
+    app.listen(PORT, () => {
       console.info(`Server available at: http://localhost:${PORT}`)
     }),
   )
diff --git a/examples/solid/with-trpc/src/vite-env.d.ts b/examples/solid/with-trpc/src/vite-env.d.ts
deleted file mode 100644
index 11f02fe2a0..0000000000
--- a/examples/solid/with-trpc/src/vite-env.d.ts
+++ /dev/null
@@ -1 +0,0 @@
-/// 
diff --git a/examples/vue/basic-file-based-jsx/package.json b/examples/vue/basic-file-based-jsx/package.json
index 9cc36a6991..362039a82c 100644
--- a/examples/vue/basic-file-based-jsx/package.json
+++ b/examples/vue/basic-file-based-jsx/package.json
@@ -10,13 +10,14 @@
   },
   "dependencies": {
     "@tailwindcss/vite": "^4.2.2",
-    "@tanstack/router-plugin": "^1.169.0",
-    "@tanstack/vue-router": "^1.170.42",
-    "@tanstack/vue-router-devtools": "^1.167.3",
+    "@tanstack/router-plugin": "^1.167.2",
+    "@tanstack/vue-router": "^1.168.1",
+    "@tanstack/vue-router-devtools": "^1.166.10",
+    "@tanstack/zod-adapter": "^1.166.9",
     "redaxios": "^0.5.1",
     "tailwindcss": "^4.2.2",
     "vue": "^3.5.16",
-    "zod": "^4.4.3"
+    "zod": "^3.24.2"
   },
   "devDependencies": {
     "@eslint/js": "^9.36.0",
@@ -26,8 +27,8 @@
     "@vitejs/plugin-vue-jsx": "^5.1.5",
     "eslint-plugin-vue": "^9.33.0",
     "typescript": "~5.8.3",
-    "vite": "^8.0.14",
+    "vite": "^8.0.0",
     "vue-eslint-parser": "^9.4.3",
-    "vue-tsc": "^3.3.8"
+    "vue-tsc": "^3.1.5"
   }
 }
diff --git a/examples/vue/basic-file-based-jsx/src/posts.tsx b/examples/vue/basic-file-based-jsx/src/posts.tsx
index f7a1941605..1b4c92b41d 100644
--- a/examples/vue/basic-file-based-jsx/src/posts.tsx
+++ b/examples/vue/basic-file-based-jsx/src/posts.tsx
@@ -7,7 +7,11 @@ export type PostType = {
   body: string
 }
 
-const queryURL = 'https://jsonplaceholder.typicode.com'
+let queryURL = 'https://jsonplaceholder.typicode.com'
+
+if (import.meta.env.VITE_NODE_ENV === 'test') {
+  queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}`
+}
 
 export const fetchPost = async (postId: string) => {
   console.info(`Fetching post with id ${postId}...`)
diff --git a/examples/vue/basic-file-based-jsx/src/routeTree.gen.ts b/examples/vue/basic-file-based-jsx/src/routeTree.gen.ts
index 5922c5f7b1..f5cd519d7f 100644
--- a/examples/vue/basic-file-based-jsx/src/routeTree.gen.ts
+++ b/examples/vue/basic-file-based-jsx/src/routeTree.gen.ts
@@ -11,62 +11,34 @@
 import { lazyRouteComponent } from '@tanstack/vue-router'
 
 import { Route as rootRouteImport } from './routes/__root'
-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 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 PostsIndexRouteImport } from './routes/posts.index'
 import { Route as PostsPostIdRouteImport } from './routes/posts.$postId'
-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 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'
 
-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 Char45824Char54620Char48124Char44397Route =
+  Char45824Char54620Char48124Char44397RouteImport.update({
+    id: '/대한민국',
+    path: '/대한민국',
+    getParentRoute: () => rootRouteImport,
+  } as any)
 const SfcComponentRoute = SfcComponentRouteImport.update({
   id: '/sfcComponent',
   path: '/sfcComponent',
@@ -77,35 +49,39 @@ const SfcComponentRoute = SfcComponentRouteImport.update({
     'default',
   ),
 })
-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',
+const RemountDepsRoute = RemountDepsRouteImport.update({
+  id: '/remountDeps',
+  path: '/remountDeps',
   getParentRoute: () => rootRouteImport,
 } as any)
-const groupInsideRoute = groupInsideRouteImport.update({
-  id: '/(group)/inside',
-  path: '/inside',
+const PostsRoute = PostsRouteImport.update({
+  id: '/posts',
+  path: '/posts',
   getParentRoute: () => rootRouteImport,
 } as any)
-const groupLazyinsideRoute = groupLazyinsideRouteImport.update({
-  id: '/(group)/lazyinside',
-  path: '/lazyinside',
+const NotRemountDepsRoute = NotRemountDepsRouteImport.update({
+  id: '/notRemountDeps',
+  path: '/notRemountDeps',
   getParentRoute: () => rootRouteImport,
 } as any)
-const LayoutLayout2Route = LayoutLayout2RouteImport.update({
-  id: '/_layout-2',
-  getParentRoute: () => LayoutRoute,
+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,
 } as any)
 const PostsIndexRoute = PostsIndexRouteImport.update({
   id: '/',
@@ -117,31 +93,55 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({
   path: '/$postId',
   getParentRoute: () => PostsRoute,
 } as any)
-const groupLayoutInsidelayoutRoute = groupLayoutInsidelayoutRouteImport.update({
-  id: '/insidelayout',
-  path: '/insidelayout',
-  getParentRoute: () => groupLayoutRoute,
+const LayoutLayout2Route = LayoutLayout2RouteImport.update({
+  id: '/_layout-2',
+  getParentRoute: () => LayoutRoute,
 } as any)
-const groupSubfolderInsideRoute = groupSubfolderInsideRouteImport.update({
-  id: '/(group)/subfolder/inside',
-  path: '/subfolder/inside',
+const groupLazyinsideRoute = groupLazyinsideRouteImport.update({
+  id: '/(group)/lazyinside',
+  path: '/lazyinside',
   getParentRoute: () => rootRouteImport,
 } as any)
-const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({
-  id: '/layout-a',
-  path: '/layout-a',
-  getParentRoute: () => LayoutLayout2Route,
+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 PostsPostIdEditRoute = PostsPostIdEditRouteImport.update({
-  id: '/posts_/$postId/edit',
-  path: '/posts/$postId/edit',
+const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({
+  id: '/layout-a',
+  path: '/layout-a',
+  getParentRoute: () => LayoutLayout2Route,
+} as any)
+const groupSubfolderInsideRoute = groupSubfolderInsideRouteImport.update({
+  id: '/(group)/subfolder/inside',
+  path: '/subfolder/inside',
   getParentRoute: () => rootRouteImport,
 } as any)
+const groupLayoutInsidelayoutRoute = groupLayoutInsidelayoutRouteImport.update({
+  id: '/insidelayout',
+  path: '/insidelayout',
+  getParentRoute: () => groupLayoutRoute,
+} as any)
 
 export interface FileRoutesByFullPath {
   '/': typeof IndexRoute
@@ -291,53 +291,11 @@ export interface RootRouteChildren {
 
 declare module '@tanstack/vue-router' {
   interface FileRoutesByPath {
-    '/': {
-      id: '/'
-      path: '/'
-      fullPath: '/'
-      preLoaderRoute: typeof IndexRouteImport
-      parentRoute: typeof rootRouteImport
-    }
-    '/_layout': {
-      id: '/_layout'
-      path: ''
-      fullPath: '/'
-      preLoaderRoute: typeof LayoutRouteImport
-      parentRoute: typeof rootRouteImport
-    }
-    '/editing-a': {
-      id: '/editing-a'
-      path: '/editing-a'
-      fullPath: '/editing-a'
-      preLoaderRoute: typeof EditingARouteImport
-      parentRoute: typeof rootRouteImport
-    }
-    '/editing-b': {
-      id: '/editing-b'
-      path: '/editing-b'
-      fullPath: '/editing-b'
-      preLoaderRoute: typeof EditingBRouteImport
-      parentRoute: typeof rootRouteImport
-    }
-    '/notRemountDeps': {
-      id: '/notRemountDeps'
-      path: '/notRemountDeps'
-      fullPath: '/notRemountDeps'
-      preLoaderRoute: typeof NotRemountDepsRouteImport
-      parentRoute: typeof rootRouteImport
-    }
-    '/posts': {
-      id: '/posts'
-      path: '/posts'
-      fullPath: '/posts'
-      preLoaderRoute: typeof PostsRouteImport
-      parentRoute: typeof rootRouteImport
-    }
-    '/remountDeps': {
-      id: '/remountDeps'
-      path: '/remountDeps'
-      fullPath: '/remountDeps'
-      preLoaderRoute: typeof RemountDepsRouteImport
+    '/대한민국': {
+      id: '/대한민국'
+      path: '/대한민국'
+      fullPath: '/대한민국'
+      preLoaderRoute: typeof Char45824Char54620Char48124Char44397RouteImport
       parentRoute: typeof rootRouteImport
     }
     '/sfcComponent': {
@@ -347,47 +305,54 @@ declare module '@tanstack/vue-router' {
       preLoaderRoute: typeof SfcComponentRouteImport
       parentRoute: typeof rootRouteImport
     }
-    '/대한민국': {
-      id: '/대한민국'
-      path: '/대한민국'
-      fullPath: '/대한민국'
-      preLoaderRoute: typeof Char45824Char54620Char48124Char44397RouteImport
+    '/remountDeps': {
+      id: '/remountDeps'
+      path: '/remountDeps'
+      fullPath: '/remountDeps'
+      preLoaderRoute: typeof RemountDepsRouteImport
       parentRoute: typeof rootRouteImport
     }
-    '/(another-group)/onlyrouteinside': {
-      id: '/(another-group)/onlyrouteinside'
-      path: '/onlyrouteinside'
-      fullPath: '/onlyrouteinside'
-      preLoaderRoute: typeof anotherGroupOnlyrouteinsideRouteImport
+    '/posts': {
+      id: '/posts'
+      path: '/posts'
+      fullPath: '/posts'
+      preLoaderRoute: typeof PostsRouteImport
       parentRoute: typeof rootRouteImport
     }
-    '/(group)/_layout': {
-      id: '/(group)/_layout'
+    '/notRemountDeps': {
+      id: '/notRemountDeps'
+      path: '/notRemountDeps'
+      fullPath: '/notRemountDeps'
+      preLoaderRoute: typeof NotRemountDepsRouteImport
+      parentRoute: typeof rootRouteImport
+    }
+    '/editing-b': {
+      id: '/editing-b'
+      path: '/editing-b'
+      fullPath: '/editing-b'
+      preLoaderRoute: typeof EditingBRouteImport
+      parentRoute: typeof rootRouteImport
+    }
+    '/editing-a': {
+      id: '/editing-a'
+      path: '/editing-a'
+      fullPath: '/editing-a'
+      preLoaderRoute: typeof EditingARouteImport
+      parentRoute: typeof rootRouteImport
+    }
+    '/_layout': {
+      id: '/_layout'
       path: ''
       fullPath: '/'
-      preLoaderRoute: typeof groupLayoutRouteImport
+      preLoaderRoute: typeof LayoutRouteImport
       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: ''
+    '/': {
+      id: '/'
+      path: '/'
       fullPath: '/'
-      preLoaderRoute: typeof LayoutLayout2RouteImport
-      parentRoute: typeof LayoutRoute
+      preLoaderRoute: typeof IndexRouteImport
+      parentRoute: typeof rootRouteImport
     }
     '/posts/': {
       id: '/posts/'
@@ -403,26 +368,47 @@ declare module '@tanstack/vue-router' {
       preLoaderRoute: typeof PostsPostIdRouteImport
       parentRoute: typeof PostsRoute
     }
-    '/(group)/_layout/insidelayout': {
-      id: '/(group)/_layout/insidelayout'
-      path: '/insidelayout'
-      fullPath: '/insidelayout'
-      preLoaderRoute: typeof groupLayoutInsidelayoutRouteImport
-      parentRoute: typeof groupLayoutRoute
+    '/_layout/_layout-2': {
+      id: '/_layout/_layout-2'
+      path: ''
+      fullPath: '/'
+      preLoaderRoute: typeof LayoutLayout2RouteImport
+      parentRoute: typeof LayoutRoute
     }
-    '/(group)/subfolder/inside': {
-      id: '/(group)/subfolder/inside'
-      path: '/subfolder/inside'
-      fullPath: '/subfolder/inside'
-      preLoaderRoute: typeof groupSubfolderInsideRouteImport
+    '/(group)/lazyinside': {
+      id: '/(group)/lazyinside'
+      path: '/lazyinside'
+      fullPath: '/lazyinside'
+      preLoaderRoute: typeof groupLazyinsideRouteImport
       parentRoute: typeof rootRouteImport
     }
-    '/_layout/_layout-2/layout-a': {
-      id: '/_layout/_layout-2/layout-a'
-      path: '/layout-a'
-      fullPath: '/layout-a'
-      preLoaderRoute: typeof LayoutLayout2LayoutARouteImport
-      parentRoute: typeof LayoutLayout2Route
+    '/(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'
@@ -431,13 +417,27 @@ declare module '@tanstack/vue-router' {
       preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport
       parentRoute: typeof LayoutLayout2Route
     }
-    '/posts_/$postId/edit': {
-      id: '/posts_/$postId/edit'
-      path: '/posts/$postId/edit'
-      fullPath: '/posts/$postId/edit'
-      preLoaderRoute: typeof PostsPostIdEditRouteImport
+    '/_layout/_layout-2/layout-a': {
+      id: '/_layout/_layout-2/layout-a'
+      path: '/layout-a'
+      fullPath: '/layout-a'
+      preLoaderRoute: typeof LayoutLayout2LayoutARouteImport
+      parentRoute: typeof LayoutLayout2Route
+    }
+    '/(group)/subfolder/inside': {
+      id: '/(group)/subfolder/inside'
+      path: '/subfolder/inside'
+      fullPath: '/subfolder/inside'
+      preLoaderRoute: typeof groupSubfolderInsideRouteImport
       parentRoute: typeof rootRouteImport
     }
+    '/(group)/_layout/insidelayout': {
+      id: '/(group)/_layout/insidelayout'
+      path: '/insidelayout'
+      fullPath: '/insidelayout'
+      preLoaderRoute: typeof groupLayoutInsidelayoutRouteImport
+      parentRoute: typeof groupLayoutRoute
+    }
   }
 }
 
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 e475111e40..83036509ba 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,32 +1,28 @@
 import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router'
-import { defineComponent } from 'vue'
 import { z } from 'zod'
-
-const OnlyRouteInsideComponent = defineComponent({
-  setup() {
-    const searchViaHook = useSearch({
-      from: '/(another-group)/onlyrouteinside',
-    })
-    const searchViaRouteHook = routeApi.useSearch()
-    const searchViaRouteApi = routeApi.useSearch()
-
-    return () => (
-      
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) - }, -}) +import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(another-group)/onlyrouteinside')({ - validateSearch: z.object({ hello: z.string().optional() }), + validateSearch: zodValidator(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 869e536811..557503a0c2 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,30 +1,28 @@ import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' -import { defineComponent } from 'vue' import { z } from 'zod' - -const InsideLayoutComponent = defineComponent({ - setup() { - const searchViaHook = useSearch({ from: '/(group)/_layout/insidelayout' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return () => ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) - }, -}) +import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(group)/_layout/insidelayout')({ - validateSearch: z.object({ hello: z.string().optional() }), + validateSearch: zodValidator(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 4a0caa8f8d..bec12d8de2 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,30 +1,28 @@ import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' -import { defineComponent } from 'vue' import { z } from 'zod' - -const InsideComponent = defineComponent({ - setup() { - const searchViaHook = useSearch({ from: '/(group)/inside' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return () => ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) - }, -}) +import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(group)/inside')({ - validateSearch: z.object({ hello: z.string().optional() }), + validateSearch: zodValidator(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 fdae632aee..56d8d6cae8 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,30 +1,28 @@ import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' -import { defineComponent } from 'vue' import { z } from 'zod' - -const LazyInsideComponent = defineComponent({ - setup() { - const searchViaHook = useSearch({ from: '/(group)/lazyinside' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return () => ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) - }, -}) +import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(group)/lazyinside')({ - validateSearch: z.object({ hello: z.string().optional() }), + validateSearch: zodValidator(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 8c7222ee70..b4487d163d 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,30 +1,28 @@ import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' -import { defineComponent } from 'vue' import { z } from 'zod' - -const SubfolderInsideComponent = defineComponent({ - setup() { - const searchViaHook = useSearch({ from: '/(group)/subfolder/inside' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return () => ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) - }, -}) +import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(group)/subfolder/inside')({ - validateSearch: z.object({ hello: z.string().optional() }), + validateSearch: zodValidator(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 adcc3acbd7..59c9e6fa48 100644 --- a/examples/vue/basic-file-based-jsx/src/routes/__root.tsx +++ b/examples/vue/basic-file-based-jsx/src/routes/__root.tsx @@ -8,100 +8,97 @@ 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 bc1dbfbbd0..15d17387c8 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,27 +1,24 @@ 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 522988e52b..ae580dfc02 100644 --- a/examples/vue/basic-file-based-jsx/src/routes/posts.tsx +++ b/examples/vue/basic-file-based-jsx/src/routes/posts.tsx @@ -1,38 +1,7 @@ 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: [ @@ -44,3 +13,31 @@ 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 ad20bcdf97..57963c6b64 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,28 +1,23 @@ 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/vite-env.d.ts b/examples/vue/basic-file-based-jsx/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/vue/basic-file-based-jsx/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/vue/basic-file-based-sfc/package.json b/examples/vue/basic-file-based-sfc/package.json index 87ab2c332b..eebf7574e7 100644 --- a/examples/vue/basic-file-based-sfc/package.json +++ b/examples/vue/basic-file-based-sfc/package.json @@ -10,19 +10,20 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/router-plugin": "^1.169.0", - "@tanstack/vue-router": "^1.170.42", - "@tanstack/vue-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.167.2", + "@tanstack/vue-router": "^1.168.1", + "@tanstack/vue-router-devtools": "^1.166.10", + "@tanstack/zod-adapter": "^1.166.9", "redaxios": "^0.5.1", "tailwindcss": "^4.2.2", "vue": "^3.5.16", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", "typescript": "~5.8.3", - "vite": "^8.0.14", - "vue-tsc": "^3.3.8" + "vite": "^8.0.0", + "vue-tsc": "^3.1.5" } } diff --git a/examples/vue/basic-file-based-sfc/src/posts.ts b/examples/vue/basic-file-based-sfc/src/posts.ts index f7a1941605..1b4c92b41d 100644 --- a/examples/vue/basic-file-based-sfc/src/posts.ts +++ b/examples/vue/basic-file-based-sfc/src/posts.ts @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/examples/vue/basic-file-based-sfc/src/routeTree.gen.ts b/examples/vue/basic-file-based-sfc/src/routeTree.gen.ts index 0bfdddab3d..fa00eb1ce0 100644 --- a/examples/vue/basic-file-based-sfc/src/routeTree.gen.ts +++ b/examples/vue/basic-file-based-sfc/src/routeTree.gen.ts @@ -11,73 +11,45 @@ import { lazyRouteComponent } from '@tanstack/vue-router' import { Route as rootRouteImport } from './routes/__root' -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 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 PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -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 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' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +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', getParentRoute: () => rootRouteImport, } as any).update({ component: lazyRouteComponent( - () => import('./routes/index.component.vue'), - 'default', - ), -}) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', - getParentRoute: () => rootRouteImport, -} as any).update({ - component: lazyRouteComponent( - () => import('./routes/_layout.component.vue'), - 'default', - ), -}) -const EditingARoute = EditingARouteImport.update({ - id: '/editing-a', - path: '/editing-a', - getParentRoute: () => rootRouteImport, -} as any).update({ - component: lazyRouteComponent( - () => import('./routes/editing-a.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'), - 'default', - ), -}) -const NotRemountDepsRoute = NotRemountDepsRouteImport.update({ - id: '/notRemountDeps', - path: '/notRemountDeps', - getParentRoute: () => rootRouteImport, -} as any).update({ - component: lazyRouteComponent( - () => import('./routes/notRemountDeps.component.vue'), + () => import('./routes/remountDeps.component.vue'), 'default', ), }) @@ -91,80 +63,52 @@ const PostsRoute = PostsRouteImport.update({ 'default', ), }) -const RemountDepsRoute = RemountDepsRouteImport.update({ - id: '/remountDeps', - path: '/remountDeps', +const NotRemountDepsRoute = NotRemountDepsRouteImport.update({ + id: '/notRemountDeps', + path: '/notRemountDeps', getParentRoute: () => rootRouteImport, } as any).update({ component: lazyRouteComponent( - () => import('./routes/remountDeps.component.vue'), + () => import('./routes/notRemountDeps.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, +const EditingBRoute = EditingBRouteImport.update({ + id: '/editing-b', + path: '/editing-b', + getParentRoute: () => rootRouteImport, } as any).update({ component: lazyRouteComponent( - () => import('./routes/_layout/_layout-2.component.vue'), + () => import('./routes/editing-b.component.vue'), + 'default', + ), +}) +const EditingARoute = EditingARouteImport.update({ + id: '/editing-a', + path: '/editing-a', + getParentRoute: () => rootRouteImport, +} as any).update({ + component: lazyRouteComponent( + () => import('./routes/editing-a.component.vue'), + 'default', + ), +}) +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', + getParentRoute: () => rootRouteImport, +} as any).update({ + component: lazyRouteComponent( + () => import('./routes/_layout.component.vue'), + 'default', + ), +}) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any).update({ + component: lazyRouteComponent( + () => import('./routes/index.component.vue'), 'default', ), }) @@ -192,37 +136,69 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ 'default', ), }) -const groupLayoutInsidelayoutRoute = groupLayoutInsidelayoutRouteImport +const LayoutLayout2Route = LayoutLayout2RouteImport.update({ + id: '/_layout-2', + getParentRoute: () => LayoutRoute, +} as any).update({ + component: lazyRouteComponent( + () => import('./routes/_layout/_layout-2.component.vue'), + 'default', + ), +}) +const groupLazyinsideRoute = groupLazyinsideRouteImport .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', + id: '/(group)/lazyinside', + path: '/lazyinside', getParentRoute: () => rootRouteImport, } as any) .update({ component: lazyRouteComponent( - () => import('./routes/(group)/subfolder/inside.component.vue'), + () => import('./routes/(group)/lazyinside.component.vue'), 'default', ), }) -const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => LayoutLayout2Route, +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/_layout/_layout-2/layout-a.component.vue'), + () => import('./routes/posts_.$postId.edit.component.vue'), 'default', ), }) @@ -236,16 +212,40 @@ const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ 'default', ), }) -const PostsPostIdEditRoute = PostsPostIdEditRouteImport.update({ - id: '/posts_/$postId/edit', - path: '/posts/$postId/edit', - getParentRoute: () => rootRouteImport, +const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => LayoutLayout2Route, } as any).update({ component: lazyRouteComponent( - () => import('./routes/posts_.$postId.edit.component.vue'), + () => import('./routes/_layout/_layout-2/layout-a.component.vue'), 'default', ), }) +const groupSubfolderInsideRoute = groupSubfolderInsideRouteImport + .update({ + id: '/(group)/subfolder/inside', + path: '/subfolder/inside', + getParentRoute: () => rootRouteImport, + } as any) + .update({ + component: lazyRouteComponent( + () => import('./routes/(group)/subfolder/inside.component.vue'), + 'default', + ), + }) +const groupLayoutInsidelayoutRoute = groupLayoutInsidelayoutRouteImport + .update({ + id: '/insidelayout', + path: '/insidelayout', + getParentRoute: () => groupLayoutRoute, + } as any) + .update({ + component: lazyRouteComponent( + () => import('./routes/(group)/_layout.insidelayout.component.vue'), + 'default', + ), + }) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -388,46 +388,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_layout': { - id: '/_layout' - path: '' - fullPath: '/' - preLoaderRoute: typeof LayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/editing-a': { - id: '/editing-a' - path: '/editing-a' - fullPath: '/editing-a' - preLoaderRoute: typeof EditingARouteImport - parentRoute: typeof rootRouteImport - } - '/editing-b': { - id: '/editing-b' - path: '/editing-b' - fullPath: '/editing-b' - preLoaderRoute: typeof EditingBRouteImport - parentRoute: typeof rootRouteImport - } - '/notRemountDeps': { - id: '/notRemountDeps' - path: '/notRemountDeps' - fullPath: '/notRemountDeps' - preLoaderRoute: typeof NotRemountDepsRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport + '/대한민국': { + id: '/대한민국' + path: '/대한민국' + fullPath: '/대한민국' + preLoaderRoute: typeof Char45824Char54620Char48124Char44397RouteImport parentRoute: typeof rootRouteImport } '/remountDeps': { @@ -437,47 +402,47 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof RemountDepsRouteImport parentRoute: typeof rootRouteImport } - '/대한민국': { - id: '/대한민국' - path: '/대한민국' - fullPath: '/대한민국' - preLoaderRoute: typeof Char45824Char54620Char48124Char44397RouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } - '/(another-group)/onlyrouteinside': { - id: '/(another-group)/onlyrouteinside' - path: '/onlyrouteinside' - fullPath: '/onlyrouteinside' - preLoaderRoute: typeof anotherGroupOnlyrouteinsideRouteImport + '/notRemountDeps': { + id: '/notRemountDeps' + path: '/notRemountDeps' + fullPath: '/notRemountDeps' + preLoaderRoute: typeof NotRemountDepsRouteImport parentRoute: typeof rootRouteImport } - '/(group)/_layout': { - id: '/(group)/_layout' + '/editing-b': { + id: '/editing-b' + path: '/editing-b' + fullPath: '/editing-b' + preLoaderRoute: typeof EditingBRouteImport + parentRoute: typeof rootRouteImport + } + '/editing-a': { + id: '/editing-a' + path: '/editing-a' + fullPath: '/editing-a' + preLoaderRoute: typeof EditingARouteImport + parentRoute: typeof rootRouteImport + } + '/_layout': { + id: '/_layout' path: '' fullPath: '/' - preLoaderRoute: typeof groupLayoutRouteImport + preLoaderRoute: typeof LayoutRouteImport 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: '' + '/': { + id: '/' + path: '/' fullPath: '/' - preLoaderRoute: typeof LayoutLayout2RouteImport - parentRoute: typeof LayoutRoute + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport } '/posts/': { id: '/posts/' @@ -493,26 +458,47 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRoute } - '/(group)/_layout/insidelayout': { - id: '/(group)/_layout/insidelayout' - path: '/insidelayout' - fullPath: '/insidelayout' - preLoaderRoute: typeof groupLayoutInsidelayoutRouteImport - parentRoute: typeof groupLayoutRoute + '/_layout/_layout-2': { + id: '/_layout/_layout-2' + path: '' + fullPath: '/' + preLoaderRoute: typeof LayoutLayout2RouteImport + parentRoute: typeof LayoutRoute } - '/(group)/subfolder/inside': { - id: '/(group)/subfolder/inside' - path: '/subfolder/inside' - fullPath: '/subfolder/inside' - preLoaderRoute: typeof groupSubfolderInsideRouteImport + '/(group)/lazyinside': { + id: '/(group)/lazyinside' + path: '/lazyinside' + fullPath: '/lazyinside' + preLoaderRoute: typeof groupLazyinsideRouteImport parentRoute: typeof rootRouteImport } - '/_layout/_layout-2/layout-a': { - id: '/_layout/_layout-2/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof LayoutLayout2LayoutARouteImport - parentRoute: typeof LayoutLayout2Route + '/(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' @@ -521,13 +507,27 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport parentRoute: typeof LayoutLayout2Route } - '/posts_/$postId/edit': { - id: '/posts_/$postId/edit' - path: '/posts/$postId/edit' - fullPath: '/posts/$postId/edit' - preLoaderRoute: typeof PostsPostIdEditRouteImport + '/_layout/_layout-2/layout-a': { + id: '/_layout/_layout-2/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof LayoutLayout2LayoutARouteImport + parentRoute: typeof LayoutLayout2Route + } + '/(group)/subfolder/inside': { + id: '/(group)/subfolder/inside' + path: '/subfolder/inside' + fullPath: '/subfolder/inside' + preLoaderRoute: typeof groupSubfolderInsideRouteImport parentRoute: typeof rootRouteImport } + '/(group)/_layout/insidelayout': { + id: '/(group)/_layout/insidelayout' + path: '/insidelayout' + fullPath: '/insidelayout' + preLoaderRoute: typeof groupLayoutInsidelayoutRouteImport + parentRoute: typeof groupLayoutRoute + } } } 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 f427c79321..491bb03649 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,6 +1,7 @@ import { createFileRoute } from '@tanstack/vue-router' import { z } from 'zod' +import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(another-group)/onlyrouteinside')({ - validateSearch: z.object({ hello: z.string().optional() }), + validateSearch: zodValidator(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 3b605763af..49ef8f7bb9 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,6 +1,7 @@ import { createFileRoute } from '@tanstack/vue-router' import { z } from 'zod' +import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(group)/_layout/insidelayout')({ - validateSearch: z.object({ hello: z.string().optional() }), + validateSearch: zodValidator(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 456e8fe169..f7b06f6a94 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,6 +1,7 @@ import { createFileRoute } from '@tanstack/vue-router' import { z } from 'zod' +import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(group)/inside')({ - validateSearch: z.object({ hello: z.string().optional() }), + validateSearch: zodValidator(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 7fba56aae4..b66d18a729 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,6 +1,7 @@ import { createFileRoute } from '@tanstack/vue-router' import { z } from 'zod' +import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(group)/lazyinside')({ - validateSearch: z.object({ hello: z.string().optional() }), + validateSearch: zodValidator(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 21e5d7ba0a..50aa8a44ad 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,6 +1,7 @@ import { createFileRoute } from '@tanstack/vue-router' import { z } from 'zod' +import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(group)/subfolder/inside')({ - validateSearch: z.object({ hello: z.string().optional() }), + validateSearch: zodValidator(z.object({ hello: z.string().optional() })), }) 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 deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/vue/basic-file-based-sfc/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/vue/basic/package.json b/examples/vue/basic/package.json index af74afff3a..75e84f30e7 100644 --- a/examples/vue/basic/package.json +++ b/examples/vue/basic/package.json @@ -9,17 +9,16 @@ "start": "vite" }, "dependencies": { - "@tanstack/vue-router": "^1.170.42", - "@tanstack/vue-router-devtools": "^1.167.3", + "@tanstack/vue-router": "^1.168.1", + "@tanstack/vue-router-devtools": "^1.166.10", "redaxios": "^0.5.1", "vue": "^3.5.13", "tailwindcss": "4.1.18" }, "devDependencies": { - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", - "vue-tsc": "^3.3.8", + "typescript": "^5.7.2", + "vite": "^8.0.0", + "vue-tsc": "^3.1.5", "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", "@tailwindcss/vite": "^4.2.2" diff --git a/examples/vue/basic/src/main.tsx b/examples/vue/basic/src/main.tsx index 09878913a8..dc12871db0 100644 --- a/examples/vue/basic/src/main.tsx +++ b/examples/vue/basic/src/main.tsx @@ -1,4 +1,4 @@ -import { createApp, defineComponent } from 'vue' +import { createApp } from 'vue' import { ErrorComponent, Link, @@ -102,20 +102,6 @@ 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', @@ -132,6 +118,18 @@ 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 8602de045f..1fd64723e5 100644 --- a/examples/vue/basic/src/posts.lazy.tsx +++ b/examples/vue/basic/src/posts.lazy.tsx @@ -1,39 +1,36 @@ 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/vite-env.d.ts b/examples/vue/basic/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/vue/basic/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/labeler-config.yml b/labeler-config.yml index 9da92bf7ff..69529887a6 100644 --- a/labeler-config.yml +++ b/labeler-config.yml @@ -4,12 +4,12 @@ '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/**/*' @@ -25,9 +25,6 @@ '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/**/*' diff --git a/media/header_router.png b/media/header_router.png new file mode 100644 index 0000000000..5f2d58134d Binary files /dev/null and b/media/header_router.png differ diff --git a/media/header_start.png b/media/header_start.png new file mode 100644 index 0000000000..8622986ee1 Binary files /dev/null and b/media/header_start.png differ diff --git a/nx.json b/nx.json index b7df8b2c09..3c404cd55b 100644 --- a/nx.json +++ b/nx.json @@ -1,7 +1,6 @@ { "$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, @@ -10,26 +9,10 @@ }, "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}/**/*", @@ -39,126 +22,54 @@ "default", "!{projectRoot}/tests/**/*", "!{projectRoot}/eslint.config.js" - ], - "buildProduction": ["sharedGlobals", "{projectRoot}/**/*"] + ] }, "targetDefaults": { "test:docs": { "cache": true, - "inputs": ["sharedGlobals", "{workspaceRoot}/docs/**/*"] + "inputs": ["{workspaceRoot}/docs/**/*"] }, "test:eslint": { "cache": true, - "dependsOn": ["^build", "build"], - "inputs": [ - "default", - "^production", - "{workspaceRoot}/eslint.config.js", - "dependentTaskOutputs" - ] + "dependsOn": ["^build"], + "inputs": ["default", "^production", "{workspaceRoot}/eslint.config.js"] }, "test:unit": { "cache": true, "dependsOn": ["^build"], - "inputs": [ - "default", - "^production", - "{workspaceRoot}/eslint.config.js", - "dependentTaskOutputs" - ], + "inputs": ["default", "^production"], "outputs": ["{projectRoot}/coverage"] }, "test:e2e": { "cache": true, - "dependsOn": ["^build", "test:e2e--*"], - "inputs": ["buildProduction", "^production", "dependentTaskOutputs"], - "outputs": ["{projectRoot}/dist", "{projectRoot}/test-results"], - "parallelism": false + "dependsOn": ["^build"], + "inputs": ["default", "^production"] }, "test:e2e:nitro": { "cache": true, "dependsOn": ["^build"], - "inputs": ["default", "^production"], - "parallelism": false + "inputs": ["default", "^production"] }, "test:e2e:basepath": { "cache": true, "dependsOn": ["^build"], - "inputs": ["default", "^production"], - "parallelism": false - }, - "test:e2e:preview": { - "cache": true, - "dependsOn": ["^build"], - "inputs": ["default", "^production"], - "parallelism": false + "inputs": ["default", "^production"] }, "test:types": { "cache": true, - "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" - ] + "dependsOn": ["^build"], + "inputs": ["default", "^production"] }, "build": { "cache": true, "dependsOn": ["^build"], - "inputs": ["buildProduction", "^buildProduction", "dependentTaskOutputs"], - "outputs": [ - "{projectRoot}/.netlify", - "{projectRoot}/.wrangler", - "{projectRoot}/.output", - "{projectRoot}/build", - "{projectRoot}/dist" - ] + "inputs": ["production", "^production"], + "outputs": ["{projectRoot}/build", "{projectRoot}/dist"] }, "test:build": { "cache": true, "dependsOn": ["build"], - "inputs": ["buildProduction", "dependentTaskOutputs"] - }, - "test:e2e*": { - "parallelism": false + "inputs": ["production"] } - }, - "plugins": [ - { - "name": "Playwright Sharding Plugin", - "plugin": "./scripts/nx/playwright-plugin.ts" - } - ], - "analytics": true + } } diff --git a/package.json b/package.json index 3ef11b1969..f090a3e076 100644 --- a/package.json +++ b/package.json @@ -5,39 +5,23 @@ "type": "git", "url": "git+https://github.com/TanStack/router.git" }, - "packageManager": "pnpm@12.18.0", - "engines": { - "pnpm": ">=12.18.0" - }, + "packageManager": "pnpm@10.28.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: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: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: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", + "benchmark:bundle-size": "pnpm nx run @benchmarks/bundle-size:build", + "benchmark:client-nav": "pnpm nx run @benchmarks/client-nav:test:perf", + "benchmark:ssr": "pnpm nx run @benchmarks/ssr:test:perf", "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", @@ -45,17 +29,15 @@ "format": "prettier --experimental-cli --ignore-unknown '**/*' --write", "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", + "changeset:version": "changeset version && node scripts/update-example-deps.mjs && pnpm install --no-frozen-lockfile && pnpm format", "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", - "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" + "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 --skipRemoteCache" }, "nx": { "includedScripts": [ @@ -63,25 +45,94 @@ ] }, "devDependencies": { - "@changesets/changelog-github": "^0.7.0", + "@arethetypeswrong/cli": "^0.18.2", "@changesets/cli": "^2.30.0", - "@nx/devkit": "24.0.0", - "@playwright/test": "catalog:", - "@swc-node/register": "^1.11.1", + "@eslint-react/eslint-plugin": "^1.26.2", + "@playwright/test": "^1.57.0", + "@svitejs/changesets-changelog-github-compact": "^1.2.0", "@tanstack/eslint-config": "0.4.0", - "@types/node": "catalog:", - "eslint": "catalog:", + "@tanstack/query-core": "^5.90.19", + "@tanstack/react-query": "^5.90.19", + "@tanstack/vite-config": "0.5.2", + "@types/node": "25.0.9", + "@types/react": "^19.2.8", + "@types/react-dom": "^19.2.3", + "@vitest/browser": "^4.0.17", + "@vitest/ui": "^4.0.17", + "eslint": "^9.22.0", + "eslint-plugin-react-hooks": "^5.1.0", "eslint-plugin-unused-imports": "^4.1.4", + "jsdom": "^25.0.1", "markdown-link-extractor": "^4.0.3", - "nx": "24.0.0", + "nx": "22.5.1", "prettier": "^3.8.0", + "publint": "^0.3.16", + "react": "^19.2.3", + "react-dom": "^19.2.3", + "redaxios": "^0.5.1", + "rimraf": "^6.1.2", "tinyglobby": "^0.2.15", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "catalog:", - "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "^5.9.3", + "typescript54": "npm:typescript@5.4", + "typescript55": "npm:typescript@5.5", "typescript56": "npm:typescript@5.6", "typescript57": "npm:typescript@5.7", "typescript58": "npm:typescript@5.8", - "typescript59": "npm:typescript@5.9" + "vite": "^8.0.0", + "vitest": "^4.0.17" + }, + "pnpm": { + "overrides": { + "@types/babel__traverse": "^7.28.0", + "vite-plugin-dts": "4.2.3", + "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/router-utils": "workspace:*", + "@tanstack/start-static-server-functions": "workspace:*", + "@tanstack/nitro-v2-vite-plugin": "workspace:*" + } } } diff --git a/packages/AGENTS.md b/packages/AGENTS.md deleted file mode 100644 index 0c63c3a15c..0000000000 --- a/packages/AGENTS.md +++ /dev/null @@ -1,16 +0,0 @@ -# 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 index 9e41a6b247..fa530bd13c 100644 --- a/packages/arktype-adapter/CHANGELOG.md +++ b/packages/arktype-adapter/CHANGELOG.md @@ -1,11 +1,5 @@ # @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 diff --git a/packages/arktype-adapter/package.json b/packages/arktype-adapter/package.json index ceca3fad73..e3ccdbc9bb 100644 --- a/packages/arktype-adapter/package.json +++ b/packages/arktype-adapter/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/arktype-adapter", - "version": "1.167.0", + "version": "1.166.9", "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": "node ../../node_modules/typescript59/lib/tsc.js", - "test:types:ts60": "tsc6", - "test:types:ts70": "tsc", + "test:types:ts59": "tsc", "test:unit": "vitest", "test:unit:dev": "pnpm run test:unit --watch --typecheck", "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", @@ -66,19 +66,11 @@ "devDependencies": { "@tanstack/react-router": "workspace:*", "arktype": "^2.1.7", - "@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:" + "@testing-library/jest-dom": "^6.6.3", + "@testing-library/react": "^16.2.0", + "react": "^19.0.0", + "react-dom": "^19.0.0", + "vite": "*" }, "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 ce6eb74756..a99ecda9c4 100644 --- a/packages/arktype-adapter/tests/index.test.tsx +++ b/packages/arktype-adapter/tests/index.test.tsx @@ -9,6 +9,7 @@ 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 deleted file mode 100644 index 8f7cbf15be..0000000000 --- a/packages/arktype-adapter/tests/jest-dom.setup.ts +++ /dev/null @@ -1,18 +0,0 @@ -import * as jestDomMatchers from '@testing-library/jest-dom/matchers' -import { expect } from 'vitest' -import type { TestingLibraryMatchers } from '@testing-library/jest-dom/matchers' - -// Workaround for Vitest 5: remove once testing-library/jest-dom#742 is merged -// and released, and go back to `import '@testing-library/jest-dom/vitest'`. -// That entry imports `vitest` from its own install location, which can resolve -// a different Vitest copy than the one running these tests, and its types -// augment Vitest 4's `Assertion` instead of Vitest 5's `Matchers`. -// Keep `jest-dom` in this file name: vite-plugin-solid only skips injecting -// `@testing-library/jest-dom/vitest` when a setup file path contains it. -expect.extend(jestDomMatchers) - -declare module 'vitest' { - // Type parameter names must match Vitest's declaration for the interfaces to merge. - // eslint-disable-next-line @typescript-eslint/naming-convention - interface Matchers extends TestingLibraryMatchers {} -} diff --git a/packages/arktype-adapter/tsconfig.build.json b/packages/arktype-adapter/tsconfig.build.json deleted file mode 100644 index 92be18587f..0000000000 --- a/packages/arktype-adapter/tsconfig.build.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "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 8d553e0a59..830c03f431 100644 --- a/packages/arktype-adapter/vite.config.ts +++ b/packages/arktype-adapter/vite.config.ts @@ -9,14 +9,12 @@ 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/eslint-plugin-router/CHANGELOG.md b/packages/eslint-plugin-router/CHANGELOG.md index f58a2ecd63..a8f2080101 100644 --- a/packages/eslint-plugin-router/CHANGELOG.md +++ b/packages/eslint-plugin-router/CHANGELOG.md @@ -1,11 +1,5 @@ # @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 diff --git a/packages/eslint-plugin-router/package.json b/packages/eslint-plugin-router/package.json index 9be54c220e..da86e5c009 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.162.0", + "version": "1.161.6", "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": "node ../../node_modules/typescript59/lib/tsc.js", - "test:types:ts60": "tsc6", - "test:types:ts70": "tsc", + "test:types:ts59": "tsc", "test:unit": "vitest", "test:unit:dev": "pnpm run test:unit --watch --typecheck", "test:build": "publint --strict && attw --pack .", @@ -56,26 +56,11 @@ }, "devDependencies": { "@typescript-eslint/rule-tester": "^8.23.0", - "combinate": "catalog:", + "combinate": "^1.1.11", "eslint": "^9.22.0", - "vite": "*", - "@tanstack/vite-config": "catalog:", - "vitest": "catalog:", - "@arethetypeswrong/cli": "catalog:", - "publint": "catalog:", - "rimraf": "catalog:" + "vite": "*" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0" - }, - "nx": { - "targets": { - "build": { - "inputs": [ - "...", - "{workspaceRoot}/eslint.config.js" - ] - } - } } } diff --git a/packages/eslint-plugin-router/tsconfig.build.json b/packages/eslint-plugin-router/tsconfig.build.json deleted file mode 100644 index 92be18587f..0000000000 --- a/packages/eslint-plugin-router/tsconfig.build.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "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 77ecb53a97..8769e2779e 100644 --- a/packages/eslint-plugin-router/vite.config.ts +++ b/packages/eslint-plugin-router/vite.config.ts @@ -16,7 +16,6 @@ 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 deleted file mode 100644 index 329bfe8343..0000000000 --- a/packages/eslint-plugin-start/.attw.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "ignoreRules": ["false-export-default"] -} diff --git a/packages/eslint-plugin-start/CHANGELOG.md b/packages/eslint-plugin-start/CHANGELOG.md deleted file mode 100644 index 45cec4b95a..0000000000 --- a/packages/eslint-plugin-start/CHANGELOG.md +++ /dev/null @@ -1,13 +0,0 @@ -# @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/eslint-plugin-start/lint-improvements.md b/packages/eslint-plugin-start/lint-improvements.md deleted file mode 100644 index ff46b57353..0000000000 --- a/packages/eslint-plugin-start/lint-improvements.md +++ /dev/null @@ -1,693 +0,0 @@ -# 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 deleted file mode 100644 index 4e312fd9f6..0000000000 --- a/packages/eslint-plugin-start/no-async-client-component.md +++ /dev/null @@ -1,346 +0,0 @@ -# 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 deleted file mode 100644 index 11450f2bd6..0000000000 --- a/packages/eslint-plugin-start/no-client-code-in-server-component.md +++ /dev/null @@ -1,163 +0,0 @@ -# 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 deleted file mode 100644 index 803264ed10..0000000000 --- a/packages/eslint-plugin-start/package.json +++ /dev/null @@ -1,82 +0,0 @@ -{ - "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 deleted file mode 100644 index 53c8ed7705..0000000000 --- a/packages/eslint-plugin-start/src/__tests__/no-async-client-component.rule.test.ts +++ /dev/null @@ -1,287 +0,0 @@ -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 deleted file mode 100644 index 39c780417f..0000000000 --- a/packages/eslint-plugin-start/src/__tests__/no-client-code-in-server-component.rule.test.ts +++ /dev/null @@ -1,289 +0,0 @@ -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 deleted file mode 100644 index 1f4ecae36f..0000000000 --- a/packages/eslint-plugin-start/src/__tests__/tsconfig.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "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 deleted file mode 100644 index a6815a6328..0000000000 --- a/packages/eslint-plugin-start/src/index.ts +++ /dev/null @@ -1,45 +0,0 @@ -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 deleted file mode 100644 index 01df0f0239..0000000000 --- a/packages/eslint-plugin-start/src/rules.ts +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index cf377ac6c4..0000000000 --- a/packages/eslint-plugin-start/src/rules/no-async-client-component/async-component-detector.ts +++ /dev/null @@ -1,121 +0,0 @@ -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 deleted file mode 100644 index ffc2809518..0000000000 --- a/packages/eslint-plugin-start/src/rules/no-async-client-component/constants.ts +++ /dev/null @@ -1,27 +0,0 @@ -/** - * 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 deleted file mode 100644 index 126019e93f..0000000000 --- a/packages/eslint-plugin-start/src/rules/no-async-client-component/context-analyzer.ts +++ /dev/null @@ -1,203 +0,0 @@ -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 deleted file mode 100644 index 54a69a6fb8..0000000000 --- a/packages/eslint-plugin-start/src/rules/no-async-client-component/no-async-client-component.rule.ts +++ /dev/null @@ -1,430 +0,0 @@ -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 deleted file mode 100644 index 3b736da2d9..0000000000 --- a/packages/eslint-plugin-start/src/rules/no-async-client-component/render-graph-builder.ts +++ /dev/null @@ -1,551 +0,0 @@ -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 deleted file mode 100644 index 87fb9a8a3e..0000000000 --- a/packages/eslint-plugin-start/src/rules/no-client-code-in-server-component/constants.ts +++ /dev/null @@ -1,266 +0,0 @@ -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 deleted file mode 100644 index 57d314ee9c..0000000000 --- a/packages/eslint-plugin-start/src/rules/no-client-code-in-server-component/no-client-code-in-server-component.rule.ts +++ /dev/null @@ -1,472 +0,0 @@ -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 deleted file mode 100644 index 7a349be6cd..0000000000 --- a/packages/eslint-plugin-start/src/rules/no-client-code-in-server-component/transitive-analyzer.ts +++ /dev/null @@ -1,245 +0,0 @@ -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 deleted file mode 100644 index 3457b7d3c1..0000000000 --- a/packages/eslint-plugin-start/src/rules/no-client-code-in-server-component/violation-detector.ts +++ /dev/null @@ -1,316 +0,0 @@ -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 deleted file mode 100644 index a80f9a0c77..0000000000 --- a/packages/eslint-plugin-start/src/shared/use-client-resolver.ts +++ /dev/null @@ -1,34 +0,0 @@ -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 deleted file mode 100644 index 74c3053188..0000000000 --- a/packages/eslint-plugin-start/src/types.ts +++ /dev/null @@ -1,3 +0,0 @@ -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 deleted file mode 100644 index 04579e47c8..0000000000 --- a/packages/eslint-plugin-start/src/utils/get-docs-url.ts +++ /dev/null @@ -1,2 +0,0 @@ -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 deleted file mode 100644 index 1715152a91..0000000000 --- a/packages/eslint-plugin-start/tsconfig.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "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 deleted file mode 100644 index 8769e2779e..0000000000 --- a/packages/eslint-plugin-start/vite.config.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 509da6a4ec..0000000000 --- a/packages/history/AGENTS.md +++ /dev/null @@ -1,3 +0,0 @@ -# History - -Accepted browser push/replace operations update the in-memory location immediately and batch native writes into a microtask. Preserve coalescing: the latest href/state wins, but any queued push wins over replaces. Use `history.flush()` when native browser state must be current; verify subsequent updates still flush afterward in `tests/createBrowserHistory.test.ts`. diff --git a/packages/history/CHANGELOG.md b/packages/history/CHANGELOG.md index ca3341088c..bcf0ac6525 100644 --- a/packages/history/CHANGELOG.md +++ b/packages/history/CHANGELOG.md @@ -1,69 +1,5 @@ # @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 diff --git a/packages/history/package.json b/packages/history/package.json index d09c710d2f..2fad180b24 100644 --- a/packages/history/package.json +++ b/packages/history/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/history", - "version": "1.162.5", + "version": "1.161.6", "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": "node ../../node_modules/typescript59/lib/tsc.js", - "test:types:ts60": "tsc6", - "test:types:ts70": "tsc", + "test:types:ts59": "tsc", "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", "test:unit": "vitest", "test:unit:dev": "pnpm run test:unit --watch", @@ -59,12 +59,6 @@ "node": ">=20.19" }, "devDependencies": { - "vite": "*", - "@tanstack/vite-config": "catalog:", - "vitest": "catalog:", - "jsdom": "catalog:", - "@arethetypeswrong/cli": "catalog:", - "publint": "catalog:", - "rimraf": "catalog:" + "vite": "*" } } diff --git a/packages/history/src/index.ts b/packages/history/src/index.ts index d2f80581b9..705dbf0111 100644 --- a/packages/history/src/index.ts +++ b/packages/history/src/index.ts @@ -36,9 +36,7 @@ export interface RouterHistory { flush: () => void destroy: () => void notify: (action: SubscriberHistoryAction) => void - _getBlockers: () => Array _ignoreSubscribers?: boolean - _ignoreNextBeforeUnload?: (href: string) => void } export interface HistoryLocation extends ParsedPath { @@ -98,40 +96,12 @@ 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, ignoreBlocker: boolean) => void + go: (n: number) => void back: (ignoreBlocker: boolean) => void forward: (ignoreBlocker: boolean) => void createHref: (path: string) => string @@ -156,21 +126,27 @@ export function createHistory(opts: { else location = opts.getLocation() } - 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') - ) { + 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) { for (const blocker of blockers) { - const nextLocation = parseHref(args.path, args.state) + const nextLocation = parseHref(actionInfo.path, actionInfo.state) const isBlocked = await blocker.blockerFn({ currentLocation: location, nextLocation, - action: args.type, + action: actionInfo.type, }) if (isBlocked) { opts.onBlocked?.() @@ -179,7 +155,7 @@ export function createHistory(opts: { } } - args.task() + task() } return { @@ -228,7 +204,7 @@ export function createHistory(opts: { go: (index, navigateOpts) => { tryNavigation({ task: () => { - opts.go(index, navigateOpts?.ignoreBlocker ?? false) + opts.go(index) handleIndexChange({ type: 'GO', index }) }, navigateOpts, @@ -270,11 +246,13 @@ export function createHistory(opts: { flush: () => opts.flush?.(), destroy: () => opts.destroy?.(), notify, - _getBlockers: () => opts.getBlockers?.() ?? [], } } function assignKeyAndIndex(index: number, state: HistoryState | undefined) { + if (!state) { + state = {} + } const key = createRandomKey() return { ...state, @@ -317,8 +295,7 @@ export function createBrowserHistory(opts?: { const _setBlockers = (newBlockers: Array) => (blockers = newBlockers) - const createHref = (path: string) => - normalizeHref(opts?.createHref ? opts.createHref(path) : path) + const createHref = opts?.createHref ?? ((path) => path) const parseLocation = opts?.parseLocation ?? (() => @@ -345,9 +322,6 @@ 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 @@ -355,14 +329,18 @@ export function createBrowserHistory(opts?: { let next: | 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 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 // This function flushes the next update to the browser history const flush = () => { @@ -374,48 +352,46 @@ export function createBrowserHistory(opts?: { history._ignoreSubscribers = true // Update the browser history - ;(next[2 /* is push */] ? win.history.pushState : win.history.replaceState)( - next[1 /* state */], + ;(next.isPush ? win.history.pushState : win.history.replaceState)( + next.state, '', - next[0 /* href */], + next.href, ) // Stop ignoring subscriber updates history._ignoreSubscribers = false - // Clear the queued action after it reaches browser history. + // Reset the nextIsPush flag and clear the scheduled update next = undefined + scheduled = undefined rollbackLocation = undefined } // This function queues up a call to update the browser history const queueHistoryAction = ( - isPush: boolean, + type: 'push' | 'replace', destHref: string, state: any, ) => { - // 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 + const href = createHref(destHref) - if (!hasPendingAction) { + if (!scheduled) { rollbackLocation = currentLocation } - // Keep the optimistic location in the router's logical URL space. + // Update the location in memory currentLocation = parseHref(destHref, state) // Keep track of the next location we need to flush to the URL - next = [ - href ?? currentLocation.href, + next = { + href, state, - next?.[2 /* is push */] || isPush, - ] + isPush: next?.isPush || type === 'push', + } - if (!hasPendingAction) { + if (!scheduled) { // Schedule an update to the browser history - queueMicrotask(() => flush()) + scheduled = Promise.resolve().then(() => flush()) } } @@ -426,10 +402,6 @@ 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 @@ -466,7 +438,7 @@ export function createBrowserHistory(opts?: { }) if (isBlocked) { ignoreNextPop = true - win.history.go(-delta) + win.history.go(1) history.notify(notify) return } @@ -516,31 +488,23 @@ export function createBrowserHistory(opts?: { const history = createHistory({ getLocation, getLength: () => win.history.length, - pushState: (href, state) => queueHistoryAction(true, href, state), - replaceState: (href, state) => queueHistoryAction(false, href, state), + pushState: (href, state) => queueHistoryAction('push', href, state), + replaceState: (href, state) => queueHistoryAction('replace', 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, ignoreBlocker) => { + go: (n) => { nextPopIsGo = true - if (ignoreBlocker) { - skipBlockerNextPop = true - ignoreNextBeforeUnload = true - } win.history.go(n) }, - createHref, + createHref: (href) => createHref(href), flush, destroy: () => { win.history.pushState = originalPushState @@ -562,21 +526,6 @@ 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) @@ -607,17 +556,14 @@ export function createHashHistory(opts?: { window?: any }): RouterHistory { return createBrowserHistory({ window: win, parseLocation: () => { - // `#/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, - ) + 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) }, createHref: (href) => `${win.location.pathname}${win.location.search}#${href}`, @@ -657,13 +603,13 @@ export function createMemoryHistory( getLength: () => entries.length, pushState: (path, state) => { // Removes all subsequent entries after the current index to start a new branch - index = index < entries.length - 1 ? index + 1 : entries.length - states[index] = state - entries[index] = path if (index < entries.length - 1) { - entries.length = index + 1 - states.length = index + 1 + entries.splice(index + 1) + states.splice(index + 1) } + states.push(state) + entries.push(path) + index = Math.max(entries.length - 1, 0) }, replaceState: (path, state) => { states[index] = state @@ -678,89 +624,54 @@ export function createMemoryHistory( go: (n) => { index = Math.min(Math.max(index + n, 0), entries.length - 1) }, - createHref: normalizeHref, + createHref: (path) => path, getBlockers: _getBlockers, setBlockers: _setBlockers, }) } -const noop = () => {} +/** + * Sanitize a path to prevent open redirect vulnerabilities. + * Removes control characters and collapses leading double slashes. + */ +function sanitizePath(path: string): string { + // Remove ASCII control characters (0x00-0x1F) and DEL (0x7F) + // These include CR (\r = 0x0D), LF (\n = 0x0A), and other potentially dangerous characters + // eslint-disable-next-line no-control-regex + let sanitized = path.replace(/[\x00-\x1f\x7f]/g, '') -class ServerHistory implements RouterHistory { - declare private _subscribers?: RouterHistory['subscribers'] - - constructor(public location: HistoryLocation) {} - - get length() { - return 1 + // Prevent open redirect via protocol-relative URLs (e.g. "//evil.com") + // Collapse leading double slashes to a single slash + if (sanitized.startsWith('//')) { + sanitized = '/' + sanitized.replace(/^\/+/, '') } - // 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)) + return sanitized } export function parseHref( href: string, state: ParsedHistoryState | undefined, ): HistoryLocation { - const sanitizedHref = normalizeHref(href) + const sanitizedHref = sanitizePath(href) const hashIndex = sanitizedHref.indexOf('#') const searchIndex = sanitizedHref.indexOf('?') - if (!state) { - const key = createRandomKey() - state = { [stateIndexKey]: 0, key, __TSR_key: key } - } + + const addedKey = createRandomKey() return { href: sanitizedHref, - pathname: sanitizedHref.slice( + pathname: sanitizedHref.substring( 0, - hashIndex > -1 - ? searchIndex > -1 + hashIndex > 0 + ? searchIndex > 0 ? Math.min(hashIndex, searchIndex) : hashIndex - : searchIndex > -1 + : searchIndex > 0 ? searchIndex : sanitizedHref.length, ), - hash: hashIndex > -1 ? sanitizedHref.slice(hashIndex) : '', + hash: hashIndex > -1 ? sanitizedHref.substring(hashIndex) : '', search: searchIndex > -1 ? sanitizedHref.slice( @@ -768,11 +679,11 @@ export function parseHref( hashIndex === -1 ? undefined : hashIndex, ) : '', - state, + state: state || { [stateIndexKey]: 0, key: addedKey, __TSR_key: addedKey }, } } // Thanks co-pilot! function createRandomKey() { - return (Math.random() + 1).toString(36).slice(7) + return (Math.random() + 1).toString(36).substring(7) } diff --git a/packages/history/tests/createBrowserHistory.test.ts b/packages/history/tests/createBrowserHistory.test.ts deleted file mode 100644 index 5b24744fb5..0000000000 --- a/packages/history/tests/createBrowserHistory.test.ts +++ /dev/null @@ -1,307 +0,0 @@ -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 e54b1a1ae1..4d68238249 100644 --- a/packages/history/tests/createHashHistory.test.ts +++ b/packages/history/tests/createHashHistory.test.ts @@ -1,162 +1,8 @@ -import { describe, expect, test, vi } from 'vitest' +import { describe, expect, test } 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 c0f565115e..1a27c04919 100644 --- a/packages/history/tests/createMemoryHistory.test.ts +++ b/packages/history/tests/createMemoryHistory.test.ts @@ -2,53 +2,6 @@ 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] }) @@ -99,38 +52,6 @@ describe('createMemoryHistory', () => { expect(history.location.pathname).toBe('/b') }) - test('discards forward entries and their state when pushing a new branch', () => { - const initialEntries = ['/'] - const history = createMemoryHistory({ initialEntries }) - history.push('/kept', { marker: 'kept' }) - const keptState = history.location.state - history.push('/discarded-first', { marker: 'discarded-first' }) - history.push('/discarded-last', { marker: 'discarded-last' }) - history.go(-2) - history.push('/new', { marker: 'new' }) - - expect(initialEntries).toEqual(['/', '/kept', '/new']) - expect(history.length).toBe(3) - expect(history.location.pathname).toBe('/new') - expect(history.location.state).toMatchObject({ - __TSR_index: 2, - marker: 'new', - }) - const newState = history.location.state - - history.forward() - expect(history.location.pathname).toBe('/new') - expect(history.location.state).toBe(newState) - - history.back() - expect(history.location.pathname).toBe('/kept') - expect(history.location.state).toBe(keptState) - - history.forward() - expect(history.location.pathname).toBe('/new') - expect(history.location.state).toBe(newState) - }) - test('length', () => { const history = createMemoryHistory() expect(history.length).toBe(1) diff --git a/packages/history/tests/createServerHistory.test.ts b/packages/history/tests/createServerHistory.test.ts deleted file mode 100644 index c036cea185..0000000000 --- a/packages/history/tests/createServerHistory.test.ts +++ /dev/null @@ -1,95 +0,0 @@ -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 aa6882e6fc..e1b8db9c1a 100644 --- a/packages/history/tests/parseHref.test.ts +++ b/packages/history/tests/parseHref.test.ts @@ -1,19 +1,7 @@ import { describe, expect, test } from 'vitest' import { parseHref } from '../src' -const baseUrl = new URL('https://victim.example/base') - describe('parseHref', () => { - test.each(['\x00', '\x01', '\x1f', '\x7f', '\t', '\n', '\r'])( - 'preserves browser path, query, and fragment interpretation for %j', - (character) => { - const href = `/a${character}b?q=a${character}b#a${character}b` - expect(new URL(parseHref(href, undefined).href, baseUrl).href).toBe( - new URL(href, baseUrl).href, - ) - }, - ) - test('works', () => { const parsed = parseHref('/foo?bar=baz#qux', {} as any) expect(parsed.pathname).toEqual('/foo') @@ -21,42 +9,6 @@ describe('parseHref', () => { expect(parsed.hash).toEqual('#qux') }) - test.each([ - ['?x=1', { pathname: '', search: '?x=1', hash: '' }], - ['#top', { pathname: '', search: '', hash: '#top' }], - ['?x=1#top', { pathname: '', search: '?x=1', hash: '#top' }], - ['#top?x=1', { pathname: '', search: '', hash: '#top?x=1' }], - ])( - 'keeps a leading query or fragment out of the pathname: %j', - (href, expected) => { - expect(parseHref(href, undefined)).toMatchObject({ href, ...expected }) - }, - ) - - test.each([ - { __TSR_index: 2 }, - { __TSR_index: 2, key: 'legacy-key', __TSR_key: 'current-key' }, - ])('preserves supplied state %j', (state) => { - Object.freeze(state) - expect(parseHref('/foo', state).state).toBe(state) - }) - - test('creates independent initial states with matching history keys', () => { - const first = parseHref('/foo', undefined) - const second = parseHref('/bar', undefined) - - for (const location of [first, second]) { - expect(location.state).toEqual({ - __TSR_index: 0, - key: expect.any(String), - __TSR_key: location.state.key, - }) - } - - first.state.__TSR_index = 1 - expect(second.state.__TSR_index).toBe(0) - }) - describe('open redirect prevention', () => { test('strips CR characters to prevent open redirect', () => { // If \r (CR) is in the href, it should be stripped @@ -93,86 +45,6 @@ describe('parseHref', () => { expect(url.pathname).toBe('/evil.com/') }) - test.each([ - '//evil.com/path', - '///evil.com/path', - '/\\evil.com/path', - '/\\\\evil.com/path', - '/\\/evil.com/path', - '\\/evil.com/path', - '\\\\evil.com/path', - ' /\\evil.com/path', - '\x01//evil.com/path', - '/\t/evil.com/path', - ])('keeps protocol-relative input %j on the current origin', (href) => { - const parsed = parseHref(href, undefined) - const url = new URL(parsed.href, 'https://victim.example') - - expect(url.origin).toBe('https://victim.example') - }) - - test.each([ - 'h\x00ttps://evil.example', - 'java\x00script:alert(1)', - '/\x00/evil.example', - '\x7f//evil.example', - '/%5c/evil.example', - '/%2f/evil.example', - '?next=//evil.example', - '#//evil.example', - '//evil.example', - '', - ' ', - '\x00', - '\x00\t\n', - ])('does not make same-origin input %j cross-origin', (href) => { - expect(new URL(href, baseUrl).origin).toBe(baseUrl.origin) - - const parsed = parseHref(href, undefined) - - expect(new URL(parsed.href, baseUrl).origin).toBe(baseUrl.origin) - }) - - test('matches WHATWG parsing of protocol-relative prefixes', () => { - const alphabet = [ - '/', - '\\', - '\t', - '\n', - '\r', - '\x00', - '\x0b', - ' ', - '\x7f', - ] - - for (let length = 0; length <= 4; length++) { - const count = alphabet.length ** length - for (let value = 0; value < count; value++) { - let input = '' - let cursor = value - for (let index = 0; index < length; index++) { - input += alphabet[cursor % alphabet.length] - cursor = Math.floor(cursor / alphabet.length) - } - input += 'evil.example/path' - - try { - new URL(input, baseUrl) - } catch { - continue - } - - const parsed = parseHref(input, undefined) - - expect( - new URL(parsed.href, baseUrl).origin, - JSON.stringify(input), - ).toBe(baseUrl.origin) - } - } - }) - test('normal paths remain unchanged', () => { const parsed = parseHref('/users/profile?id=1#section', undefined) expect(parsed.href).toBe('/users/profile?id=1#section') diff --git a/packages/history/tsconfig.build.json b/packages/history/tsconfig.build.json deleted file mode 100644 index 92be18587f..0000000000 --- a/packages/history/tsconfig.build.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "rootDir": "./src" - }, - "include": ["src"] -} diff --git a/packages/history/vite.config.ts b/packages/history/vite.config.ts index 5eef55c1d9..830c03f431 100644 --- a/packages/history/vite.config.ts +++ b/packages/history/vite.config.ts @@ -17,6 +17,5 @@ export default mergeConfig( tanstackViteConfig({ entry: './src/index.ts', srcDir: './src', - tsconfigPath: './tsconfig.build.json', }), ) diff --git a/packages/nitro-v2-vite-plugin/CHANGELOG.md b/packages/nitro-v2-vite-plugin/CHANGELOG.md new file mode 100644 index 0000000000..c27fc171e9 --- /dev/null +++ b/packages/nitro-v2-vite-plugin/CHANGELOG.md @@ -0,0 +1,13 @@ +# @tanstack/nitro-v2-vite-plugin + +## 1.154.9 + +### Patch Changes + +- build: update to vite-config 5.x (rolldown) ([#6926](https://github.com/TanStack/router/pull/6926)) + +## 1.154.8 + +### Patch Changes + +- fix: build with @tanstack/vite-config 0.4.3 ([#6923](https://github.com/TanStack/router/pull/6923)) diff --git a/packages/nitro-v2-vite-plugin/README.md b/packages/nitro-v2-vite-plugin/README.md new file mode 100644 index 0000000000..5882e61120 --- /dev/null +++ b/packages/nitro-v2-vite-plugin/README.md @@ -0,0 +1 @@ +# Experimental Nitro v2 Vite Plugin diff --git a/packages/eslint-plugin-start/eslint.config.js b/packages/nitro-v2-vite-plugin/eslint.config.js similarity index 100% rename from packages/eslint-plugin-start/eslint.config.js rename to packages/nitro-v2-vite-plugin/eslint.config.js diff --git a/packages/nitro-v2-vite-plugin/package.json b/packages/nitro-v2-vite-plugin/package.json new file mode 100644 index 0000000000..c315a0dbc4 --- /dev/null +++ b/packages/nitro-v2-vite-plugin/package.json @@ -0,0 +1,69 @@ +{ + "name": "@tanstack/nitro-v2-vite-plugin", + "version": "1.154.9", + "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.13.1", + "pathe": "^2.0.3" + }, + "peerDependencies": { + "vite": ">=7.0.0" + } +} diff --git a/packages/nitro-v2-vite-plugin/src/index.ts b/packages/nitro-v2-vite-plugin/src/index.ts new file mode 100644 index 0000000000..d8ae5009de --- /dev/null +++ b/packages/nitro-v2-vite-plugin/src/index.ts @@ -0,0 +1,197 @@ +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 new file mode 100644 index 0000000000..bd398a8728 --- /dev/null +++ b/packages/nitro-v2-vite-plugin/tsconfig.json @@ -0,0 +1,8 @@ +{ + "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 new file mode 100644 index 0000000000..7e4ae12a99 --- /dev/null +++ b/packages/nitro-v2-vite-plugin/vite.config.ts @@ -0,0 +1,13 @@ +import { defineConfig, mergeConfig } from 'vitest/config' +import { tanstackViteConfig } from '@tanstack/vite-config' + +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 index f74de5f187..5cf7264cc0 100644 --- a/packages/react-router-devtools/CHANGELOG.md +++ b/packages/react-router-devtools/CHANGELOG.md @@ -1,70 +1,5 @@ # @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 diff --git a/packages/react-router-devtools/README.md b/packages/react-router-devtools/README.md index 0079d7c065..7be76f46c2 100644 --- a/packages/react-router-devtools/README.md +++ b/packages/react-router-devtools/README.md @@ -1,22 +1,5 @@ -
- - - - 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 969371a6a6..928198fc71 100644 --- a/packages/react-router-devtools/package.json +++ b/packages/react-router-devtools/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/react-router-devtools", - "version": "1.167.3", + "version": "1.166.10", "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": "node ../../node_modules/typescript59/lib/tsc.js", - "test:types:ts60": "tsc6", - "test:types:ts70": "tsc", + "test:types:ts59": "tsc", "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", "build": "vite build" }, @@ -65,21 +65,10 @@ "@tanstack/router-devtools-core": "workspace:*" }, "devDependencies": { - "@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:" + "@vitejs/plugin-react": "^4.3.4", + "react": ">=19", + "react-dom": ">=19", + "vite": "*" }, "peerDependencies": { "@tanstack/react-router": "workspace:^", diff --git a/packages/react-router-devtools/src/TanStackRouterDevtools.tsx b/packages/react-router-devtools/src/TanStackRouterDevtools.tsx index 2248d27ef6..925e7687e9 100644 --- a/packages/react-router-devtools/src/TanStackRouterDevtools.tsx +++ b/packages/react-router-devtools/src/TanStackRouterDevtools.tsx @@ -1,5 +1,3 @@ -'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 ee7fba313b..46118bf2e6 100644 --- a/packages/react-router-devtools/src/TanStackRouterDevtoolsPanel.tsx +++ b/packages/react-router-devtools/src/TanStackRouterDevtoolsPanel.tsx @@ -1,5 +1,3 @@ -'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 e711869ce8..3db31a9b73 100644 --- a/packages/react-router-devtools/src/index.ts +++ b/packages/react-router-devtools/src/index.ts @@ -1,5 +1,3 @@ -'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 deleted file mode 100644 index 92be18587f..0000000000 --- a/packages/react-router-devtools/tsconfig.build.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "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 fc0a511b1a..1599b212c0 100644 --- a/packages/react-router-devtools/tsconfig.json +++ b/packages/react-router-devtools/tsconfig.json @@ -2,8 +2,7 @@ "extends": "../../tsconfig.json", "compilerOptions": { "jsx": "react-jsx", - "jsxImportSource": "react", - "types": ["node"] + "jsxImportSource": "react" }, "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 0f6d3b9227..9cbd5e5179 100644 --- a/packages/react-router-devtools/vite.config.ts +++ b/packages/react-router-devtools/vite.config.ts @@ -17,7 +17,6 @@ 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 index d0fc73ff50..b62986d681 100644 --- a/packages/react-router-ssr-query/CHANGELOG.md +++ b/packages/react-router-ssr-query/CHANGELOG.md @@ -1,71 +1,5 @@ # @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 diff --git a/packages/react-router-ssr-query/README.md b/packages/react-router-ssr-query/README.md index c3a60d1008..0a19fd3b81 100644 --- a/packages/react-router-ssr-query/README.md +++ b/packages/react-router-ssr-query/README.md @@ -2,21 +2,7 @@ # TanStack React Router - - - - TanStack React Router - +![TanStack Router Header](https://raw.githubusercontent.com/TanStack/router/main/media/header_router.png) 🤖 Type-safe router w/ built-in caching & URL state management for React! diff --git a/packages/react-router-ssr-query/package.json b/packages/react-router-ssr-query/package.json index 7333146047..a6982e9ea6 100644 --- a/packages/react-router-ssr-query/package.json +++ b/packages/react-router-ssr-query/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/react-router-ssr-query", - "version": "1.167.3", + "version": "1.166.10", "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": "node ../../node_modules/typescript59/lib/tsc.js", - "test:types:ts60": "tsc6", - "test:types:ts70": "tsc", + "test:types:ts59": "tsc", "test:unit": "exit 0; vitest", "test:unit:dev": "pnpm run test:unit --watch", "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", @@ -67,28 +67,18 @@ "@tanstack/router-ssr-query-core": "workspace:*" }, "devDependencies": { - "@vitejs/plugin-react": "catalog:", - "react": "catalog:", - "react-dom": "catalog:", + "@vitejs/plugin-react": "^4.3.4", + "react": ">=19", + "react-dom": ">=19", "@tanstack/react-router": "workspace:*", - "@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:" + "@tanstack/react-query": ">=5.90.0", + "vite": "*" }, "peerDependencies": { "react": ">=18.0.0 || >=19.0.0", "react-dom": ">=18.0.0 || >=19.0.0", - "@tanstack/query-core": ">=5.102.0", - "@tanstack/react-router": ">=1.170.33", - "@tanstack/react-query": ">=5.102.0" + "@tanstack/query-core": ">=5.90.0", + "@tanstack/react-router": ">=1.127.0", + "@tanstack/react-query": ">=5.90.0" } } diff --git a/packages/react-router-ssr-query/tsconfig.build.json b/packages/react-router-ssr-query/tsconfig.build.json deleted file mode 100644 index 92be18587f..0000000000 --- a/packages/react-router-ssr-query/tsconfig.build.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "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 ffe4359c13..7b2f860743 100644 --- a/packages/react-router-ssr-query/vite.config.ts +++ b/packages/react-router-ssr-query/vite.config.ts @@ -17,7 +17,6 @@ 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 index 7e1e2f1a62..b86a3527b6 100644 --- a/packages/react-router/CHANGELOG.md +++ b/packages/react-router/CHANGELOG.md @@ -1,730 +1,5 @@ # @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 diff --git a/packages/react-router/README.md b/packages/react-router/README.md index c3a60d1008..0a19fd3b81 100644 --- a/packages/react-router/README.md +++ b/packages/react-router/README.md @@ -2,21 +2,7 @@ # TanStack React Router - - - - TanStack React Router - +![TanStack Router Header](https://raw.githubusercontent.com/TanStack/router/main/media/header_router.png) 🤖 Type-safe router w/ built-in caching & URL state management for React! diff --git a/packages/react-router/bin/intent.js b/packages/react-router/bin/intent.js new file mode 100755 index 0000000000..5b08532885 --- /dev/null +++ b/packages/react-router/bin/intent.js @@ -0,0 +1,25 @@ +#!/usr/bin/env node +// Auto-generated by @tanstack/intent setup +// Exposes the intent end-user CLI for consumers of this library. +// Commit this file, then add to your package.json: +// "bin": { "intent": "./bin/intent.js" } +try { + await import('@tanstack/intent/intent-library') +} catch (e) { + const isModuleNotFound = + e?.code === 'ERR_MODULE_NOT_FOUND' || e?.code === 'MODULE_NOT_FOUND' + const missingIntentLibrary = + typeof e?.message === 'string' && e.message.includes('@tanstack/intent') + + if (isModuleNotFound && missingIntentLibrary) { + console.error('@tanstack/intent is not installed.') + console.error('') + console.error('Install it as a dev dependency:') + console.error(' npm add -D @tanstack/intent') + console.error('') + console.error('Or run directly:') + console.error(' npx @tanstack/intent@latest list') + process.exit(1) + } + throw e +} diff --git a/packages/react-router/package.json b/packages/react-router/package.json index 9a61d5af25..cfc57e0077 100644 --- a/packages/react-router/package.json +++ b/packages/react-router/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/react-router", - "version": "1.170.46", + "version": "1.168.1", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", @@ -27,18 +27,20 @@ "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": "node ../../node_modules/typescript59/lib/tsc.js -p tsconfig.legacy.json", - "test:types:ts60": "tsc6 -p tsconfig.legacy.json", - "test:types:ts70": "tsc -p tsconfig.legacy.json", + "test:types:ts59": "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": "vite build" + "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" }, "type": "module", "types": "dist/esm/index.d.ts", @@ -46,10 +48,6 @@ "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", @@ -81,45 +79,40 @@ "default": "./dist/cjs/ssr/client.cjs" } }, - "./package.json": "./package.json" + "./package.json": "./package.json", + "./llms": { + "import": { + "types": "./dist/llms/index.d.ts", + "default": "./dist/llms/index.js" + } + } }, "sideEffects": false, "files": [ "dist", - "src", - "skills", - "!skills/_artifacts" + "src" ], "engines": { "node": ">=20.19" }, "dependencies": { "@tanstack/history": "workspace:*", - "@tanstack/react-store": "^0.11.2", + "@tanstack/react-store": "^0.9.2", "@tanstack/router-core": "workspace:*", - "isbot": "catalog:" + "isbot": "^5.1.22", + "tiny-invariant": "^1.3.3", + "tiny-warning": "^1.0.3" }, "devDependencies": { - "@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:", + "@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", "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:" + "zod": "^3.24.2" }, "peerDependencies": { "react": ">=18.0.0 || >=19.0.0", diff --git a/packages/react-router/skills/compositions/router-query/SKILL.md b/packages/react-router/skills/compositions/router-query/SKILL.md index 4fdd74fc30..89fba76b54 100644 --- a/packages/react-router/skills/compositions/router-query/SKILL.md +++ b/packages/react-router/skills/compositions/router-query/SKILL.md @@ -1,15 +1,14 @@ --- -name: router-query +name: compositions/router-query description: >- Integrating TanStack Router with TanStack Query: queryClient - in router context, static queries and fire-and-forget queries in loaders, + in router context, ensureQueryData/prefetchQuery in loaders, useSuspenseQuery in components, defaultPreloadStaleTime: 0, setupRouterSsrQueryIntegration for SSR dehydration/hydration and streaming, per-request QueryClient isolation. -metadata: - type: composition - library: tanstack-router - library_version: '1.166.2' +type: composition +library: tanstack-router +library_version: '1.166.2' requires: - router-core - router-core/data-loading @@ -21,7 +20,7 @@ sources: # 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 requires familiarity with both TanStack Router and TanStack Query. Read [router-core](../../../../router-core/skills/router-core/SKILL.md) and [react-router](../../react-router/SKILL.md) first. This skill 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. @@ -182,9 +181,9 @@ export function createAppRouter() { } ``` -## Core Pattern: Static `query` in Loader + `useSuspenseQuery` in Component +## Core Pattern: `ensureQueryData` 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. +This is the recommended pattern. The loader ensures data is in the cache before render (no loading flash). The component subscribes to the cache for updates. ```tsx // src/routes/posts.tsx @@ -204,12 +203,9 @@ const postsQueryOptions = queryOptions({ 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', - }) + // ensureQueryData returns cached data if available, fetches if not in cache + // To also refetch stale data, pass revalidateIfStale: true + return context.queryClient.ensureQueryData(postsQueryOptions) }, component: PostsPage, }) @@ -249,10 +245,7 @@ const postQueryOptions = (postId: string) => export const Route = createFileRoute('/posts/$postId')({ loader: ({ context, params }) => { - return context.queryClient.query({ - ...postQueryOptions(params.postId), - staleTime: 'static', - }) + return context.queryClient.ensureQueryData(postQueryOptions(params.postId)) }, component: PostPage, }) @@ -265,23 +258,20 @@ function PostPage() { } ``` -## Streaming Pattern: Fire-and-Forget `query` (Not Awaited) +## Streaming Pattern: `prefetchQuery` (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: +For non-critical data, start the fetch without blocking navigation: ```tsx -import { noop, useQuery, useSuspenseQuery } from '@tanstack/react-query' +import { useQuery, useSuspenseQuery } from '@tanstack/react-query' export const Route = createFileRoute('/dashboard')({ loader: ({ context }) => { // Await critical data - const user = context.queryClient.query({ - ...userQueryOptions, - staleTime: 'static', - }) + const user = context.queryClient.ensureQueryData(userQueryOptions) - // Start non-critical query without awaiting — streams during SSR - void context.queryClient.query({ ...analyticsQueryOptions }).catch(noop) + // Start non-critical fetch without awaiting — streams during SSR + context.queryClient.prefetchQuery(analyticsQueryOptions) return user }, @@ -313,10 +303,7 @@ import { useRouter } from '@tanstack/react-router' export const Route = createFileRoute('/posts')({ loader: ({ context }) => - context.queryClient.query({ - ...postsQueryOptions, - staleTime: 'static', - }), + context.queryClient.ensureQueryData(postsQueryOptions), errorComponent: PostsErrorComponent, component: PostsPage, }) @@ -325,7 +312,7 @@ function PostsErrorComponent({ error, reset, }: { - error: unknown + error: Error reset: () => void }) { const router = useRouter() @@ -337,7 +324,7 @@ function PostsErrorComponent({ return (
-

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

+

{error.message}

) @@ -385,29 +372,24 @@ export function createAppRouter() { } ``` -### 3. MEDIUM: Awaiting a fire-and-forget query in a loader blocks rendering +### 3. MEDIUM: Awaiting `prefetchQuery` in 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. +`prefetchQuery` is designed to fire-and-forget. 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) + await context.queryClient.prefetchQuery(analyticsQueryOptions) } -// CORRECT — fire and forget for streaming, with handled rejection +// CORRECT — fire and forget for streaming loader: ({ context }) => { - void context.queryClient.query({ ...analyticsQueryOptions }).catch(noop) + context.queryClient.prefetchQuery(analyticsQueryOptions) } -// If you need to block (critical data), use a static query instead: +// If you need to block (critical data), use ensureQueryData instead: loader: ({ context }) => { - return context.queryClient.query({ - ...criticalQueryOptions, - staleTime: 'static', - }) + return context.queryClient.ensureQueryData(criticalQueryOptions) } ``` @@ -432,10 +414,10 @@ const rootRoute = createRootRouteWithContext<{ queryClient: QueryClient }>()({ TanStack Router has its own SWR cache (`staleTime`, `gcTime`, `defaultPreloadStaleTime`). When using Query as an external cache: - Set `defaultPreloadStaleTime: 0` to prevent Router's cache from short-circuiting Query's freshness logic -- Router's `staleTime`/`gcTime` still apply to the loader return value. For pure Query patterns, return nothing from the loader (just 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 +- Router's `staleTime`/`gcTime` still apply to the loader return value. For pure Query patterns, return nothing from the loader (just `ensureQueryData` for the side effect) and read data exclusively from `useSuspenseQuery` +- `router.invalidate()` re-runs loaders (which call `ensureQueryData`), but Query decides whether to actually refetch based on its own `staleTime` ## 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 +- [router-core/data-loading](../../../../router-core/skills/router-core/data-loading/SKILL.md) — built-in loader caching fundamentals +- [router-core/ssr](../../../../router-core/skills/router-core/ssr/SKILL.md) — SSR setup for dehydration/hydration diff --git a/packages/react-router/skills/lifecycle/migrate-from-react-router/SKILL.md b/packages/react-router/skills/lifecycle/migrate-from-react-router/SKILL.md index fdc4f4c4e5..c9f53358e6 100644 --- a/packages/react-router/skills/lifecycle/migrate-from-react-router/SKILL.md +++ b/packages/react-router/skills/lifecycle/migrate-from-react-router/SKILL.md @@ -1,14 +1,13 @@ --- -name: migrate-from-react-router +name: lifecycle/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' +type: lifecycle +library: tanstack-router +library_version: '1.166.2' requires: - router-core - react-router diff --git a/packages/react-router/skills/react-router/SKILL.md b/packages/react-router/skills/react-router/SKILL.md index f8df76df02..074f23e091 100644 --- a/packages/react-router/skills/react-router/SKILL.md +++ b/packages/react-router/skills/react-router/SKILL.md @@ -8,11 +8,10 @@ description: >- 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 +type: framework +library: tanstack-router +library_version: '1.166.2' +framework: react requires: - router-core sources: @@ -23,7 +22,9 @@ sources: # React Router (`@tanstack/react-router`) -This skill builds on router-core. Read `@tanstack/router-core#router-core` first for foundational concepts. +This skill builds on router-core. Read [router-core](../../../router-core/skills/router-core/SKILL.md) first for foundational concepts. + +This skill covers the React-specific bindings, components, hooks, and setup for TanStack Router. > **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. @@ -346,7 +347,7 @@ import { CatchBoundary } from '@tanstack/react-router' ; 'widget'} onCatch={(error) => console.error(error)} - errorComponent={({ error }) =>
{String(error)}
} + errorComponent={({ error }) =>
Error: {error.message}
} >
@@ -495,4 +496,4 @@ function App() { ## Cross-References -- `@tanstack/router-core#router-core` — all sub-skills for domain-specific patterns (search params, data loading, navigation, auth, SSR, etc.) +- [router-core/SKILL.md](../../../router-core/skills/router-core/SKILL.md) — all sub-skills for domain-specific patterns (search params, data loading, navigation, auth, SSR, etc.) diff --git a/packages/react-router/src/Asset.tsx b/packages/react-router/src/Asset.tsx index 04cbac9064..4de655fed8 100644 --- a/packages/react-router/src/Asset.tsx +++ b/packages/react-router/src/Asset.tsx @@ -1,54 +1,22 @@ -'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 } -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) { +export function Asset({ + tag, + attrs, + children, + nonce, +}: RouterManagedTag & { nonce?: string }): React.ReactElement | null { + switch (tag) { case 'title': return ( @@ -58,96 +26,31 @@ export function Asset( case 'meta': return <meta {...attrs} suppressHydrationWarning /> case 'link': + return <link {...attrs} nonce={nonce} suppressHydrationWarning /> + case 'style': return ( - <link + <style {...attrs} - precedence={ - attrs?.precedence ?? - (attrs?.rel === 'stylesheet' ? 'default' : undefined) - } + dangerouslySetInnerHTML={{ __html: children as string }} 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} preventScriptHoist={preventScriptHoist}> - {children} - </Script> - ) + return <Script attrs={attrs}>{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 !== '' && @@ -166,28 +69,47 @@ function Script({ } React.useEffect(() => { - if (dataScript) { - return - } + if (dataScript) 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 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 (existingScript) { + return } const script = document.createElement('script') - setScriptAttrs(script, attrs) + for (const [key, value] of Object.entries(attrs)) { + if ( + key !== 'suppressHydrationWarning' && + value !== undefined && + value !== false + ) { + script.setAttribute( + key, + typeof value === 'boolean' ? '' : String(value), + ) + } + } document.head.appendChild(script) - return () => script.remove() + return () => { + if (script.parentNode) { + script.parentNode.removeChild(script) + } + } } if (typeof children === 'string') { @@ -195,29 +117,48 @@ function Script({ typeof attrs?.type === 'string' ? attrs.type : 'text/javascript' const nonceAttr = typeof attrs?.nonce === 'string' ? attrs.nonce : undefined - for (const el of document.scripts) { - if (el.hasAttribute('src')) { - continue - } - + const existingScript = Array.from( + document.querySelectorAll('script:not([src])'), + ).find((el) => { + if (!(el instanceof HTMLScriptElement)) return false const sType = el.getAttribute('type') ?? 'text/javascript' const sNonce = el.getAttribute('nonce') ?? undefined - if ( + return ( el.textContent === children && sType === typeAttr && sNonce === nonceAttr - ) { - return - } + ) + }) + + if (existingScript) { + return } const script = document.createElement('script') script.textContent = children - setScriptAttrs(script, attrs) + + 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), + ) + } + } + } document.head.appendChild(script) - return () => script.remove() + return () => { + if (script.parentNode) { + script.parentNode.removeChild(script) + } + } } return undefined @@ -226,27 +167,14 @@ function 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 - /> - ) + return <script {...attrs} suppressHydrationWarning /> } if (typeof children === 'string') { return ( <script {...attrs} - dangerouslySetInnerHTML={innerHTML} + dangerouslySetInnerHTML={{ __html: children }} suppressHydrationWarning /> ) @@ -264,7 +192,7 @@ function Script({ <script {...attrs} suppressHydrationWarning - dangerouslySetInnerHTML={innerHTML} + dangerouslySetInnerHTML={{ __html: children }} /> ) } @@ -276,12 +204,11 @@ function Script({ if (attrs?.src) { return <script {...attrs} suppressHydrationWarning /> } - if (typeof children === 'string') { return ( <script {...attrs} - dangerouslySetInnerHTML={innerHTML} + dangerouslySetInnerHTML={{ __html: children }} suppressHydrationWarning /> ) diff --git a/packages/react-router/src/CatchBoundary.tsx b/packages/react-router/src/CatchBoundary.tsx index 1015a9e116..68197b2eb6 100644 --- a/packages/react-router/src/CatchBoundary.tsx +++ b/packages/react-router/src/CatchBoundary.tsx @@ -1,61 +1,83 @@ -'use client' - import * as React from 'react' -import { wrapInNonRouteComponentContext } from './nonRouteComponentContext' import type { ErrorRouteComponent } from './route' import type { ErrorInfo } from 'react' -export class CatchBoundary extends React.Component<{ - getResetKey: () => unknown +export function CatchBoundary(props: { + getResetKey: () => number | string children: React.ReactNode errorComponent?: ErrorRouteComponent - onCatch?: (error: unknown, errorInfo: ErrorInfo) => void + 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 }> { - // 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 } + 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() } - - return { resetKey } } - static getDerivedStateFromError(error: unknown) { - return { error: [error] } - } - reset = () => { - this.setState({ error: 0 }) - } - componentDidCatch(error: unknown, errorInfo: ErrorInfo) { - this.props.onCatch?.(error, errorInfo) + componentDidCatch(error: Error, errorInfo: ErrorInfo) { + if (this.props.onCatch) { + this.props.onCatch(error, errorInfo) + } } render() { - 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 + // 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() + }, + }) } } -export function ErrorComponent({ error }: { error: unknown }) { +export function ErrorComponent({ error }: { error: any }) { const [show, setShow] = React.useState(process.env.NODE_ENV !== 'production') return ( @@ -89,9 +111,7 @@ export function ErrorComponent({ error }: { error: unknown }) { overflow: 'auto', }} > - {(error as { message?: string } | null)?.message ? ( - <code>{(error as { message: string }).message}</code> - ) : null} + {error.message ? <code>{error.message}</code> : null} </pre> </div> ) : null} diff --git a/packages/react-router/src/ClientOnly.tsx b/packages/react-router/src/ClientOnly.tsx index 010a6d3117..931804b259 100644 --- a/packages/react-router/src/ClientOnly.tsx +++ b/packages/react-router/src/ClientOnly.tsx @@ -1,10 +1,5 @@ -'use client' - import React from 'react' -const getSnapshot = () => true -const getServerSnapshot = () => false - export interface ClientOnlyProps { /** * The children to render when the JS is loaded. @@ -34,7 +29,11 @@ export interface ClientOnlyProps { * ``` */ export function ClientOnly({ children, fallback = null }: ClientOnlyProps) { - return <React.Fragment>{useHydrated() ? children : fallback}</React.Fragment> + return useHydrated() ? ( + <React.Fragment>{children}</React.Fragment> + ) : ( + <React.Fragment>{fallback}</React.Fragment> + ) } /** @@ -56,24 +55,14 @@ export function ClientOnly({ children, fallback = null }: ClientOnlyProps) { * ``` * @returns True if the JS has been hydrated already, false otherwise. */ -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 { +export function useHydrated(): boolean { return React.useSyncExternalStore( subscribe, - getSnapshot, - enabled ? getServerSnapshot : getSnapshot, + () => true, + () => false, ) } function subscribe() { - return () => { - // noop - } + return () => {} } diff --git a/packages/react-router/src/HeadContent.dev.tsx b/packages/react-router/src/HeadContent.dev.tsx index 776f334318..3dfaa6613e 100644 --- a/packages/react-router/src/HeadContent.dev.tsx +++ b/packages/react-router/src/HeadContent.dev.tsx @@ -1,12 +1,10 @@ -'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' + +const DEV_STYLES_ATTR = 'data-tanstack-router-dev-styles' /** * Render route-managed head tags (title, meta, links, styles, head scripts). @@ -17,8 +15,8 @@ import type { HeadContentProps } from './HeadContent' * * @link https://tanstack.com/router/latest/docs/framework/react/guide/document-head-management */ -export function HeadContent(props: HeadContentProps) { - const tags = useTags(props.assetCrossOrigin) +export function HeadContent() { + const tags = useTags() const router = useRouter() const nonce = router.options.ssr?.nonce const hydrated = useHydrated() @@ -35,9 +33,7 @@ export function HeadContent(props: HeadContentProps) { // Filter out dev styles after hydration const filteredTags = hydrated - ? tags.filter( - (tag) => tag.tag !== 'link' || tag.attrs?.[DEV_STYLES_ATTR] !== true, - ) + ? tags.filter((tag) => !tag.attrs?.[DEV_STYLES_ATTR]) : tags return ( diff --git a/packages/react-router/src/HeadContent.tsx b/packages/react-router/src/HeadContent.tsx index 6a0c8188bc..e917fd9596 100644 --- a/packages/react-router/src/HeadContent.tsx +++ b/packages/react-router/src/HeadContent.tsx @@ -1,22 +1,15 @@ -'use client' - import * as React from 'react' import { Asset } from './Asset' import { useRouter } from './useRouter' import { useTags } from './headContentUtils' -import type { AssetCrossOriginConfig } from '@tanstack/router-core' - -export interface HeadContentProps { - assetCrossOrigin?: AssetCrossOriginConfig -} /** * Render route-managed head tags (title, meta, links, styles, head scripts). * 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(props: HeadContentProps) { - const tags = useTags(props.assetCrossOrigin) +export function HeadContent() { + const tags = useTags() const router = useRouter() const nonce = router.options.ssr?.nonce return ( diff --git a/packages/react-router/src/Match.tsx b/packages/react-router/src/Match.tsx index db1d341ec4..36b41ef124 100644 --- a/packages/react-router/src/Match.tsx +++ b/packages/react-router/src/Match.tsx @@ -1,86 +1,123 @@ -'use client' - import * as React from 'react' -import { useSelector } from '@tanstack/react-store' -import { isNotFound, rootRouteId } from '@tanstack/router-core' +import { useStore } from '@tanstack/react-store' +import invariant from 'tiny-invariant' +import warning from 'tiny-warning' +import { + createControlledPromise, + getLocationChangeInfo, + isNotFound, + isRedirect, + rootRouteId, +} from '@tanstack/router-core' import { isServer } from '@tanstack/router-core/isServer' import { CatchBoundary, ErrorComponent } from './CatchBoundary' 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, - AnyRouteMatch, + ParsedLocation, 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({ - routeId, + matchId, }: { - routeId: string + matchId: string }) { const router = useRouter() if (isServer ?? router.isServer) { - const match = router.stores.byRoute.get(routeId)!.get()! - return matchView(router, match) + const match = router.stores.activeMatchStoresById.get(matchId)?.state + invariant( + match, + `Could not find match for matchId "${matchId}". Please file an issue!`, + ) + + const routeId = match.routeId as string + const parentRouteId = (router.routesById[routeId] as AnyRoute).parentRoute + ?.id + + return ( + <MatchView + router={router} + matchId={matchId} + resetKey={router.stores.loadedAt.state} + matchState={{ + routeId, + ssr: match.ssr, + _displayPending: match._displayPending, + parentRouteId, + }} + /> + ) } - const matchStore = router.stores.getMatchStore(routeId) + // Subscribe directly to the match store from the pool. + // The matchId prop is stable for this component's lifetime (set by Outlet), + // and reconcileMatchPool reuses stores for the same matchId. // eslint-disable-next-line react-hooks/rules-of-hooks - const match = useSelector(matchStore)! - return matchView(router, match) + const matchStore = router.stores.activeMatchStoresById.get(matchId) + invariant( + matchStore, + `Could not find match for matchId "${matchId}". Please file an issue!`, + ) + // eslint-disable-next-line react-hooks/rules-of-hooks + const resetKey = useStore(router.stores.loadedAt, (loadedAt) => loadedAt) + // eslint-disable-next-line react-hooks/rules-of-hooks + const match = useStore(matchStore, (value) => value) + // eslint-disable-next-line react-hooks/rules-of-hooks + const matchState = React.useMemo(() => { + const routeId = match.routeId as string + const parentRouteId = (router.routesById[routeId] as AnyRoute).parentRoute + ?.id + + return { + routeId, + ssr: match.ssr, + _displayPending: match._displayPending, + parentRouteId: parentRouteId as string | undefined, + } satisfies MatchViewState + }, [match._displayPending, match.routeId, match.ssr, router.routesById]) + + return ( + <MatchView + router={router} + matchId={matchId} + resetKey={resetKey} + matchState={matchState} + /> + ) }) -function matchView(router: ReturnType<typeof useRouter>, match: AnyRouteMatch) { - const route: AnyRoute = router.routesById[match.routeId] +type MatchViewState = { + routeId: string + ssr: boolean | 'data-only' | undefined + _displayPending: boolean | undefined + parentRouteId: string | undefined +} - const pendingElement = renderPending(router, route) +function MatchView({ + router, + matchId, + resetKey, + matchState, +}: { + router: ReturnType<typeof useRouter> + matchId: string + resetKey: number + matchState: MatchViewState +}) { + const route: AnyRoute = router.routesById[matchState.routeId] + + const PendingComponent = + route.options.pendingComponent ?? router.options.defaultPendingComponent + + const pendingElement = PendingComponent ? <PendingComponent /> : null const routeErrorComponent = route.options.errorComponent ?? router.options.defaultErrorComponent @@ -88,112 +125,206 @@ function matchView(router: ReturnType<typeof useRouter>, match: AnyRouteMatch) { const routeOnCatch = route.options.onCatch ?? router.options.defaultOnCatch const routeNotFoundComponent = route.isRoot - ? // If it's the root route, use the _notFound option, with fallback to the notFoundRoute's component + ? // If it's the root route, use the globalNotFound option, with fallback to the notFoundRoute's component (route.options.notFoundComponent ?? router.options.notFoundRoute?.options.component) : route.options.notFoundComponent - 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) && + 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) && (route.options.wrapInSuspense ?? - pendingElement ?? + PendingComponent ?? ((route.options.errorComponent as any)?.preload || resolvedNoSsr)) + ? React.Suspense + : 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 ResolvedCatchBoundary = routeErrorComponent + ? CatchBoundary + : SafeFragment - const scrollRestoration = - (isServer ?? router.isServer) && - route.parentRoute?.id === rootRouteId && - router.options.scrollRestoration ? ( - <ScrollRestoration /> - ) : null + const ResolvedNotFoundBoundary = routeNotFoundComponent + ? CatchNotFound + : SafeFragment - const ShellComponent = - route.isRoot && (route.options as RootRouteOptions).shellComponent + 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 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> + 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> + {matchState.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.stores.location.state, + router.stores.resolvedLocation.state, + ), + }) + prevLocationRef.current = router.latestLocation + } + }} + /> ) } export const MatchInner = React.memo(function MatchInnerImpl({ - match, + matchId, }: { - match: AnyRouteMatch + matchId: string }): any { const router = useRouter() - const routeId = match.routeId + + if (isServer ?? router.isServer) { + const match = router.stores.activeMatchStoresById.get(matchId)?.state + invariant( + match, + `Could not find match for matchId "${matchId}". Please file an issue!`, + ) + + const routeId = match.routeId as string + const route = router.routesById[routeId] as AnyRoute + 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 + const Comp = route.options.component ?? router.options.defaultComponent + const out = Comp ? <Comp key={key} /> : <Outlet /> + + if (match._displayPending) { + throw router.getMatch(match.id)?._nonReactive.displayPendingPromise + } + + if (match._forcePending) { + throw router.getMatch(match.id)?._nonReactive.minPendingPromise + } + + if (match.status === 'pending') { + throw router.getMatch(match.id)?._nonReactive.loadPromise + } + + if (match.status === 'notFound') { + invariant(isNotFound(match.error), 'Expected a notFound error') + return renderRouteNotFound(router, route, match.error) + } + + if (match.status === 'redirected') { + invariant(isRedirect(match.error), 'Expected a redirect error') + throw router.getMatch(match.id)?._nonReactive.loadPromise + } + + if (match.status === 'error') { + const RouteErrorComponent = + (route.options.errorComponent ?? + router.options.defaultErrorComponent) || + ErrorComponent + return ( + <RouteErrorComponent + error={match.error as any} + reset={undefined as any} + info={{ + componentStack: '', + }} + /> + ) + } + + return out + } + + // eslint-disable-next-line react-hooks/rules-of-hooks + const matchStore = router.stores.activeMatchStoresById.get(matchId) + invariant( + matchStore, + `Could not find match for matchId "${matchId}". Please file an issue!`, + ) + // eslint-disable-next-line react-hooks/rules-of-hooks + const match = useStore(matchStore, (value) => value) + const routeId = match.routeId as string const route = router.routesById[routeId] as AnyRoute + // eslint-disable-next-line react-hooks/rules-of-hooks const key = React.useMemo(() => { const remountFn = - route.options.remountDeps ?? router.options.defaultRemountDeps + (router.routesById[routeId] as AnyRoute).options.remountDeps ?? + router.options.defaultRemountDeps const remountDeps = remountFn?.({ routeId, loaderDeps: match.loaderDeps, @@ -206,49 +337,91 @@ export const MatchInner = React.memo(function MatchInnerImpl({ match.loaderDeps, match._strictParams, match._strictSearch, - route.options.remountDeps, router.options.defaultRemountDeps, + router.routesById, ]) + + // eslint-disable-next-line react-hooks/rules-of-hooks const out = React.useMemo(() => { const Comp = route.options.component ?? router.options.defaultComponent - return Comp ? <Comp key={key} /> : <Outlet /> + if (Comp) { + return <Comp key={key} /> + } + return <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') { - 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 + // 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 (!(isServer ?? 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._tx) { - throw router._tx[5] - } - return renderPending(router, route) + throw router.getMatch(match.id)?._nonReactive.loadPromise } 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 (isServer ?? router.isServer) { const RouteErrorComponent = (route.options.errorComponent ?? router.options.defaultErrorComponent) || ErrorComponent - const errorElement = ( + return ( <RouteErrorComponent - error={match.error} + error={match.error as any} reset={undefined as any} info={{ componentStack: '', }} /> ) - return process.env.NODE_ENV !== 'production' - ? wrapInNonRouteComponentContext(errorElement, 'errorComponent') - : errorElement } + throw match.error } @@ -262,65 +435,63 @@ 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() { - 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.`, - ) - } - } - const router = useRouter() - const routeId = React.useContext(matchContext)! + const matchId = React.useContext(matchContext) - let parentGlobalNotFound: boolean - let parentNotFoundError: unknown - let childRouteId: string | undefined + let routeId: string | undefined + let parentGlobalNotFound = false + let childMatchId: 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 + const matches = router.stores.activeMatchesSnapshot.state + const parentIndex = matchId + ? matches.findIndex((match) => match.id === matchId) + : -1 + const parentMatch = parentIndex >= 0 ? matches[parentIndex] : undefined + routeId = parentMatch?.routeId as string | undefined + parentGlobalNotFound = parentMatch?.globalNotFound ?? false + childMatchId = + parentIndex >= 0 ? (matches[parentIndex + 1]?.id as string) : undefined } else { - const parentMatchStore = router.stores.getMatchStore(routeId) + // Subscribe directly to the match store from the pool instead of + // the two-level byId → matchStore pattern. + const parentMatchStore = matchId + ? router.stores.activeMatchStoresById.get(matchId) + : undefined // eslint-disable-next-line react-hooks/rules-of-hooks - ;[parentGlobalNotFound, parentNotFoundError] = useSelector( - parentMatchStore, - (match): OutletMatchSelection => [!!match!._notFound, match!.error], - { compare: outletMatchSelectionEqual }, - ) + ;[routeId, parentGlobalNotFound] = useStore(parentMatchStore, (match) => [ + match?.routeId as string | undefined, + match?.globalNotFound ?? false, + ]) // eslint-disable-next-line react-hooks/rules-of-hooks - childRouteId = useSelector(router.stores.ids, (ids) => { - return ids[ids.indexOf(routeId) + 1] + childMatchId = useStore(router.stores.matchesId, (ids) => { + const index = ids.findIndex((id) => id === matchId) + return ids[index + 1] }) } + const route = routeId ? router.routesById[routeId] : undefined + + const pendingElement = router.options.defaultPendingComponent ? ( + <router.options.defaultPendingComponent /> + ) : null + if (parentGlobalNotFound) { - return renderRouteNotFound( - router, - router.routesById[routeId], - parentNotFoundError, - ) + invariant(route, 'Could not resolve route for Outlet render') + return renderRouteNotFound(router, route, undefined) } - if (!childRouteId) { + if (!childMatchId) { return null } - const nextMatch = <Match routeId={childRouteId} /> + const nextMatch = <Match matchId={childMatchId} /> if (routeId === rootRouteId) { return ( - <React.Suspense fallback={renderPending(router)}> - {nextMatch} - </React.Suspense> + <React.Suspense fallback={pendingElement}>{nextMatch}</React.Suspense> ) } diff --git a/packages/react-router/src/Matches.tsx b/packages/react-router/src/Matches.tsx index a20c862b23..953a49401b 100644 --- a/packages/react-router/src/Matches.tsx +++ b/packages/react-router/src/Matches.tsx @@ -1,16 +1,14 @@ -'use client' - import * as React from 'react' -import { useSelector } from '@tanstack/react-store' -import { rootRouteId } from '@tanstack/router-core' +import warning from 'tiny-warning' +import { useStore } from '@tanstack/react-store' +import { replaceEqualDeep, rootRouteId } from '@tanstack/router-core' import { isServer } from '@tanstack/router-core/isServer' -import { CatchBoundary } from './CatchBoundary' +import { CatchBoundary, ErrorComponent } from './CatchBoundary' import { useRouter } from './useRouter' -import { useStructuralSharing } from './useMatch' -import { useLayoutEffect } from './utils' -import { Transitioner, settleOwner } from './Transitioner' +import { Transitioner } from './Transitioner' import { matchContext } from './matchContext' -import { Match, renderPending } from './Match' +import { Match } from './Match' +import { SafeFragment } from './SafeFragment' import type { StructuralSharingOption, ValidateSelected, @@ -25,8 +23,11 @@ import type { MakeRouteMatchUnion, MaskOptions, MatchRouteOptions, + NoInfer, RegisteredRouter, + ResolveRelativePath, ResolveRoute, + RouteByPath, ToSubOptionsProps, } from '@tanstack/router-core' @@ -48,28 +49,23 @@ export function Matches() { const router = useRouter() const rootRoute: AnyRoute = router.routesById[rootRouteId] - const pendingElement = renderPending(router, rootRoute) + 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 = + (isServer ?? router.isServer) || + (typeof document !== 'undefined' && router.ssr) + ? SafeFragment + : React.Suspense const inner = ( - <> - {!(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> - )} - </> + <ResolvedSuspense fallback={pendingElement}> + {!(isServer ?? router.isServer) && <Transitioner />} + <MatchesInner /> + </ResolvedSuspense> ) return router.options.InnerWrap ? ( @@ -81,44 +77,42 @@ export function Matches() { function MatchesInner() { const router = useRouter() - 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 _isServer = isServer ?? router.isServer + const matchId = _isServer + ? router.stores.firstMatchId.state + : // eslint-disable-next-line react-hooks/rules-of-hooks + useStore(router.stores.firstMatchId, (id) => id) + const resetKey = _isServer + ? router.stores.loadedAt.state + : // eslint-disable-next-line react-hooks/rules-of-hooks + useStore(router.stores.loadedAt, (loadedAt) => 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 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> + return ( + <matchContext.Provider value={matchId}> + {router.options.disableGlobalCatchBoundary ? ( + matchComponent + ) : ( + <CatchBoundary + getResetKey={() => resetKey} + errorComponent={ErrorComponent} + onCatch={ + process.env.NODE_ENV !== 'production' + ? (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()) + } + : undefined + } + > + {matchComponent} + </CatchBoundary> + )} + </matchContext.Provider> ) } @@ -141,40 +135,30 @@ 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 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. + * Useful for conditional rendering and active UI states. * * @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>(): < - 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']> { +export function useMatchRoute<TRouter extends AnyRouter = RegisteredRouter>() { const router = useRouter() - if (isServer ?? router.isServer) { - return (opts) => { - const { pending, caseSensitive, fuzzy, includeSearch, ...rest } = opts - return router.matchRoute(rest as any, { - pending, - caseSensitive, - fuzzy, - includeSearch, - }) - } + if (!(isServer ?? router.isServer)) { + // eslint-disable-next-line react-hooks/rules-of-hooks + useStore(router.stores.matchRouteReactivity, (d) => d) } - // eslint-disable-next-line react-hooks/rules-of-hooks return React.useCallback( - (opts) => { + < + 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 { pending, caseSensitive, fuzzy, includeSearch, ...rest } = opts return router.matchRoute(rest as any, { @@ -184,15 +168,7 @@ export function useMatchRoute<TRouter extends AnyRouter = RegisteredRouter>(): < includeSearch, }) }, - [ - 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), - ], + [router], ) } @@ -206,9 +182,10 @@ 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?: Expand< - ResolveRoute<TRouter, TFrom, TTo>['types']['allParams'] - >, + params?: RouteByPath< + TRouter['routeTree'], + ResolveRelativePath<TFrom, NoInfer<TTo>> + >['types']['allParams'], ) => React.ReactNode) | React.ReactNode } @@ -261,9 +238,13 @@ export function useMatches< StructuralSharingOption<TRouter, TSelected, TStructuralSharing>, ): UseMatchesResult<TRouter, TSelected> { const router = useRouter<TRouter>() + const previousResult = + React.useRef<ValidateSelected<TRouter, TSelected, TStructuralSharing>>( + undefined, + ) if (isServer ?? router.isServer) { - const matches = router.stores.matches.get() as Array< + const matches = router.stores.activeMatchesSnapshot.state as Array< MakeRouteMatchUnion<TRouter> > return (opts?.select ? opts.select(matches) : matches) as UseMatchesResult< @@ -272,17 +253,37 @@ export function useMatches< > } - // 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> + // eslint-disable-next-line react-hooks/rules-of-hooks + return useStore(router.stores.activeMatchesSnapshot, (matches) => { + const selected = opts?.select + ? opts.select(matches as Array<MakeRouteMatchUnion<TRouter>>) + : (matches as any) + + if (opts?.structuralSharing ?? router.options.defaultStructuralSharing) { + const shared = replaceEqualDeep(previousResult.current, selected) + previousResult.current = shared + return shared + } + + return selected + }) as UseMatchesResult<TRouter, TSelected> } /** - * Read the presented route matches above the current match, or select a - * derived value from them. + * 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 */ export function useParentMatches< TRouter extends AnyRouter = RegisteredRouter, @@ -292,13 +293,13 @@ export function useParentMatches< opts?: UseMatchesBaseOptions<TRouter, TSelected, TStructuralSharing> & StructuralSharingOption<TRouter, TSelected, TStructuralSharing>, ): UseMatchesResult<TRouter, TSelected> { - const contextRouteId = React.useContext(matchContext) + const contextMatchId = React.useContext(matchContext) return useMatches({ select: (matches: Array<MakeRouteMatchUnion<TRouter>>) => { matches = matches.slice( 0, - matches.findIndex((d) => d.routeId === contextRouteId), + matches.findIndex((d) => d.id === contextMatchId), ) return opts?.select ? opts.select(matches) : matches }, @@ -307,8 +308,8 @@ export function useParentMatches< } /** - * Read the presented route matches below the current match, or select a - * derived value from them. + * Read the array of active route matches that are children of the current + * match (or selected parent) in the match tree. */ export function useChildMatches< TRouter extends AnyRouter = RegisteredRouter, @@ -318,12 +319,12 @@ export function useChildMatches< opts?: UseMatchesBaseOptions<TRouter, TSelected, TStructuralSharing> & StructuralSharingOption<TRouter, TSelected, TStructuralSharing>, ): UseMatchesResult<TRouter, TSelected> { - const contextRouteId = React.useContext(matchContext) + const contextMatchId = React.useContext(matchContext) return useMatches({ select: (matches: Array<MakeRouteMatchUnion<TRouter>>) => { matches = matches.slice( - matches.findIndex((d) => d.routeId === contextRouteId) + 1, + matches.findIndex((d) => d.id === contextMatchId) + 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 e61cdf1b8a..d340feb4da 100644 --- a/packages/react-router/src/RouterProvider.tsx +++ b/packages/react-router/src/RouterProvider.tsx @@ -1,7 +1,4 @@ -'use client' - import * as React from 'react' -import { hasKeys } from '@tanstack/router-core' import { Matches } from './Matches' import { routerContext } from './routerContext' import type { @@ -24,7 +21,7 @@ export function RouterContextProvider< }: RouterProps<TRouter, TDehydrated> & { children: React.ReactNode }) { - if (hasKeys(rest)) { + if (Object.keys(rest).length > 0) { // Allow the router to update options on the router instance router.update({ ...router.options, @@ -50,11 +47,11 @@ export function RouterContextProvider< } /** - * Renders the current match presentation and provides the router to the React - * tree via context. + * Top-level component that renders the active route matches and provides the + * router to the React tree via context. * - * Accepts mutable router options via props. Configure initialization-only - * options with `createRouter`. + * Accepts the same options as `createRouter` via props to update the router + * instance after creation. * * @link https://tanstack.com/router/latest/docs/framework/react/api/router/createRouterFunction */ @@ -80,7 +77,7 @@ export type RouterProps< TRouter['history'], TDehydrated >, - 'context' | 'pathParamsAllowedCharacters' + 'context' > & { router: TRouter context?: Partial< diff --git a/packages/react-router/src/SafeFragment.tsx b/packages/react-router/src/SafeFragment.tsx new file mode 100644 index 0000000000..72a95bac01 --- /dev/null +++ b/packages/react-router/src/SafeFragment.tsx @@ -0,0 +1,5 @@ +import * as React from 'react' + +export function SafeFragment(props: any) { + return <>{props.children}</> +} diff --git a/packages/react-router/src/Scripts.tsx b/packages/react-router/src/Scripts.tsx index 56afe0a443..d2110b68be 100644 --- a/packages/react-router/src/Scripts.tsx +++ b/packages/react-router/src/Scripts.tsx @@ -1,71 +1,106 @@ -import { useSelector } from '@tanstack/react-store' -import { - composeSsrBodyScripts, - deepEqual, - getSsrBodyScriptParts, -} from '@tanstack/router-core' +import { useStore } from '@tanstack/react-store' +import { deepEqual } from '@tanstack/router-core' import { isServer } from '@tanstack/router-core/isServer' import { Asset } from './Asset' 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. - * During streaming SSR, `<Scripts>` marks where late hydration scripts may - * begin to be inserted. + * Should be placed near the end of the document body. */ export const Scripts = () => { const router = useRouter() const nonce = router.options.ssr?.nonce - 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 - } + const getAssetScripts = (matches: Array<any>) => { + const assetScripts: Array<RouterManagedTag> = [] + const manifest = router.ssr?.manifest + + if (!manifest) { + return [] } - return parts + + 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 } - const getScripts = (matches: Array<any>) => { - return composeSsrBodyScripts(getParts(matches)) - } + const getScripts = (matches: Array<any>): Array<RouterManagedTag> => + ( + matches + .map((match) => match.scripts!) + .flat(1) + .filter(Boolean) as Array<RouterManagedTag> + ).map( + ({ children, ...script }) => + ({ + tag: 'script', + attrs: { + ...script, + suppressHydrationWarning: true, + nonce, + }, + children, + }) satisfies RouterManagedTag, + ) if (isServer ?? router.isServer) { - const activeMatches = router.stores.matches.get() - return renderScripts( - composeSsrBodyScripts( - getParts(activeMatches), - router.serverSsr?.takeInitialHydrationScriptTags(), - ), + const assetScripts = getAssetScripts( + router.stores.activeMatchesSnapshot.state, ) + const scripts = getScripts(router.stores.activeMatchesSnapshot.state) + return renderScripts(router, scripts, assetScripts) } // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static - const scripts = useSelector(router.stores.matches, getScripts, { - compare: deepEqual, - }) + const assetScripts = useStore( + router.stores.activeMatchesSnapshot, + getAssetScripts, + deepEqual, + ) + // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static + const scripts = useStore( + router.stores.activeMatchesSnapshot, + getScripts, + deepEqual, + ) - return renderScripts(scripts) + return renderScripts(router, scripts, assetScripts) } -function renderScripts(scripts: Array<ScriptRenderAsset>) { +function renderScripts( + router: ReturnType<typeof useRouter>, + scripts: Array<RouterManagedTag>, + assetScripts: Array<RouterManagedTag>, +) { + let serverBufferedScript: RouterManagedTag | undefined = undefined + + if (router.serverSsr) { + serverBufferedScript = router.serverSsr.takeBufferedScripts() + } + + const allScripts = [...scripts, ...assetScripts] as Array<RouterManagedTag> + + if (serverBufferedScript) { + allScripts.unshift(serverBufferedScript) + } + return ( <> - {scripts.map((asset, i) => ( + {allScripts.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 d36210db41..55591c92ce 100644 --- a/packages/react-router/src/ScrollRestoration.tsx +++ b/packages/react-router/src/ScrollRestoration.tsx @@ -1,5 +1,7 @@ import { - getElementScrollRestorationEntry, + defaultGetScrollRestorationKey, + getCssSelector, + scrollRestorationCache, setupScrollRestoration, } from '@tanstack/router-core' import { useRouter } from './useRouter' @@ -45,5 +47,23 @@ export function useElementScrollRestoration( ): ScrollRestorationEntry | undefined { useScrollRestoration() - return getElementScrollRestorationEntry(useRouter(), options) + 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] } diff --git a/packages/react-router/src/Transitioner.tsx b/packages/react-router/src/Transitioner.tsx index ddf8afea2e..d84d22a6ba 100644 --- a/packages/react-router/src/Transitioner.tsx +++ b/packages/react-router/src/Transitioner.tsx @@ -1,56 +1,48 @@ -'use client' - import * as React from 'react' -import { getLocationChangeInfo, trimPathRight } from '@tanstack/router-core' -import { useLayoutEffect } from './utils' +import { batch, useStore } from '@tanstack/react-store' +import { + getLocationChangeInfo, + handleHashScroll, + trimPathRight, +} from '@tanstack/router-core' +import { useLayoutEffect, usePrevious } from './utils' import { useRouter } from './useRouter' -import type { AnyRouter } from '@tanstack/router-core' -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>> -}) { +export function Transitioner() { const router = useRouter() - 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 mountLoadForRouter = React.useRef({ router, mounted: false }) - router.startTransition = (fn, expected) => - new Promise((resolve) => { - settleOwner(acknowledgement, false) - acknowledgement.push(expected, resolve) - t(router) - React.startTransition(fn) + const [isTransitioning, setIsTransitioning] = React.useState(false) + // Track pending state changes + const isLoading = useStore(router.stores.isLoading, (value) => value) + const hasPendingMatches = useStore( + router.stores.hasPendingMatches, + (value) => value, + ) + + 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) }) + } - // Subscribe before canonicalizing so the initial URL has exactly one load. - useLayoutEffect(() => { + // Subscribe to location changes + // and try to load the new location + React.useEffect(() => { 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: location.pathname, + to: router.latestLocation.pathname, search: true, params: true, hash: true, @@ -59,41 +51,92 @@ export function Transitioner({ }) // Check if the current URL matches the canonical form. - // Compare publicHref (browser-facing URL) consistently with server - // canonicalization. + // Compare publicHref (browser-facing URL) for consistency with + // the server-side redirect check in router.beforeLoad. if ( - trimPathRight(location.publicHref) !== + trimPathRight(router.latestLocation.publicHref) !== trimPathRight(nextLocation.publicHref) ) { - router.commitLocation({ - ...nextLocation, - replace: true, - ignoreBlocker: true, - }) - return unsub + router.commitLocation({ ...nextLocation, replace: true }) } - 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() } - - 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.stores.location.state, + router.stores.resolvedLocation.state, + ), + }) + } + }, [previousIsLoading, router, isLoading]) + + useLayoutEffect(() => { + // emit onBeforeRouteMount + if (previousIsPagePending && !isPagePending) { + router.emit({ + type: 'onBeforeRouteMount', + ...getLocationChangeInfo( + router.stores.location.state, + router.stores.resolvedLocation.state, + ), + }) + } + }, [isPagePending, previousIsPagePending, router]) + + useLayoutEffect(() => { + if (previousIsAnyPending && !isAnyPending) { + const changeInfo = getLocationChangeInfo( + router.stores.location.state, + router.stores.resolvedLocation.state, + ) + router.emit({ + type: 'onResolved', + ...changeInfo, + }) + + batch(() => { + router.stores.status.setState(() => 'idle') + router.stores.resolvedLocation.setState( + () => router.stores.location.state, + ) + }) + + if (changeInfo.hrefChanged) { + handleHashScroll(router) + } + } + }, [isAnyPending, previousIsAnyPending, router]) + return null } diff --git a/packages/react-router/src/fileRoute.ts b/packages/react-router/src/fileRoute.ts index f4d8c9b967..c38c24485f 100644 --- a/packages/react-router/src/fileRoute.ts +++ b/packages/react-router/src/fileRoute.ts @@ -1,3 +1,4 @@ +import warning from 'tiny-warning' import { createRoute } from './route' import { useMatch } from './useMatch' @@ -54,14 +55,16 @@ export function createFileRoute< 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'] { - return (options) => { - const route = createRoute(options as any) - ;(route as any).isRoot = false - return route as any + if (typeof path === 'object') { + return new FileRoute<TFilePath, TParentRoute, TId, TPath, TFullPath>(path, { + silent: true, + }).createRoute(path) as any } + return new FileRoute<TFilePath, TParentRoute, TId, TPath, TFullPath>(path, { + silent: true, + }).createRoute } /** @@ -148,11 +151,10 @@ export class FileRoute< THandlers > => { 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.', - ) - } + warning( + this.silent, + '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 @@ -185,8 +187,9 @@ export function FileRouteLoader< >, ) => TLoaderFn { 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`, + 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`, ) } return (loaderFn) => loaderFn as any @@ -218,7 +221,11 @@ export class LazyRoute<TRoute extends AnyRoute> { } useMatch: UseMatchRoute<TRoute['id']> = (opts) => { - return useMatch({ ...opts, from: this.options.id } as any) as any + return useMatch({ + select: opts?.select, + from: this.options.id, + structuralSharing: opts?.structuralSharing, + } as any) as any } useRouteContext: UseRouteContextRoute<TRoute['id']> = (opts) => { @@ -226,11 +233,21 @@ export class LazyRoute<TRoute extends AnyRoute> { } useSearch: UseSearchRoute<TRoute['id']> = (opts) => { - return useSearch({ ...opts, from: this.options.id } as any) + // 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 } useParams: UseParamsRoute<TRoute['id']> = (opts) => { - return useParams({ ...opts, from: this.options.id } as any) + // 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 } useLoaderDeps: UseLoaderDepsRoute<TRoute['id']> = (opts) => { diff --git a/packages/react-router/src/headContentUtils.tsx b/packages/react-router/src/headContentUtils.tsx index d517e0e453..5340d8aa19 100644 --- a/packages/react-router/src/headContentUtils.tsx +++ b/packages/react-router/src/headContentUtils.tsx @@ -1,32 +1,16 @@ import * as React from 'react' -import { useSelector } from '@tanstack/react-store' -import { - _getAssetMatches, - appendUniqueUserTags, - deepEqual, - escapeHtml, - getAssetCrossOrigin, - getScriptPreloadAttrs, - resolveManifestCssLink, -} from '@tanstack/router-core' +import { useStore } from '@tanstack/react-store' +import { deepEqual, escapeHtml } from '@tanstack/router-core' import { isServer } from '@tanstack/router-core/isServer' import { useRouter } from './useRouter' -import type { - AnyRouteMatch, - AssetCrossOriginConfig, - RouterManagedTag, -} from '@tanstack/router-core' +import type { RouterManagedTag } from '@tanstack/router-core' function buildTagsFromMatches( router: ReturnType<typeof useRouter>, nonce: string | undefined, - matches: Array<AnyRouteMatch>, - assetCrossOrigin?: AssetCrossOriginConfig, + matches: Array<any>, ): Array<RouterManagedTag> { - matches = _getAssetMatches(matches) - const routeMeta = matches - .map((match) => match.meta) - .filter((meta) => meta !== undefined) + const routeMeta = matches.map((match) => match.meta!).filter(Boolean) const resultMeta: Array<RouterManagedTag> = [] const metaByAttribute: Record<string, true> = {} @@ -94,8 +78,9 @@ function buildTagsFromMatches( resultMeta.reverse() const constructedLinks = matches - .flatMap((match) => match.links ?? []) - .filter((link) => link !== undefined) + .map((match) => match.links!) + .filter(Boolean) + .flat(1) .map((link) => ({ tag: 'link', attrs: { @@ -105,94 +90,87 @@ function buildTagsFromMatches( })) 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({ + const assetLinks = matches + .map((match) => manifest?.routes[match.routeId]?.assets ?? []) + .filter(Boolean) + .flat(1) + .filter((asset) => asset.tag === 'link') + .map( + (asset) => + ({ tag: 'link', attrs: { - rel: 'stylesheet', - ...resolvedLink, - crossOrigin: - getAssetCrossOrigin(assetCrossOrigin, 'stylesheet') ?? - resolvedLink.crossOrigin, + ...asset.attrs, suppressHydrationWarning: true, nonce, }, - }) - }) - }) - - if (manifest.inlineStyle) { - manifestCssTags.push({ - tag: 'style', - attrs: { - ...manifest.inlineStyle.attrs, - nonce, - }, - children: manifest.inlineStyle.children, - inlineCss: true, - }) - } - } + }) satisfies RouterManagedTag, + ) 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, - }, - }) - }) - }) - } + 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, + }, + }) + }), + ) - 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 styles = ( + matches + .map((match) => match.styles!) + .flat(1) + .filter(Boolean) as Array<RouterManagedTag> + ).map(({ children, ...attrs }) => ({ + tag: 'style', + attrs: { + ...attrs, + nonce, + }, + children, + })) - 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 headScripts = ( + matches + .map((match) => match.headScripts!) + .flat(1) + .filter(Boolean) as Array<RouterManagedTag> + ).map(({ children, ...script }) => ({ + tag: 'script', + attrs: { + ...script, + nonce, + }, + children, + })) - const tags: Array<RouterManagedTag> = [] - appendUniqueUserTags(tags, resultMeta) - tags.push(...preloadLinks) - appendUniqueUserTags(tags, constructedLinks) - tags.push(...manifestCssTags) - appendUniqueUserTags(tags, styles) - appendUniqueUserTags(tags, headScripts) - return tags + return uniqBy( + [ + ...resultMeta, + ...preloadLinks, + ...constructedLinks, + ...assetLinks, + ...styles, + ...headScripts, + ] as Array<RouterManagedTag>, + (d) => JSON.stringify(d), + ) } /** - * Build the head/link/meta/script tags from the renderable presented prefix. + * Build the list of head/link/meta/script tags to render for active matches. * Used internally by `HeadContent`. */ -export const useTags = (assetCrossOrigin?: AssetCrossOriginConfig) => { +export const useTags = () => { const router = useRouter() const nonce = router.options.ssr?.nonce @@ -200,17 +178,223 @@ export const useTags = (assetCrossOrigin?: AssetCrossOriginConfig) => { return buildTagsFromMatches( router, nonce, - router.stores.matches.get(), - assetCrossOrigin, + router.stores.activeMatchesSnapshot.state, ) } // 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], + const routeMeta = useStore( + router.stores.activeMatchesSnapshot, + (matches) => { + return matches.map((match) => match.meta!).filter(Boolean) + }, + deepEqual, ) + // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static - return useSelector(router.stores.matches, selectTags, { compare: deepEqual }) + 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 if ('script:ld+json' in m) { + // Handle JSON-LD structured data + // Content is HTML-escaped to prevent XSS when injected via dangerouslySetInnerHTML + 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() + + return resultMeta + }, [routeMeta, nonce]) + + // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static + const links = useStore( + router.stores.activeMatchesSnapshot, + (matches) => { + const constructed = 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 = 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] + }, + deepEqual, + ) + + // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static + const preloadLinks = useStore( + router.stores.activeMatchesSnapshot, + (matches) => { + const preloadLinks: Array<RouterManagedTag> = [] + + 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 + }, + deepEqual, + ) + + // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static + const styles = useStore( + router.stores.activeMatchesSnapshot, + (matches) => + ( + matches + .map((match) => match.styles!) + .flat(1) + .filter(Boolean) as Array<RouterManagedTag> + ).map(({ children, ...attrs }) => ({ + tag: 'style', + attrs: { + ...attrs, + nonce, + }, + children, + })), + deepEqual, + ) + + // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static + const headScripts: Array<RouterManagedTag> = useStore( + router.stores.activeMatchesSnapshot, + (matches) => + ( + matches + .map((match) => match.headScripts!) + .flat(1) + .filter(Boolean) as Array<RouterManagedTag> + ).map(({ children, ...script }) => ({ + tag: 'script', + attrs: { + ...script, + nonce, + }, + children, + })), + deepEqual, + ) + + return uniqBy( + [ + ...meta, + ...preloadLinks, + ...links, + ...styles, + ...headScripts, + ] as Array<RouterManagedTag>, + (d) => { + return JSON.stringify(d) + }, + ) +} + +export 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 + }) } diff --git a/packages/react-router/src/index.dev.tsx b/packages/react-router/src/index.dev.tsx index dde6fd2eea..e7c962f3d6 100644 --- a/packages/react-router/src/index.dev.tsx +++ b/packages/react-router/src/index.dev.tsx @@ -1,5 +1,3 @@ -'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 diff --git a/packages/react-router/src/index.rsc.ts b/packages/react-router/src/index.rsc.ts deleted file mode 100644 index d5baf7e952..0000000000 --- a/packages/react-router/src/index.rsc.ts +++ /dev/null @@ -1,11 +0,0 @@ -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 23ebf57938..09b93ad193 100644 --- a/packages/react-router/src/index.tsx +++ b/packages/react-router/src/index.tsx @@ -1,5 +1,3 @@ -'use client' - export { defer, isMatch, @@ -17,6 +15,8 @@ export { stringifySearchWith, functionalUpdate, replaceEqualDeep, + isPlainObject, + isPlainArray, deepEqual, createControlledPromise, retainSearchParams, @@ -71,7 +71,6 @@ export type { ResolveRouteContext, SearchSerializer, SearchParser, - SearchMiddleware, TrailingSlashOption, Manifest, RouterManagedTag, @@ -127,7 +126,6 @@ export type { AwaitOptions } from './awaited' export { CatchBoundary, ErrorComponent } from './CatchBoundary' export { ClientOnly, useHydrated } from './ClientOnly' -export { reactUse, useLayoutEffect } from './utils' export { FileRoute, @@ -202,6 +200,7 @@ export type { RegisteredRouter, RouterContextOptions, ControllablePromise, + InjectedHtmlEntry, RouterOptions, RouterState, ListenerFn, @@ -327,9 +326,6 @@ export type { InferSelected, ValidateUseSearchResult, ValidateUseParamsResult, - SerializerExtensions, - RegisteredSerializableInput, - Serializable, } from '@tanstack/router-core' export { ScriptOnce } from './ScriptOnce' diff --git a/packages/react-router/src/lazyRouteComponent.tsx b/packages/react-router/src/lazyRouteComponent.tsx index a7b58c4499..b4fe8703c5 100644 --- a/packages/react-router/src/lazyRouteComponent.tsx +++ b/packages/react-router/src/lazyRouteComponent.tsx @@ -1,6 +1,5 @@ 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' @@ -25,48 +24,58 @@ 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) => { - // Resolved clients have no preload work; SSR can reuse the import. - if (!(isServer ?? typeof window === 'undefined')) { - loadPromise = undefined - ;(lazyComp as any).preload = undefined - } + loadPromise = 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) { - // 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(() => {}) - } - } + // Otherwise, just throw the error throw error } diff --git a/packages/react-router/src/link.tsx b/packages/react-router/src/link.tsx index ce6a7ed9d1..3f0dc83a22 100644 --- a/packages/react-router/src/link.tsx +++ b/packages/react-router/src/link.tsx @@ -1,24 +1,24 @@ -'use client' - import * as React from 'react' +import { useStore } from '@tanstack/react-store' +import { flushSync } from 'react-dom' import { deepEqual, + exactPathTest, functionalUpdate, - getUrlScheme, isDangerousProtocol, preloadWarning, removeTrailingSlash, } from '@tanstack/router-core' import { isServer } from '@tanstack/router-core/isServer' import { useRouter } from './useRouter' -import { createLinkScope, matchContext } from './matchContext' +import { useForwardedRef, useIntersectionObserver } from './utils' + +import { useHydrated } from './ClientOnly' import type { - ActiveOptions, AnyRouter, Constrain, LinkOptions, - ParsedLocation, RegisteredRouter, RoutePaths, } from '@tanstack/router-core' @@ -28,97 +28,6 @@ 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. * @@ -140,38 +49,51 @@ 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 innerRef = useForwardedRef(forwardedRef) + + // Determine if we're on the server - used for tree-shaking client-only code + const _isServer = isServer ?? router.isServer + + const { + // custom props + activeProps, + inactiveProps, + activeOptions, + to, + preload: userPreload, + preloadDelay: userPreloadDelay, + hashScrollIntoView, + replace, + startTransition, + resetScroll, + viewTransition, + // element props + children, + target, + disabled, + style, + className, + 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 // ========================================================================== // SERVER EARLY RETURN @@ -184,11 +106,259 @@ export function useLinkProps< // // 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) + if (_isServer) { + const safeInternal = isSafeInternal(to) + + // If `to` is obviously an absolute URL, treat as external and avoid + // computing the internal location via `buildLocation`. + if ( + typeof to === 'string' && + !safeInternal && + // Quick checks to avoid `new URL` in common internal-like cases + to.indexOf(':') > -1 + ) { + try { + new URL(to) + if (isDangerousProtocol(to, router.protocolAllowlist)) { + if (process.env.NODE_ENV !== 'production') { + console.warn(`Blocked Link with dangerous protocol: ${to}`) + } + return { + ...propsSafeToSpread, + ref: innerRef as React.ComponentPropsWithRef<'a'>['ref'], + href: undefined, + ...(children && { children }), + ...(target && { target }), + ...(disabled && { disabled }), + ...(style && { style }), + ...(className && { className }), + } + } + + return { + ...propsSafeToSpread, + ref: innerRef as React.ComponentPropsWithRef<'a'>['ref'], + href: to, + ...(children && { children }), + ...(target && { target }), + ...(disabled && { disabled }), + ...(style && { style }), + ...(className && { className }), + } + } catch { + // Not an absolute URL + } + } + + const next = router.buildLocation({ ...options, from: options.from } as any) + + // Use publicHref - it contains the correct href for display + // When a rewrite changes the origin, publicHref is the full URL + // Otherwise it's the origin-stripped path + // This avoids constructing URL objects in the hot path + const hrefOptionPublicHref = next.maskedLocation + ? next.maskedLocation.publicHref + : next.publicHref + const hrefOptionExternal = next.maskedLocation + ? next.maskedLocation.external + : next.external + const hrefOption = getHrefOption( + hrefOptionPublicHref, + hrefOptionExternal, + router.history, + disabled, + ) + + const externalLink = (() => { + if (hrefOption?.external) { + if (isDangerousProtocol(hrefOption.href, router.protocolAllowlist)) { + if (process.env.NODE_ENV !== 'production') { + console.warn( + `Blocked Link with dangerous protocol: ${hrefOption.href}`, + ) + } + return undefined + } + return hrefOption.href + } + + if (safeInternal) return undefined + + // Only attempt URL parsing when it looks like an absolute URL. + if (typeof to === 'string' && to.indexOf(':') > -1) { + try { + new URL(to) + if (isDangerousProtocol(to, router.protocolAllowlist)) { + if (process.env.NODE_ENV !== 'production') { + console.warn(`Blocked Link with dangerous protocol: ${to}`) + } + return undefined + } + return to + } catch {} + } + + return undefined + })() + + const isActive = (() => { + if (externalLink) return false + + const currentLocation = router.stores.location.state + + const exact = activeOptions?.exact ?? false + + if (exact) { + const testExact = exactPathTest( + currentLocation.pathname, + next.pathname, + router.basepath, + ) + if (!testExact) { + return false + } + } else { + const currentPathSplit = removeTrailingSlash( + currentLocation.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 + } + } + + const includeSearch = activeOptions?.includeSearch ?? true + if (includeSearch) { + if (currentLocation.search !== next.search) { + const currentSearchEmpty = + !currentLocation.search || + (typeof currentLocation.search === 'object' && + Object.keys(currentLocation.search).length === 0) + const nextSearchEmpty = + !next.search || + (typeof next.search === 'object' && + Object.keys(next.search).length === 0) + + if (!(currentSearchEmpty && nextSearchEmpty)) { + const searchTest = deepEqual(currentLocation.search, next.search, { + partial: !exact, + ignoreUndefined: !activeOptions?.explicitUndefined, + }) + if (!searchTest) { + return false + } + } + } + } + + // Hash is not available on the server + if (activeOptions?.includeHash) { + return false + } + + return true + })() + + if (externalLink) { + return { + ...propsSafeToSpread, + ref: innerRef as React.ComponentPropsWithRef<'a'>['ref'], + href: externalLink, + ...(children && { children }), + ...(target && { target }), + ...(disabled && { disabled }), + ...(style && { style }), + ...(className && { className }), + } + } + + const resolvedActiveProps: React.HTMLAttributes<HTMLAnchorElement> = + isActive + ? (functionalUpdate(activeProps as any, {}) ?? STATIC_ACTIVE_OBJECT) + : STATIC_EMPTY_OBJECT + + const resolvedInactiveProps: React.HTMLAttributes<HTMLAnchorElement> = + isActive + ? STATIC_EMPTY_OBJECT + : (functionalUpdate(inactiveProps, {}) ?? STATIC_EMPTY_OBJECT) + + const resolvedStyle = (() => { + const baseStyle = style + const activeStyle = resolvedActiveProps.style + const inactiveStyle = resolvedInactiveProps.style + + if (!baseStyle && !activeStyle && !inactiveStyle) { + return undefined + } + + if (baseStyle && !activeStyle && !inactiveStyle) { + return baseStyle + } + + if (!baseStyle && activeStyle && !inactiveStyle) { + return activeStyle + } + + if (!baseStyle && !activeStyle && inactiveStyle) { + return inactiveStyle + } + + return { + ...baseStyle, + ...activeStyle, + ...inactiveStyle, + } + })() + + const resolvedClassName = (() => { + const baseClassName = className + const activeClassName = resolvedActiveProps.className + const inactiveClassName = resolvedInactiveProps.className + + if (!baseClassName && !activeClassName && !inactiveClassName) { + return '' + } + + let out = '' + + if (baseClassName) { + out = baseClassName + } + + if (activeClassName) { + out = out ? `${out} ${activeClassName}` : activeClassName + } + + if (inactiveClassName) { + out = out ? `${out} ${inactiveClassName}` : inactiveClassName + } + + return out + })() + + return { + ...propsSafeToSpread, + ...resolvedActiveProps, + ...resolvedInactiveProps, + href: hrefOption?.href, + ref: innerRef as React.ComponentPropsWithRef<'a'>['ref'], + disabled: !!disabled, + target, + ...(resolvedStyle && { style: resolvedStyle }), + ...(resolvedClassName && { className: resolvedClassName }), + ...(disabled && STATIC_DISABLED_PROPS), + ...(isActive && STATIC_ACTIVE_PROPS), + } } // ========================================================================== @@ -204,489 +374,389 @@ export function useLinkProps< // 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 { - activeOptions, - to, - preload: userPreload, - preloadDelay: userPreloadDelay, - disabled, - target, - onClick, - onBlur, - onFocus, - onMouseEnter, - onMouseLeave, - onTouchStart, - } = options as typeof options & { to?: string } + const isHydrated = useHydrated() // 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)) - - // `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 - } - - 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 [ - 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 + const _options = React.useMemo( + () => options, // eslint-disable-next-line react-hooks/exhaustive-deps + [ + router, + options.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 currentLocation = useStore( + router.stores.location, + (l) => l, + (prev, next) => prev.href === next.href, + ) + + // eslint-disable-next-line react-hooks/rules-of-hooks + const next = React.useMemo(() => { + const opts = { _fromLocation: currentLocation, ..._options } + return router.buildLocation(opts as any) + }, [router, currentLocation, _options]) + + // Use publicHref - it contains the correct href for display + // When a rewrite changes the origin, publicHref is the full URL + // Otherwise it's the origin-stripped path + // This avoids constructing URL objects in the hot path + const hrefOptionPublicHref = next.maskedLocation + ? next.maskedLocation.publicHref + : next.publicHref + const hrefOptionExternal = next.maskedLocation + ? next.maskedLocation.external + : next.external + // eslint-disable-next-line react-hooks/rules-of-hooks + const hrefOption = React.useMemo( + () => + getHrefOption( + hrefOptionPublicHref, + hrefOptionExternal, + router.history, + disabled, + ), + [disabled, hrefOptionExternal, hrefOptionPublicHref, router.history], + ) + + // eslint-disable-next-line react-hooks/rules-of-hooks + const externalLink = React.useMemo(() => { + if (hrefOption?.external) { + // Block dangerous protocols for external links + if (isDangerousProtocol(hrefOption.href, router.protocolAllowlist)) { + if (process.env.NODE_ENV !== 'production') { + console.warn( + `Blocked Link with dangerous protocol: ${hrefOption.href}`, + ) + } + return undefined + } + return hrefOption.href + } + const safeInternal = isSafeInternal(to) + if (safeInternal) return undefined + if (typeof to !== 'string' || to.indexOf(':') === -1) return undefined + try { + new URL(to as any) + // Block dangerous protocols like javascript:, blob:, data: + if (isDangerousProtocol(to, router.protocolAllowlist)) { + if (process.env.NODE_ENV !== 'production') { + console.warn(`Blocked Link with dangerous protocol: ${to}`) + } + return undefined + } + return to + } catch {} + return undefined + }, [to, hrefOption, router.protocolAllowlist]) + + // eslint-disable-next-line react-hooks/rules-of-hooks + const isActive = React.useMemo(() => { + if (externalLink) return false + if (activeOptions?.exact) { + const testExact = exactPathTest( + currentLocation.pathname, + next.pathname, + router.basepath, + ) + if (!testExact) { + return false + } + } else { + const currentPathSplit = removeTrailingSlash( + currentLocation.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 + } + } + + if (activeOptions?.includeSearch ?? true) { + const searchTest = deepEqual(currentLocation.search, next.search, { + partial: !activeOptions?.exact, + ignoreUndefined: !activeOptions?.explicitUndefined, + }) + if (!searchTest) { + return false + } + } + + if (activeOptions?.includeHash) { + return isHydrated && currentLocation.hash === next.hash + } + return true }, [ - router, - scope, - options.from, - options.hash, - options.href, - to, - stableSearch, - stableParams, - options.state, - options.mask, - options.unsafeRelative, - stableActiveOptions, - disabled, + activeOptions?.exact, + activeOptions?.explicitUndefined, + activeOptions?.includeHash, + activeOptions?.includeSearch, + currentLocation, + externalLink, + isHydrated, + next.hash, + next.pathname, + next.search, + router.basepath, ]) - // 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 + // 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, + } + + // eslint-disable-next-line react-hooks/rules-of-hooks + const [isTransitioning, setIsTransitioning] = React.useState(false) // eslint-disable-next-line react-hooks/rules-of-hooks const hasRenderFetched = React.useRef(false) const preload = - options.reloadDocument || externalLink || linkDisabled + options.reloadDocument || externalLink ? false : (userPreload ?? router.options.defaultPreload) const preloadDelay = userPreloadDelay ?? router.options.defaultPreloadDelay ?? 0 - // `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 - } + const doPreload = React.useCallback(() => { + router + .preloadRoute({ ..._options, _builtLocation: next } as any) + .catch((err) => { + console.warn(err) + console.warn(preloadWarning) + }) + }, [router, _options, next]) - if (!preloadDelay) { - preloadLink(router, dest) - return + // eslint-disable-next-line react-hooks/rules-of-hooks + const preloadViewportIoCallback = React.useCallback( + (entry: IntersectionObserverEntry | undefined) => { + if (entry?.isIntersecting) { + doPreload() } - - innerRef.t ??= setTimeout(() => { - innerRef.t = undefined - preloadLink(router, dest) - }, preloadDelay) }, - [router, dest, innerRef, preload, preloadDelay], + [doPreload], + ) + + // eslint-disable-next-line react-hooks/rules-of-hooks + useIntersectionObserver( + innerRef, + preloadViewportIoCallback, + intersectionObserverOptions, + { disabled: !!disabled || !(preload === 'viewport') }, ) - // 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(() => { - // Disabled preloading creates neither an observer nor an intent timer. - if (!preload) { + if (hasRenderFetched.current) { return } - if (preload === 'render' && !hasRenderFetched.current) { + if (!disabled && preload === 'render') { + doPreload() hasRenderFetched.current = true - preloadLink(router, dest) } - 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 - } + }, [disabled, doPreload, preload]) // The click handler const handleClick = (e: React.MouseEvent) => { - // The element's own target attribute is the fallback. - const effectiveTarget = - target ?? - (e.currentTarget as HTMLAnchorElement | SVGAElement).getAttribute( - 'target', - ) + // Check actual element's target attribute as fallback + const elementTarget = ( + e.currentTarget as HTMLAnchorElement | SVGAElement + ).getAttribute('target') + const effectiveTarget = target !== undefined ? target : elementTarget if ( - !linkDisabled && - !(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) && + !disabled && + !isCtrlEvent(e) && !e.defaultPrevented && (!effectiveTarget || effectiveTarget === '_self') && e.button === 0 ) { e.preventDefault() - cancelPreload(innerRef) - // The current options carry the navigation controls; `dest` only - // contributes the location the link displays. Navigation builds again - // to run `validateSearch` before committing. - router.navigate({ ...options, _fromLocation: dest._fromLocation }) + 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, + }) } } - const handleTouchStart = () => { - if (preload === 'intent') { - preloadLink(router, dest) + 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 }), + ...(onBlur && { onBlur }), + ...(onFocus && { onFocus }), + ...(onMouseEnter && { onMouseEnter }), + ...(onMouseLeave && { onMouseLeave }), + ...(onTouchStart && { onTouchStart }), } } - const handleLeave = () => { - if (preload === 'intent') { - cancelPreload(innerRef) + const enqueueIntentPreload = (e: React.MouseEvent | React.FocusEvent) => { + if (disabled || preload !== 'intent') return + + if (!preloadDelay) { + doPreload() + return + } + + const eventTarget = e.currentTarget + + if (timeoutMap.has(eventTarget)) { + return + } + + const id = setTimeout(() => { + timeoutMap.delete(eventTarget) + doPreload() + }, preloadDelay) + timeoutMap.set(eventTarget, id) + } + + const handleTouchStart = (_: React.TouchEvent) => { + if (disabled || preload !== 'intent') return + doPreload() + } + + const handleLeave = (e: React.MouseEvent | React.FocusEvent) => { + if (disabled || !preload || !preloadDelay) return + const eventTarget = e.currentTarget + const id = timeoutMap.get(eventTarget) + if (id) { + clearTimeout(id) + timeoutMap.delete(eventTarget) } } - 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) + return { + ...propsSafeToSpread, + ...resolvedActiveProps, + ...resolvedInactiveProps, + href: hrefOption?.href, + ref: innerRef as React.ComponentPropsWithRef<'a'>['ref'], + onClick: composeHandlers([onClick, handleClick]), + onBlur: composeHandlers([onBlur, handleLeave]), + onFocus: composeHandlers([onFocus, enqueueIntentPreload]), + onMouseEnter: composeHandlers([onMouseEnter, enqueueIntentPreload]), + 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), + ...(isHydrated && isTransitioning && STATIC_TRANSITIONING_PROPS), + } } const STATIC_EMPTY_OBJECT = {} const STATIC_ACTIVE_OBJECT = { className: 'active' } -// 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 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' } -// 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 +const timeoutMap = new WeakMap<EventTarget, ReturnType<typeof setTimeout>>() + +const intersectionObserverOptions: IntersectionObserverInit = { + rootMargin: '100px', +} + +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) } - props[key] = (options as Record<string, unknown>)[key] } - return props -} - -// 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, + publicHref: string, + external: boolean, + history: AnyRouter['history'], disabled: boolean | undefined, ) { - if (disabled) { - return undefined + if (disabled) return undefined + // Full URL means rewrite changed the origin - treat as external-like + if (external) { + return { href: publicHref, external: true } } - 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: history.createHref(publicHref) || '/', + external: false, } - return href +} + +function isSafeInternal(to: unknown) { + if (typeof to !== 'string') return false + const zero = to.charCodeAt(0) + if (zero === 47) return to.charCodeAt(1) !== 47 // '/' but not '//' + return zero === 46 // '.', '..', './', '../' } type UseLinkReactProps<TComp> = TComp extends keyof React.JSX.IntrinsicElements @@ -748,7 +818,10 @@ 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 }) => React.ReactNode) + | ((state: { + isActive: boolean + isTransitioning: boolean + }) => React.ReactNode) } type LinkComponentReactProps<TComp> = Omit< @@ -835,7 +908,7 @@ export function createLink<const TComp>( * * Props: * - `preload`: Controls route preloading (eg. 'intent', 'render', 'viewport', true/false) - * - `preloadDelay`: Delay in ms before preloading on focus, hover, or viewport entry + * - `preloadDelay`: Delay in ms before preloading on hover * - `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 @@ -844,50 +917,30 @@ 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.memo( - React.forwardRef<Element, any>((props, ref) => { - const host = props._asChild || 'a' - const linkProps = useLinkProps(props as any, ref, host) +export const Link: LinkComponent<'a'> = React.forwardRef<Element, any>( + (props, ref) => { + const { _asChild, ...rest } = props + const { type: _type, ...linkProps } = useLinkProps(rest as any, ref) const children = - typeof props.children === 'function' - ? props.children({ + typeof rest.children === 'function' + ? rest.children({ isActive: (linkProps as any)['data-status'] === 'active', }) - : props.children + : rest.children - return React.createElement(host, linkProps, children) - }), - areLinkPropsEqual, + if (!_asChild) { + // the ReturnType of useLinkProps returns the correct type for a <a> element, not a general component that has a disabled prop + // @ts-expect-error + const { disabled: _, ...rest } = linkProps + return React.createElement('a', rest, children) + } + return React.createElement(_asChild, linkProps, children) + }, ) as any -// 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 +function isCtrlEvent(e: React.MouseEvent) { + return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) } export type LinkOptionsFnOptions< diff --git a/packages/react-router/src/matchContext.tsx b/packages/react-router/src/matchContext.tsx index 12db4dbada..ce182bd994 100644 --- a/packages/react-router/src/matchContext.tsx +++ b/packages/react-router/src/matchContext.tsx @@ -1,70 +1,4 @@ -'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 deleted file mode 100644 index 252ab7fd10..0000000000 --- a/packages/react-router/src/nonRouteComponentContext.tsx +++ /dev/null @@ -1,21 +0,0 @@ -'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 3c5287cb2e..9932eadd47 100644 --- a/packages/react-router/src/not-found.tsx +++ b/packages/react-router/src/not-found.tsx @@ -1,7 +1,7 @@ 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 { useStore } from '@tanstack/react-store' import { CatchBoundary } from './CatchBoundary' import { useRouter } from './useRouter' import type { ErrorInfo } from 'react' @@ -9,14 +9,14 @@ import type { NotFoundError } from '@tanstack/router-core' export function CatchNotFound(props: { fallback?: (error: NotFoundError) => React.ReactElement - onCatch?: (error: NotFoundError, errorInfo: ErrorInfo) => void + onCatch?: (error: Error, 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 pathname = router.stores.location.state.pathname + const status = router.stores.status.state const resetKey = `not-found-${pathname}-${status}` return ( @@ -44,12 +44,12 @@ export function CatchNotFound(props: { // TODO: Some way for the user to programmatically reset the not-found boundary? // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static - const pathname = useSelector( + const pathname = useStore( 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 status = useStore(router.stores.status, (status) => status) const resetKey = `not-found-${pathname}-${status}` return ( diff --git a/packages/react-router/src/renderRouteNotFound.tsx b/packages/react-router/src/renderRouteNotFound.tsx index 9e363da7f4..225a013bea 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,27 +18,18 @@ export function renderRouteNotFound( ) { if (!route.options.notFoundComponent) { if (router.options.defaultNotFoundComponent) { - const notFoundElement = ( - <router.options.defaultNotFoundComponent {...data} /> - ) - return process.env.NODE_ENV !== 'production' - ? wrapInNonRouteComponentContext(notFoundElement, 'notFoundComponent') - : notFoundElement + return <router.options.defaultNotFoundComponent {...data} /> } - 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>)`, - ) - } + 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>)`, + ) } return <DefaultGlobalNotFound /> } - const notFoundElement = <route.options.notFoundComponent {...data} /> - return process.env.NODE_ENV !== 'production' - ? wrapInNonRouteComponentContext(notFoundElement, 'notFoundComponent') - : notFoundElement + return <route.options.notFoundComponent {...data} /> } diff --git a/packages/react-router/src/route.tsx b/packages/react-router/src/route.tsx index 57dca9ef02..58f5198d56 100644 --- a/packages/react-router/src/route.tsx +++ b/packages/react-router/src/route.tsx @@ -107,19 +107,33 @@ export class RouteApi< } useMatch: UseMatchRoute<TId> = (opts) => { - return useMatch({ ...opts, from: this.id } as any) as any + return useMatch({ + select: opts?.select, + from: this.id, + structuralSharing: opts?.structuralSharing, + } as any) as any } useRouteContext: UseRouteContextRoute<TId> = (opts) => { - return useRouteContext({ ...(opts as any), from: this.id }) + return useRouteContext({ ...(opts as any), from: this.id as any }) } useSearch: UseSearchRoute<TId> = (opts) => { - return useSearch({ ...opts, from: this.id } as any) + // 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 } useParams: UseParamsRoute<TId> = (opts) => { - return useParams({ ...opts, from: this.id } as any) + // 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 } useLoaderDeps: UseLoaderDepsRoute<TId> = (opts) => { @@ -247,7 +261,11 @@ export class Route< } useMatch: UseMatchRoute<TId> = (opts) => { - return useMatch({ ...opts, from: this.id } as any) as any + return useMatch({ + select: opts?.select, + from: this.id, + structuralSharing: opts?.structuralSharing, + } as any) as any } useRouteContext: UseRouteContextRoute<TId> = (opts?) => { @@ -255,11 +273,21 @@ export class Route< } useSearch: UseSearchRoute<TId> = (opts) => { - return useSearch({ ...opts, from: this.id } as any) + // 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 } useParams: UseParamsRoute<TId> = (opts) => { - return useParams({ ...opts, from: this.id } as any) + // 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 } useLoaderDeps: UseLoaderDepsRoute<TId> = (opts) => { @@ -504,7 +532,11 @@ export class RootRoute< } useMatch: UseMatchRoute<RootRouteId> = (opts) => { - return useMatch({ ...opts, from: this.id } as any) as any + return useMatch({ + select: opts?.select, + from: this.id, + structuralSharing: opts?.structuralSharing, + } as any) as any } useRouteContext: UseRouteContextRoute<RootRouteId> = (opts) => { @@ -512,11 +544,21 @@ export class RootRoute< } useSearch: UseSearchRoute<RootRouteId> = (opts) => { - return useSearch({ ...opts, from: this.id } as any) + // 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 } useParams: UseParamsRoute<RootRouteId> = (opts) => { - return useParams({ ...opts, from: this.id } as any) + // 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 } useLoaderDeps: UseLoaderDepsRoute<RootRouteId> = (opts) => { @@ -622,7 +664,7 @@ export interface DefaultRouteTypes<TProps> { export interface RouteTypes<TProps> extends DefaultRouteTypes<TProps> {} export type AsyncRouteComponent<TProps> = RouteTypes<TProps>['component'] & { - preload?: () => Promise<void> | undefined + preload?: () => Promise<void> } export type RouteComponent = AsyncRouteComponent<{}> diff --git a/packages/react-router/src/router.ts b/packages/react-router/src/router.ts index de5e89a9fb..2033bd1330 100644 --- a/packages/react-router/src/router.ts +++ b/packages/react-router/src/router.ts @@ -1,4 +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 { @@ -73,7 +74,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: unknown, errorInfo: React.ErrorInfo) => void + defaultOnCatch?: (error: Error, errorInfo: React.ErrorInfo) => void } } @@ -117,3 +118,11 @@ export class Router< 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 30b442c6c4..dc623b70c2 100644 --- a/packages/react-router/src/routerContext.tsx +++ b/packages/react-router/src/routerContext.tsx @@ -1,5 +1,3 @@ -'use client' - import * as React from 'react' import type { AnyRouter } from '@tanstack/router-core' diff --git a/packages/react-router/src/routerStores.ts b/packages/react-router/src/routerStores.ts index 3197f54681..86126271a2 100644 --- a/packages/react-router/src/routerStores.ts +++ b/packages/react-router/src/routerStores.ts @@ -1,4 +1,4 @@ -import { batch, createAtom } from '@tanstack/react-store' +import { batch, createStore } from '@tanstack/react-store' import { createNonReactiveMutableStore, createNonReactiveReadonlyStore, @@ -19,8 +19,8 @@ export const getStoreFactory: GetStoreConfig = (opts) => { } } return { - createMutableStore: createAtom, - createReadonlyStore: createAtom, + createMutableStore: createStore, + createReadonlyStore: createStore, batch: batch, } } diff --git a/packages/react-router/src/scroll-restoration.tsx b/packages/react-router/src/scroll-restoration.tsx index 5c49425e77..f8c3c4559a 100644 --- a/packages/react-router/src/scroll-restoration.tsx +++ b/packages/react-router/src/scroll-restoration.tsx @@ -1,14 +1,45 @@ -import { getScrollRestorationScriptForRouter } from '@tanstack/router-core/scroll-restoration-script' +import { + defaultGetScrollRestorationKey, + escapeHtml, + restoreScroll, + storageKey, +} from '@tanstack/router-core' +import { isServer } from '@tanstack/router-core/isServer' import { useRouter } from './useRouter' import { ScriptOnce } from './ScriptOnce' export function ScrollRestoration() { const router = useRouter() - const script = getScrollRestorationScriptForRouter(router) - - if (!script) { + if (!router.isScrollRestoring || !(isServer ?? router.isServer)) { 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 - return <ScriptOnce children={script} /> + const restoreScrollOptions: Parameters<typeof restoreScroll>[0] = { + storageKey, + shouldScrollRestoration: true, + } + if (resolvedKey) { + restoreScrollOptions.key = resolvedKey + } + + return ( + <ScriptOnce + children={`(${restoreScroll.toString()})(${escapeHtml(JSON.stringify(restoreScrollOptions))})`} + /> + ) } diff --git a/packages/react-router/src/ssr/RouterClient.tsx b/packages/react-router/src/ssr/RouterClient.tsx index 69abc97f0b..7c1cc491df 100644 --- a/packages/react-router/src/ssr/RouterClient.tsx +++ b/packages/react-router/src/ssr/RouterClient.tsx @@ -3,11 +3,16 @@ import { Await } from '../awaited' import { RouterProvider } from '../RouterProvider' import type { AnyRouter } from '@tanstack/router-core' -let hydrationPromise: Promise<void> | undefined +let hydrationPromise: Promise<void | Array<Array<void>>> | undefined export function RouterClient(props: { router: AnyRouter }) { - hydrationPromise ??= hydrate(props.router).finally(() => window.$_TSR!.h()) - + if (!hydrationPromise) { + if (!props.router.stores.matchesId.state.length) { + hydrationPromise = hydrate(props.router) + } else { + hydrationPromise = Promise.resolve() + } + } return ( <Await promise={hydrationPromise} diff --git a/packages/react-router/src/ssr/renderRouterToStream.tsx b/packages/react-router/src/ssr/renderRouterToStream.tsx index b55fc35405..3621bf667d 100644 --- a/packages/react-router/src/ssr/renderRouterToStream.tsx +++ b/packages/react-router/src/ssr/renderRouterToStream.tsx @@ -1,13 +1,12 @@ -import { PassThrough, Readable } from 'node:stream' +import { PassThrough } from 'node:stream' import ReactDOMServer from 'react-dom/server' import { isbot } from 'isbot' import { - createSsrStreamResponse, - getSsrStatus, + transformPipeableStreamWithRouter, 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 ({ @@ -21,116 +20,71 @@ export const renderRouterToStream = async ({ responseHeaders: Headers children: ReactNode }) => { - 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) - } + 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 } - try { - if (typeof ReactDOMServer.renderToReadableStream === 'function') { - const stream = await ReactDOMServer.renderToReadableStream(children, { - signal, + const responseStream = transformReadableStreamWithRouter( + router, + stream as unknown as ReadableStream, + ) + return new Response(responseStream as any, { + status: router.stores.statusCode.state, + headers: responseHeaders, + }) + } + + if (typeof ReactDOMServer.renderToPipeableStream === 'function') { + const reactAppPassthrough = new PassThrough() + + try { + const pipeable = ReactDOMServer.renderToPipeableStream(children, { nonce: router.options.ssr?.nonce, progressiveChunkSize: Number.POSITIVE_INFINITY, - 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) + ...(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)), + ) + } }, }) - if (rendererAbort) { - await waitForRequest(stream.allReady, rendererAbort.signal) - } - return createSsrStreamResponse( - router, - new Response(responseStream, { - status: getSsrStatus(router), - headers: responseHeaders, - }), - ) + } catch (e) { + console.error('Error in renderToPipeableStream:', e) + reactAppPassthrough.destroy(e instanceof Error ? e : new Error(String(e))) } - 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, - }, - ) - - 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.', + const responseStream = transformPipeableStreamWithRouter( + router, + reactAppPassthrough, ) - } catch (error) { - router.serverSsr?.cleanup() - throw error + return new Response(responseStream as any, { + status: router.stores.statusCode.state, + headers: responseHeaders, + }) } + + throw new Error( + 'No renderToReadableStream or renderToPipeableStream found in react-dom/server. Ensure you are using a version of react-dom that supports streaming.', + ) } diff --git a/packages/react-router/src/ssr/renderRouterToString.tsx b/packages/react-router/src/ssr/renderRouterToString.tsx index 4b2faa2409..3b8131eaea 100644 --- a/packages/react-router/src/ssr/renderRouterToString.tsx +++ b/packages/react-router/src/ssr/renderRouterToString.tsx @@ -1,5 +1,4 @@ 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' @@ -12,9 +11,26 @@ export const renderRouterToString = async ({ responseHeaders: Headers children: ReactNode }) => { - return renderSsrHtmlResponse({ - router, - responseHeaders, - render: () => ReactDOMServer.renderToString(children), - }) + try { + let html = ReactDOMServer.renderToString(children) + router.serverSsr!.setRenderFinished() + + const injectedHtml = router.serverSsr!.takeBufferedHtml() + if (injectedHtml) { + html = html.replace(`</body>`, () => `${injectedHtml}</body>`) + } + + return new Response(`<!DOCTYPE html>${html}`, { + status: router.stores.statusCode.state, + 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/react-router/src/useBlocker.tsx b/packages/react-router/src/useBlocker.tsx index 65636510c9..209af19501 100644 --- a/packages/react-router/src/useBlocker.tsx +++ b/packages/react-router/src/useBlocker.tsx @@ -1,5 +1,3 @@ -'use client' - import * as React from 'react' import { useRouter } from './useRouter' import type { @@ -14,12 +12,12 @@ import type { RegisteredRouter, } from '@tanstack/router-core' -type ShouldBlockFnLocation< +interface ShouldBlockFnLocation< out TRouteId, out TFullPath, out TAllParams, out TFullSearchSchema, -> = { +> { routeId: TRouteId fullPath: TFullPath pathname: string @@ -179,24 +177,22 @@ export function useBlocker( location: HistoryLocation, ): AnyShouldBlockFnLocation { const parsedLocation = router.parseLocation(location) - const [, rawParams, foundRoute] = router.getMatchedRoutes( - parsedLocation.pathname, - ) - if (foundRoute === undefined) { + const matchedRoutes = router.getMatchedRoutes(parsedLocation.pathname) + if (matchedRoutes.foundRoute === undefined) { return { routeId: '__notFound__', fullPath: parsedLocation.pathname, pathname: parsedLocation.pathname, - params: rawParams, + params: matchedRoutes.routeParams, search: router.options.parseSearch(location.search), } } return { - routeId: foundRoute.id, - fullPath: foundRoute.fullPath, + routeId: matchedRoutes.foundRoute.id, + fullPath: matchedRoutes.foundRoute.fullPath, pathname: parsedLocation.pathname, - params: rawParams, + params: matchedRoutes.routeParams, search: router.options.parseSearch(location.search), } } diff --git a/packages/react-router/src/useCanGoBack.ts b/packages/react-router/src/useCanGoBack.ts index 2a8ce612b1..602c1ae2f5 100644 --- a/packages/react-router/src/useCanGoBack.ts +++ b/packages/react-router/src/useCanGoBack.ts @@ -1,4 +1,4 @@ -import { useSelector } from '@tanstack/react-store' +import { useStore } from '@tanstack/react-store' import { isServer } from '@tanstack/router-core/isServer' import { useRouter } from './useRouter' @@ -6,11 +6,11 @@ export function useCanGoBack() { const router = useRouter() if (isServer ?? router.isServer) { - return router.stores.location.get().state.__TSR_index !== 0 + return router.stores.location.state.state.__TSR_index !== 0 } // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static - return useSelector( + return useStore( 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 755a39616e..eb82a40461 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: (match) => { - return opts.select ? opts.select(match.loaderData) : match.loaderData + select: (s: any) => { + return opts.select ? opts.select(s.loaderData) : s.loaderData }, - }) as UseLoaderDataResult<TRouter, TFrom, TStrict, TSelected> + } as any) as UseLoaderDataResult<TRouter, TFrom, TStrict, TSelected> } diff --git a/packages/react-router/src/useLoaderDeps.tsx b/packages/react-router/src/useLoaderDeps.tsx index 21e7267d4e..0e5365eea0 100644 --- a/packages/react-router/src/useLoaderDeps.tsx +++ b/packages/react-router/src/useLoaderDeps.tsx @@ -62,8 +62,8 @@ export function useLoaderDeps< const { select, ...rest } = opts return useMatch({ ...rest, - select: (match) => { - return select ? select(match.loaderDeps) : match.loaderDeps + select: (s) => { + return select ? select(s.loaderDeps) : s.loaderDeps }, }) as UseLoaderDepsResult<TRouter, TFrom, TSelected> } diff --git a/packages/react-router/src/useLocation.tsx b/packages/react-router/src/useLocation.tsx index 5fa39fa92e..3c366b36a8 100644 --- a/packages/react-router/src/useLocation.tsx +++ b/packages/react-router/src/useLocation.tsx @@ -1,9 +1,8 @@ -'use client' - -import { useSelector } from '@tanstack/react-store' +import { useStore } from '@tanstack/react-store' +import { useRef } from 'react' +import { replaceEqualDeep } from '@tanstack/router-core' import { isServer } from '@tanstack/router-core/isServer' import { useRouter } from './useRouter' -import { useStructuralSharing } from './useMatch' import type { StructuralSharingOption, ValidateSelected, @@ -53,16 +52,28 @@ export function useLocation< const router = useRouter<TRouter>() if (isServer ?? router.isServer) { - const location = router.stores.location.get() + const location = router.stores.location.state 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, + const previousResult = // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static - useStructuralSharing(opts, router), - ) as UseLocationResult<TRouter, TSelected> + useRef<ValidateSelected<TRouter, TSelected, TStructuralSharing>>(undefined) + + // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static + return useStore(router.stores.location, (location) => { + const selected = ( + opts?.select ? opts.select(location as any) : location + ) as ValidateSelected<TRouter, TSelected, TStructuralSharing> + + if (opts?.structuralSharing ?? router.options.defaultStructuralSharing) { + const shared = replaceEqualDeep(previousResult.current, selected) + previousResult.current = shared + return shared + } + + return selected + }) as UseLocationResult<TRouter, TSelected> } diff --git a/packages/react-router/src/useMatch.tsx b/packages/react-router/src/useMatch.tsx index 95a4aaa286..26dbc1082f 100644 --- a/packages/react-router/src/useMatch.tsx +++ b/packages/react-router/src/useMatch.tsx @@ -1,9 +1,8 @@ -'use client' - import * as React from 'react' -import { useSelector } from '@tanstack/react-store' -import { invariant, replaceEqualDeep } from '@tanstack/router-core' +import { useStore } from '@tanstack/react-store' +import { replaceEqualDeep } from '@tanstack/router-core' import { isServer } from '@tanstack/router-core/isServer' +import invariant from 'tiny-invariant' import { dummyMatchContext, matchContext } from './matchContext' import { useRouter } from './useRouter' import type { @@ -20,46 +19,11 @@ 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 - } -} +const dummyStore = { + state: undefined, + get: () => undefined, + subscribe: () => () => {}, +} as any export interface UseMatchBaseOptions< TRouter extends AnyRouter, @@ -79,18 +43,17 @@ export type UseMatchRoute<out TFrom> = < TRouter extends AnyRouter = RegisteredRouter, TSelected = unknown, TStructuralSharing extends boolean = boolean, - TThrow extends boolean = true, >( opts?: UseMatchBaseOptions< TRouter, TFrom, true, - TThrow, + true, TSelected, TStructuralSharing > & StructuralSharingOption<TRouter, TSelected, TStructuralSharing>, -) => ThrowOrOptional<UseMatchResult<TRouter, TFrom, true, TSelected>, TThrow> +) => UseMatchResult<TRouter, TFrom, true, TSelected> export type UseMatchOptions< TRouter extends AnyRouter, @@ -143,54 +106,58 @@ export function useMatch< >, ): ThrowOrOptional<UseMatchResult<TRouter, TFrom, TStrict, TSelected>, TThrow> { const router = useRouter<TRouter>() - const nearestRouteId = React.useContext( + const nearestMatchId = React.useContext( opts.from ? dummyMatchContext : matchContext, ) - const routeId = opts.from ?? nearestRouteId - const matchStore = router.stores.getMatchStore(routeId!) + const key = opts.from ?? nearestMatchId + const matchStore = key + ? opts.from + ? router.stores.getMatchStoreByRouteId(key) + : router.stores.activeMatchStoresById.get(key) + : 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() - } + const match = matchStore?.state + invariant( + !((opts.shouldThrow ?? true) && !match), + `Could not find ${opts.from ? `an active match from "${opts.from}"` : 'a nearest match!'}`, + ) + if (match === undefined) { return undefined as any } return (opts.select ? opts.select(match as any) : match) as any } - const selector = + const previousResult = // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static - useStructuralSharing(opts, router) + React.useRef<ValidateSelected<TRouter, TSelected, TStructuralSharing>>( + undefined, + ) // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static - const matchSelection = useSelector(matchStore, (match) => - match ? selector(match as any) : dummyMatch, - ) + return useStore(matchStore ?? dummyStore, (match) => { + invariant( + !((opts.shouldThrow ?? true) && !match), + `Could not find ${opts.from ? `an active match from "${opts.from}"` : 'a nearest match!'}`, + ) - 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!'}`, - ) + if (match === undefined) { + return undefined } - invariant() - } + const selected = ( + opts.select ? opts.select(match as any) : match + ) as ValidateSelected<TRouter, TSelected, TStructuralSharing> - return undefined as any + if (opts.structuralSharing ?? router.options.defaultStructuralSharing) { + const shared = replaceEqualDeep(previousResult.current, selected) + previousResult.current = shared + return shared + } + + return selected + }) as any } diff --git a/packages/react-router/src/useNavigate.tsx b/packages/react-router/src/useNavigate.tsx index ce95e5b4c1..f697d0fbdd 100644 --- a/packages/react-router/src/useNavigate.tsx +++ b/packages/react-router/src/useNavigate.tsx @@ -1,5 +1,3 @@ -'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 44a6e47f9d..444eee7a41 100644 --- a/packages/react-router/src/useParams.tsx +++ b/packages/react-router/src/useParams.tsx @@ -49,18 +49,17 @@ 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, + /* TThrow */ true, TSelected, TStructuralSharing > & StructuralSharingOption<TRouter, TSelected, TStructuralSharing>, -) => ThrowOrOptional<UseParamsResult<TRouter, TFrom, true, TSelected>, TThrow> +) => UseParamsResult<TRouter, TFrom, true, TSelected> /** * 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 6708274c11..1bc4220f38 100644 --- a/packages/react-router/src/useRouter.tsx +++ b/packages/react-router/src/useRouter.tsx @@ -1,6 +1,5 @@ -'use client' - import * as React from 'react' +import warning from 'tiny-warning' import { routerContext } from './routerContext' import type { AnyRouter, RegisteredRouter } from '@tanstack/router-core' @@ -18,18 +17,9 @@ export function useRouter<TRouter extends AnyRouter = RegisteredRouter>(opts?: { warn?: boolean }): TRouter { const value = React.useContext(routerContext) - if (!value) { - warnMissingRouter(opts) - } + warning( + !((opts?.warn ?? true) && !value), + 'useRouter must be used inside a <RouterProvider> component!', + ) 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 fa17ee9f59..1d3ce690cb 100644 --- a/packages/react-router/src/useRouterState.tsx +++ b/packages/react-router/src/useRouterState.tsx @@ -1,9 +1,8 @@ -'use client' - -import { useSelector } from '@tanstack/react-store' +import { useStore } from '@tanstack/react-store' +import { useRef } from 'react' +import { replaceEqualDeep } from '@tanstack/router-core' import { isServer } from '@tanstack/router-core/isServer' import { useRouter } from './useRouter' -import { useStructuralSharing } from './useMatch' import type { AnyRouter, RegisteredRouter, @@ -56,10 +55,9 @@ export function useRouterState< // 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< + const _isServer = isServer ?? router.isServer + if (_isServer) { + const state = router.stores.__store.state as RouterState< TRouter['routeTree'] > return (opts?.select ? opts.select(state) : state) as UseRouterStateResult< @@ -68,10 +66,23 @@ export function useRouterState< > } - // 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> + const previousResult = + // eslint-disable-next-line react-hooks/rules-of-hooks + useRef<ValidateSelected<TRouter, TSelected, TStructuralSharing>>(undefined) + + // eslint-disable-next-line react-hooks/rules-of-hooks + return useStore(router.stores.__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> } diff --git a/packages/react-router/src/useSearch.tsx b/packages/react-router/src/useSearch.tsx index 3979967d76..46b6e51642 100644 --- a/packages/react-router/src/useSearch.tsx +++ b/packages/react-router/src/useSearch.tsx @@ -49,18 +49,17 @@ 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, + /* TThrow */ true, TSelected, TStructuralSharing > & StructuralSharingOption<TRouter, TSelected, TStructuralSharing>, -) => ThrowOrOptional<UseSearchResult<TRouter, TFrom, true, TSelected>, TThrow> +) => UseSearchResult<TRouter, TFrom, true, TSelected> /** * Read and select the current route's search parameters with type-safety. @@ -99,7 +98,7 @@ export function useSearch< strict: opts.strict, shouldThrow: opts.shouldThrow, structuralSharing: opts.structuralSharing, - select: (match) => { + select: (match: any) => { 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 7887761993..33f8ea9acc 100644 --- a/packages/react-router/src/utils.ts +++ b/packages/react-router/src/utils.ts @@ -1,13 +1,10 @@ -'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' +const REACT_USE = 'use' /** * React.use if available (React 19+), undefined otherwise. @@ -28,9 +25,7 @@ export function useStableCallback<T extends (...args: Array<any>) => any>( } export const useLayoutEffect = - (isServer ?? typeof window === 'undefined') - ? React.useEffect - : React.useLayoutEffect + typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect /** * Taken from https://www.developerway.com/posts/implementing-advanced-use-previous-hook#part3 @@ -57,3 +52,74 @@ 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 deleted file mode 100644 index 11978db209..0000000000 --- a/packages/react-router/tests/Asset.test.tsx +++ /dev/null @@ -1,166 +0,0 @@ -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 89e1088454..2116e78416 100644 --- a/packages/react-router/tests/Matches.test-d.tsx +++ b/packages/react-router/tests/Matches.test-d.tsx @@ -8,8 +8,7 @@ import { useMatchRoute, useMatches, } from '../src' -import type * as React from 'react' -import type { AnyRouteMatch, MakeMatchRouteOptions, RouteMatch } from '../src' +import type { AnyRouteMatch, RouteMatch } from '../src' const rootRoute = createRootRoute() @@ -234,19 +233,3 @@ 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 93dca8b9c0..dd3ca3dfa6 100644 --- a/packages/react-router/tests/Matches.test.tsx +++ b/packages/react-router/tests/Matches.test.tsx @@ -1,19 +1,9 @@ import { afterEach, describe, expect, test } from 'vitest' -import { - act, - cleanup, - fireEvent, - render, - renderHook, - screen, - waitFor, -} from '@testing-library/react' +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' import { createMemoryHistory } from '@tanstack/history' -import { createControlledPromise } from '@tanstack/router-core' import { Link, Outlet, - RouterContextProvider, RouterProvider, createRootRoute, createRoute, @@ -136,11 +126,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({ @@ -155,187 +145,6 @@ 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 deleted file mode 100644 index e8dc5447cb..0000000000 --- a/packages/react-router/tests/Outlet.test.tsx +++ /dev/null @@ -1,146 +0,0 @@ -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 976410cba5..7db908644b 100644 --- a/packages/react-router/tests/Scripts.test.tsx +++ b/packages/react-router/tests/Scripts.test.tsx @@ -1,4 +1,4 @@ -import { afterEach, describe, expect, test, vi } from 'vitest' +import { afterEach, describe, expect, test } from 'vitest' import { act, cleanup, @@ -9,14 +9,11 @@ import { } 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, @@ -27,23 +24,19 @@ import { 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'] - }, -) => +const createTestManifest = (routeId: string) => ({ - ...(options?.scriptFormat ? { scriptFormat: options.scriptFormat } : {}), routes: { [routeId]: { - preloads: [options?.preloadHref ?? '/main.js'], - css: [options?.stylesheetHref ?? '/main.css'], + assets: [ + { + tag: 'link', + attrs: { + rel: 'stylesheet', + href: '/main.css', + }, + }, + ], }, }, }) satisfies Manifest @@ -60,7 +53,6 @@ afterEach(() => { cleanup() browserHistories.splice(0).forEach((history) => history.destroy()) window.history.replaceState(null, 'root', '/') - delete window.$_TSR }) describe('ssr scripts', () => { @@ -162,12 +154,15 @@ describe('ssr scripts', () => { { src: 'script3.js' }, ]) - const html = ReactDOMServer.renderToString( - <RouterProvider router={router} />, + const { container } = await act(() => + render(<RouterProvider router={router} />), + ) + expect(await screen.findByTestId('root')).toBeInTheDocument() + expect(await screen.findByTestId('index')).toBeInTheDocument() + + 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>`, ) - expect(html).toContain('<script src="script.js"></script>') - expect(html).toContain('<script src="script3.js"></script>') - expect(html).not.toContain('script2.js') }) }) @@ -222,65 +217,6 @@ describe('scripts with async/defer attributes', () => { 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: () => [ @@ -338,119 +274,6 @@ describe('scripts with async/defer attributes', () => { }) 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: () => @@ -547,38 +370,8 @@ describe('ssr HeadContent', () => { ) }) - test('renders manifest module preloads with low fetch priority', async () => { - const preloadHref = '/low-priority-module.js' - const rootRoute = createRootRoute({ - component: () => <HeadContent />, - }) - 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( - <RouterProvider router={router} />, - ) - expect(html).toContain( - `<link rel="modulepreload" href="${preloadHref}" fetchPriority="low"/>`, - ) - }) - test('keeps manifest stylesheet links mounted when history state changes', async () => { const history = createTestBrowserHistory() - const stylesheetHref = '/history-state.css' const rootRoute = createRootRoute({ component: () => { @@ -614,9 +407,7 @@ describe('ssr HeadContent', () => { }) router.ssr = { - manifest: createTestManifest(rootRoute.id, { - stylesheetHref, - }), + manifest: createTestManifest(rootRoute.id), } await router.load() @@ -625,7 +416,7 @@ describe('ssr HeadContent', () => { const getStylesheetLink = () => Array.from(document.querySelectorAll('link[rel="stylesheet"]')).find( - (link) => link.getAttribute('href') === stylesheetHref, + (link) => link.getAttribute('href') === '/main.css', ) await waitFor(() => { @@ -646,273 +437,13 @@ describe('ssr HeadContent', () => { expect(getStylesheetLink()).toBe(initialLink) expect( Array.from(document.querySelectorAll('link[rel="stylesheet"]')).filter( - (link) => link.getAttribute('href') === stylesheetHref, + (link) => link.getAttribute('href') === '/main.css', ), ).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( - <HeadContent - assetCrossOrigin={{ - script: 'anonymous', - stylesheet: 'use-credentials', - }} - />, - document.head, - )} - <Outlet /> - </> - ) - }, - }) - - const indexRoute = createRoute({ - path: '/', - getParentRoute: () => rootRoute, - component: () => <div>Index</div>, - }) - - const router = createRouter({ - history, - routeTree: rootRoute.addChildren([indexRoute]), - }) - - router.ssr = { - manifest: createTestManifest(rootRoute.id, { - stylesheetHref, - preloadHref, - }), - } - - await router.load() - - await act(() => render(<RouterProvider router={router} />)) - - 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(<HeadContent />, document.head)} - <Outlet /> - </> - ) - }, - }) - - const indexRoute = createRoute({ - path: '/', - getParentRoute: () => rootRoute, - component: () => <div>Index</div>, - }) - - 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(<RouterProvider router={router} />)) - - 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(<HeadContent />, document.head)} - <Outlet /> - </> - ) - }, - }) - - const indexRoute = createRoute({ - path: '/', - getParentRoute: () => rootRoute, - component: () => <div>Index</div>, - }) - - const router = createRouter({ - history, - routeTree: rootRoute.addChildren([indexRoute]), - }) - - router.ssr = { - manifest: createTestManifest(rootRoute.id, { - preloadHref, - scriptFormat: 'iife', - }), - } - - await router.load() - - await act(() => render(<RouterProvider router={router} />)) - - 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( - <HeadContent assetCrossOrigin="anonymous" />, - document.head, - )} - <Outlet /> - </> - ) - }, - }) - - const indexRoute = createRoute({ - path: '/', - getParentRoute: () => rootRoute, - component: () => <div>Index</div>, - }) - - 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(<RouterProvider router={router} />)) - - 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: () => { @@ -943,9 +474,7 @@ describe('ssr HeadContent', () => { }) router.ssr = { - manifest: createTestManifest(rootRoute.id, { - stylesheetHref, - }), + manifest: createTestManifest(rootRoute.id), } await router.load() @@ -954,7 +483,7 @@ describe('ssr HeadContent', () => { const getStylesheetLink = () => Array.from(document.querySelectorAll('link[rel="stylesheet"]')).find( - (link) => link.getAttribute('href') === stylesheetHref, + (link) => link.getAttribute('href') === '/main.css', ) await waitFor(() => { @@ -985,134 +514,10 @@ describe('ssr HeadContent', () => { expect(getStylesheetLink()).toBe(initialLink) expect( Array.from(document.querySelectorAll('link[rel="stylesheet"]')).filter( - (link) => link.getAttribute('href') === stylesheetHref, + (link) => link.getAttribute('href') === '/main.css', ), ).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(<HeadContent />, document.head)} - <Outlet /> - <Scripts /> - </> - ), - }) - const parentRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/parent', - shouldReload: true, - loader: () => { - if (failParent) { - throw new Error('parent failed') - } - }, - component: Outlet, - errorComponent: () => <div>Parent error</div>, - }) - 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: () => <div>Child content</div>, - }) - 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(<RouterProvider router={router} />)) - - 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', () => { 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 deleted file mode 100644 index 09945bb9af..0000000000 --- a/packages/react-router/tests/ancestor-loader-child-pending-min.test.tsx +++ /dev/null @@ -1,157 +0,0 @@ -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<void>() - const childLoader = createControlledPromise<void>() - const rootRoute = createRootRoute({ - component: () => <Outlet />, - }) - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () => <div>Index</div>, - }) - const parentRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/parent', - loader: () => parentLoader, - component: () => <Outlet />, - }) - const childRoute = createRoute({ - getParentRoute: () => parentRoute, - path: '/child', - pendingMs: 0, - pendingMinMs: 100, - pendingComponent: () => <div>Child pending</div>, - loader: () => childLoader, - component: () => <div>Child content</div>, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([ - indexRoute, - parentRoute.addChildren([childRoute]), - ]), - history: createMemoryHistory({ initialEntries: ['/'] }), - defaultPendingMs: 0, - }) - - await router.load() - render(<RouterProvider router={router} />) - expect(screen.getByText('Index')).toBeInTheDocument() - - let navigation!: Promise<void> - 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<void>() - const childLoader = createControlledPromise<void>() - const rootRoute = createRootRoute({ component: Outlet }) - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () => <div>Index</div>, - }) - const parentRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/parent', - loader: () => parentLoader, - component: Outlet, - }) - const childRoute = createRoute({ - getParentRoute: () => parentRoute, - path: '/child', - pendingMs: 1_000, - pendingMinMs: 0, - pendingComponent: () => <div>Child pending</div>, - loader: () => childLoader, - component: () => <div>Child content</div>, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([ - indexRoute, - parentRoute.addChildren([childRoute]), - ]), - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - - await router.load() - render(<RouterProvider router={router} />) - - let navigation!: Promise<void> - 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 3ed3c3039e..60d1e8a821 100644 --- a/packages/react-router/tests/blocker.test.tsx +++ b/packages/react-router/tests/blocker.test.tsx @@ -1,4 +1,5 @@ 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 deleted file mode 100644 index dcdd94af67..0000000000 --- a/packages/react-router/tests/component-preload-retry-pending-min.test.tsx +++ /dev/null @@ -1,150 +0,0 @@ -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<void>() - const Page = Object.assign(() => <div>Page content</div>, { - preload: () => componentGate, - }) - const rootRoute = createRootRoute({}) - const pageRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/page', - component: Page, - pendingMs: 10, - pendingComponent: () => <div>Loading page...</div>, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([pageRoute]), - history: createMemoryHistory({ initialEntries: ['/page'] }), - }) - - render(<RouterProvider router={router} />) - - 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<void>() - let preloadAttempt = 0 - let retryInvalidation!: Promise<void> - let retrySettled = false - - const Page = Object.assign( - () => <div data-testid="page-content">Page content</div>, - { - preload: vi.fn(() => { - preloadAttempt++ - return preloadAttempt === 1 - ? Promise.reject(new Error('initial chunk request failed')) - : retryChunk - }), - }, - ) - - function RetryError({ reset }: ErrorComponentProps) { - const router = useRouter() - return ( - <button - type="button" - onClick={() => { - reset() - retryInvalidation = router.invalidate() - void retryInvalidation.then(() => { - retrySettled = true - }) - }} - > - Retry chunk - </button> - ) - } - - const rootRoute = createRootRoute({}) - const pageRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/page', - component: Page, - errorComponent: RetryError, - pendingMs: 0, - pendingMinMs: 100, - pendingComponent: () => ( - <div data-testid="page-pending">Loading page...</div> - ), - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([pageRoute]), - history: createMemoryHistory({ initialEntries: ['/page'] }), - }) - - render(<RouterProvider router={router} />) - - 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 deleted file mode 100644 index 7abe959ebc..0000000000 --- a/packages/react-router/tests/component-preload-retry.test.tsx +++ /dev/null @@ -1,208 +0,0 @@ -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(() => ( - <div data-testid="pending-component">Loading page</div> - )) - const rootRoute = createRootRoute({ - component: () => ( - <> - <Link to="/">Home link</Link> - <Link to="/page">Page link</Link> - <Outlet /> - </> - ), - }) - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () => <div>Home content</div>, - }) - 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(<RouterProvider router={router} />) - 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: () => <div>Page content</div> }) - }) - 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 = () => <div>Page content</div> - 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 ( - <button - type="button" - onClick={() => { - reset() - void router.invalidate() - }} - > - Retry - </button> - ) - } - - 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(<RouterProvider router={router} />) - - 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 = () => <div>Page content</div> - 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(<RouterProvider router={router} />) - - expect(await screen.findByText('Page content')).toBeInTheDocument() - expect(importer).toHaveBeenCalledTimes(2) -}) diff --git a/packages/react-router/tests/errorBoundary.test-d.tsx b/packages/react-router/tests/errorBoundary.test-d.tsx deleted file mode 100644 index ccb66929dd..0000000000 --- a/packages/react-router/tests/errorBoundary.test-d.tsx +++ /dev/null @@ -1,30 +0,0 @@ -import { expectTypeOf, test } from 'vitest' -import { createRootRoute, createRouter } from '../src' -import type { ErrorComponentProps } from '../src' - -test('only boundary errors default to unknown', () => { - expectTypeOf<ErrorComponentProps['error']>().toEqualTypeOf<unknown>() - expectTypeOf<ErrorComponentProps<Error>['error']>().toEqualTypeOf<Error>() - const routeTree = createRootRoute({ - errorComponent: ({ error }) => { - expectTypeOf(error).toEqualTypeOf<unknown>() - return null - }, - onCatch: (error) => { - expectTypeOf(error).toEqualTypeOf<unknown>() - }, - onError: (error) => { - expectTypeOf(error).toBeAny() - }, - }) - createRouter({ - routeTree, - defaultErrorComponent: ({ error }) => { - expectTypeOf(error).toEqualTypeOf<unknown>() - return null - }, - defaultOnCatch: (error) => { - expectTypeOf(error).toEqualTypeOf<unknown>() - }, - }) -}) diff --git a/packages/react-router/tests/errorComponent.test.tsx b/packages/react-router/tests/errorComponent.test.tsx index 441610a2e7..2c0062a9ac 100644 --- a/packages/react-router/tests/errorComponent.test.tsx +++ b/packages/react-router/tests/errorComponent.test.tsx @@ -1,36 +1,18 @@ import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' -import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import { 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 <div>Error: {getErrorMessage(props.error)}</div> -} - -function getErrorMessage(error: unknown) { - return error instanceof Error ? error.message : String(error) + return <div>Error: {props.error.message}</div> } async function asyncToThrowFn() { @@ -42,10 +24,6 @@ function throwFn() { throw new Error('error thrown') } -function primitiveThrowFn() { - throw 'primitive error thrown' -} - let history: RouterHistory beforeEach(() => { @@ -60,197 +38,48 @@ afterEach(() => { cleanup() }) -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 +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 ( - <div> - <Link to="/about">link to about</Link> - </div> - ) - }, - }) - const aboutRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/about', - beforeLoad: caller === 'beforeLoad' ? testFn : undefined, - loader: caller === 'loader' ? testFn : undefined, - component: function Home() { - return <div>About route content</div> - }, - 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(<RouterProvider router={router} />) - - 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 <div>Index route content</div> - }, - 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(<RouterProvider router={router} />) - - 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 }) => { + test.each(callers)( + 'an Error is thrown on navigate in the route $caller function', + async ({ caller, testFn }) => { const rootRoute = createRootRoute() - const indexErrorComponent = vi.fn(() => <div>Index error</div>) - const indexRoute = createRoute({ getParentRoute: () => rootRoute, path: '/', component: function Home() { return ( <div> - <div>Index route content</div> <Link to="/about">link to about</Link> </div> ) }, - errorComponent: indexErrorComponent, }) - const aboutRoute = createRoute({ getParentRoute: () => rootRoute, path: '/about', - component: function About() { + beforeLoad: caller === 'beforeLoad' ? testFn : undefined, + loader: caller === 'loader' ? testFn : undefined, + component: function Home() { return <div>About route content</div> }, - errorComponent: isUsingLazyError ? undefined : MyErrorComponent, - ...routeOptions, + errorComponent: 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, }) @@ -260,815 +89,59 @@ describe.each([true, false])( name: 'link to about', }) - await act(() => fireEvent.click(linkToAbout)) + expect(linkToAbout).toBeInTheDocument() + fireEvent.mouseOver(linkToAbout) + fireEvent.focus(linkToAbout) + fireEvent.click(linkToAbout) - expect( - await screen.findByText('Error: error thrown', undefined, { - timeout: 1500, - }), - ).toBeInTheDocument() + const errorComponent = await screen.findByText( + `Error: error thrown`, + undefined, + { timeout: 1500 }, + ) + await expect( + screen.findByText('About route content'), + ).rejects.toThrow() + expect(errorComponent).toBeInTheDocument() + }, + ) - await act(() => router.navigate({ to: '/' })) + 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 <div>Index route content</div> + }, + errorComponent: MyErrorComponent, + }) - expect( - await screen.findByText('Index route content'), - ).toBeInTheDocument() - expect(indexErrorComponent).not.toHaveBeenCalled() + const routeTree = rootRoute.addChildren([indexRoute]) + + const router = createRouter({ + routeTree, + defaultPreload: options.preload, + history, + }) + + render(<RouterProvider router={router} />) + + 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<number>() - 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 <div>Recovered child revision {revision}</div> - }, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([childRoute]), - history, - }) - vi.spyOn(console, 'warn').mockImplementation(() => {}) - vi.spyOn(console, 'error').mockImplementation(() => {}) - - render(<RouterProvider router={router} />) - 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<number>() - let loaderCalls = 0 - const rootRoute = createRootRoute({ - component: Outlet, - errorComponent: ({ error }) => ( - <div>Ancestor error: {getErrorMessage(error)}</div> - ), - }) - 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 <div>Recovered child revision {revision}</div> - }, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([childRoute]), - history, - }) - vi.spyOn(console, 'warn').mockImplementation(() => {}) - vi.spyOn(console, 'error').mockImplementation(() => {}) - - let invalidation: Promise<void> | undefined - try { - render(<RouterProvider router={router} />) - 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 ( - <div> - <Link to="/about">link to about</Link> - </div> - ) - }, - }) - const aboutRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/about', - beforeLoad: primitiveThrowFn, - component: function About() { - return <div>About route content</div> - }, - errorComponent: ({ error }) => <div>Error: {String(error)}</div>, - }) - - const routeTree = rootRoute.addChildren([indexRoute, aboutRoute]) - - const router = createRouter({ - routeTree, - history, - }) - - render(<RouterProvider router={router} />) - - 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( - <CatchBoundary - getResetKey={() => 0} - errorComponent={({ error }) => ( - <div>{Object.is(error, thrown) ? 'Caught value' : 'Wrong value'}</div> - )} - onCatch={onCatch} - > - <ThrowFalsy /> - </CatchBoundary>, - ) - - 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(<RouterProvider router={router} />) - - 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 }) => ( - <div> - {error instanceof Error && error.cause === thrown - ? 'Promise route error' - : 'Wrong route error'} - </div> - ), - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute]), - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - - render(<RouterProvider router={router} />) - - 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 ( - <html> - <body> - {children} - <Scripts /> - </body> - </html> - ) - }, - component: function Root() { - return <Outlet /> - }, - }) - const aboutRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/about', - beforeLoad: primitiveThrowFn, - component: function About() { - return <div>About route content</div> - }, - errorComponent: ({ error }) => <div>Error: {String(error)}</div>, - }) - - 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: <RouterServer router={router} />, - }), - ) - - 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<void>() - const childStarted = createControlledPromise<void>() - const parentGate = createControlledPromise<void>() - const childGate = createControlledPromise<void>() - const childSettled = createControlledPromise<void>() - const rootRoute = createRootRoute({ component: Outlet }) - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () => <div>Home</div>, - }) - const parentRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/parent', - component: Outlet, - loader: async () => { - parentStarted.resolve() - await parentGate - throw new Error('later parent failure') - }, - errorComponent: () => <div>Parent error boundary</div>, - }) - const childRoute = createRoute({ - getParentRoute: () => parentRoute, - path: '/child', - loader: async () => { - childStarted.resolve() - await childGate - childSettled.resolve() - throw new Error('first child failure') - }, - errorComponent: () => <div>Child error boundary</div>, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([ - indexRoute, - parentRoute.addChildren([childRoute]), - ]), - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - - await router.load() - render(<RouterProvider router={router} />) - - let navigation!: Promise<void> - 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<void>() - const childStarted = createControlledPromise<void>() - const parentGate = createControlledPromise<void>() - const childGate = createControlledPromise<void>() - const childSettled = createControlledPromise<void>() - const lazyParentOptions = createLazyRoute('/parent')({ - component: () => ( - <> - <div>Lazy parent shell</div> - <Outlet /> - </> - ), - }) - const parentChunk = createControlledPromise<typeof lazyParentOptions>() - const rootRoute = createRootRoute({ component: Outlet }) - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () => <div>Home</div>, - }) - const parentRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/parent', - loader: async () => { - parentStarted.resolve() - await parentGate - throw new Error('later parent failure') - }, - errorComponent: () => <div>Parent error boundary</div>, - }).lazy(() => parentChunk) - const childRoute = createRoute({ - getParentRoute: () => parentRoute, - path: '/child', - loader: async () => { - childStarted.resolve() - await childGate - childSettled.resolve() - throw new Error('first child failure') - }, - errorComponent: () => <div>Child error boundary</div>, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([ - indexRoute, - parentRoute.addChildren([childRoute]), - ]), - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - - await router.load() - render(<RouterProvider router={router} />) - - let navigation: Promise<void> | 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<void>() - const childStarted = createControlledPromise<void>() - const parentGate = createControlledPromise<void>() - const childGate = createControlledPromise<void>() - const childSettled = createControlledPromise<void>() - const rootRoute = createRootRoute({ - shellComponent: function RootDocument({ children }) { - return ( - <html> - <body> - {children} - <Scripts /> - </body> - </html> - ) - }, - component: Outlet, - }) - const parentRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/parent', - component: Outlet, - loader: async () => { - parentStarted.resolve() - await parentGate - throw new Error('later parent failure') - }, - errorComponent: () => <div>Parent error boundary</div>, - }) - const childRoute = createRoute({ - getParentRoute: () => parentRoute, - path: '/child', - loader: async () => { - childStarted.resolve() - await childGate - childSettled.resolve() - throw new Error('first child failure') - }, - errorComponent: () => <div>Child error boundary</div>, - }) - 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: <RouterServer router={router} />, - }), - ) - 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 ( - <html> - <head> - <HeadContent /> - </head> - <body> - {children} - <Scripts /> - </body> - </html> - ) - }, - 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 <div>Route content</div> - }, - errorComponent: ({ error }) => ( - <div>Error UI: {getErrorMessage(error)}</div> - ), - }) - - 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: <RouterServer router={router} />, - }), - ) - - 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 <Outlet /> - }, - notFoundComponent: function NotFound() { - return <div>No pizza</div> - }, - pendingComponent: function Pending() { - return <div>Loading...</div> - }, - loader: rootLoader, - shouldReload: true, - pendingMs: 0, - pendingMinMs: 100, - wrapInSuspense: true, - }) - - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: function Home() { - return ( - <div> - <Link to="/pizza/rotten" preload="intent"> - link to rotten pizza - </Link> - </div> - ) - }, - }) - - const restaurantRoute = createRoute({ - getParentRoute: () => rootRoute, - id: 'restaurant', - component: function Restaurant() { - return <Outlet /> - }, - }) - - const pizzaRoute = createRoute({ - getParentRoute: () => restaurantRoute, - path: '/pizza/$pizzaType', - component: function Pizza() { - return <div>Pizza</div> - }, - 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(<RouterProvider router={router} />) - - 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(<ErrorComponent error={error} />) - - 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 <div>Recovered child</div> - } - - function App() { - return ( - <CatchBoundary - getResetKey={() => resetKey} - onCatch={onCatch} - errorComponent={({ reset }) => <button onClick={reset}>Reset</button>} - > - <Child /> - </CatchBoundary> - ) - } - - const { rerender } = render(<App />) - shouldThrow = false - rerender(<App />) - expect(screen.queryByText('Recovered child')).not.toBeInTheDocument() - fireEvent.click(screen.getByText('Reset')) - expect(screen.getByText('Recovered child')).toBeInTheDocument() - - shouldThrow = true - rerender(<App />) - shouldThrow = false - resetKey++ - rerender(<App />) - 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 <div>Healthy child</div> - } - - function App() { - return ( - <CatchBoundary - getResetKey={() => resetKey} - errorComponent={() => <div>Caught error</div>} - > - <Child /> - </CatchBoundary> - ) - } - - const { rerender } = render(<App />) - expect(screen.getByText('Healthy child')).toBeInTheDocument() - - resetKey = {} - rerender(<App />) - expect(screen.getByText('Healthy child')).toBeInTheDocument() - - shouldThrow = true - rerender(<App />) - expect(screen.getByText('Caught error')).toBeInTheDocument() - - shouldThrow = false - rerender(<App />) - expect(screen.getByText('Caught error')).toBeInTheDocument() - - resetKey = undefined - rerender(<App />) - expect(screen.getByText('Healthy child')).toBeInTheDocument() - - shouldThrow = true - rerender(<App />) - 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 cc0e7b265a..c97d932325 100644 --- a/packages/react-router/tests/fileRoute.test-d.tsx +++ b/packages/react-router/tests/fileRoute.test-d.tsx @@ -17,31 +17,6 @@ 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 { '/': { @@ -93,13 +68,6 @@ 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' - } } } @@ -132,31 +100,3 @@ 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 9f3fa290d3..2a8e225371 100644 --- a/packages/react-router/tests/fileRoute.test.ts +++ b/packages/react-router/tests/fileRoute.test.ts @@ -1,5 +1,5 @@ /* eslint-disable */ -import { afterEach, describe, it, expect, vi } from 'vitest' +import { describe, it, expect } from 'vitest' import { getRouteApi, createFileRoute, @@ -7,33 +7,8 @@ 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 deleted file mode 100644 index 57d99c8af5..0000000000 --- a/packages/react-router/tests/hydration-capped-boundary-pending.test.tsx +++ /dev/null @@ -1,264 +0,0 @@ -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<void>> = [] - -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 <div data-testid="missing-page">Missing page</div> - } - - 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(<RouterProvider router={serverRouter} />) - 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<typeof hydrateRoot> - await act(async () => { - root = hydrateRoot(container, <RouterProvider router={clientRouter} />, { - 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 <div data-testid="boundary-error">Boundary error</div> - } - - function BoundaryNotFound() { - React.useEffect(() => { - boundaryCommits() - }, []) - return <div data-testid="boundary-not-found">Boundary not found</div> - } - - const makeRouteTree = () => { - const boundaryOptions = { - beforeLoad: () => { - throw outcome === 'notFound' - ? notFound() - : new Error('server route failure') - }, - pendingComponent: () => ( - <div data-testid="boundary-pending">Boundary pending</div> - ), - 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: () => <div>Child</div>, - }) - 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( - <RouterProvider router={serverRouter} />, - ) - 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<typeof hydrateRoot> - await act(async () => { - root = hydrateRoot(container, <RouterProvider router={clientRouter} />) - 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 deleted file mode 100644 index c53dc62ae3..0000000000 --- a/packages/react-router/tests/hydration-terminal-lane.test.tsx +++ /dev/null @@ -1,141 +0,0 @@ -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: () => ( - <> - <div>{parentRoute.useLoaderData()}</div> - <Outlet /> - </> - ), - }) - const childRoute = createRoute({ - getParentRoute: () => parentRoute, - path: '/child', - ssr: false, - loader: childLoader, - component: () => <div>{childRoute.useLoaderData()}</div>, - }) - 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(<RouterProvider router={router} />) - - 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: () => <div role="status">Missing page pending</div>, - notFoundComponent: () => <div>Missing page</div>, - }) - 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(<RouterProvider router={router} />) - 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 deleted file mode 100644 index 41b2c11608..0000000000 --- a/packages/react-router/tests/issue-2072-context-invalidate.test.tsx +++ /dev/null @@ -1,157 +0,0 @@ -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<boolean> = [] - const rootRoute = createRootRouteWithContext<{ - auth: { isAuthenticated: boolean } - }>()() - const loginRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/login', - beforeLoad: ({ context }) => { - if (context.auth.isAuthenticated) { - throw redirect({ to: '/private' }) - } - }, - component: () => <div>Login page</div>, - }) - 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: () => <div>Private page</div>, - }) - 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 ( - <> - <button - onClick={() => { - setIsAuthenticated(false) - router.invalidate() - }} - > - Logout - </button> - <RouterProvider - router={router} - context={{ auth: { isAuthenticated } }} - /> - </> - ) - } - - render(<App />) - 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<boolean> = [] - const rootRoute = createRootRouteWithContext<{ - auth: { isAuthenticated: boolean } - }>()() - const loginRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/login', - beforeLoad: ({ context }) => { - if (context.auth.isAuthenticated) { - throw redirect({ to: '/private' }) - } - }, - component: () => <div>Login page</div>, - }) - 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: () => <div>Private page</div>, - }) - 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 ( - <> - <button - onClick={() => { - setIsAuthenticated(true) - router.invalidate() - }} - > - Login - </button> - <RouterProvider - router={router} - context={{ auth: { isAuthenticated } }} - /> - </> - ) - } - - render(<App />) - 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 deleted file mode 100644 index 9cf3f82cb7..0000000000 --- a/packages/react-router/tests/issue-2182-root-pending.test.tsx +++ /dev/null @@ -1,55 +0,0 @@ -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<string>() - const rootRoute = createRootRoute({ - pendingMs: 0, - pendingMinMs: 100, - pendingComponent: () => <div data-testid="root-pending">Pending</div>, - loader: () => loaderGate, - component: () => <div data-testid="root-content">Loaded</div>, - }) - const router = createRouter({ - routeTree: rootRoute, - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - - render(<RouterProvider router={router} />) - - 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 deleted file mode 100644 index 2821571c42..0000000000 --- a/packages/react-router/tests/issue-2905-root-beforeload-pending.test.tsx +++ /dev/null @@ -1,59 +0,0 @@ -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: () => <div data-testid="root-pending">Root pending</div>, - component: () => <div data-testid="root-content">Root</div>, - }) - const router = createRouter({ - routeTree: rootRoute, - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - - render(<RouterProvider router={router} />) - 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 deleted file mode 100644 index 11e2c150cc..0000000000 --- a/packages/react-router/tests/issue-4467-lazy-route-pending.test.tsx +++ /dev/null @@ -1,222 +0,0 @@ -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: () => <h1>Index page</h1>, - }) - const lazyPageOptions = createLazyRoute('/page')({ - component: () => <h1>Page</h1>, - }) - const lazyOptions = createControlledPromise<typeof lazyPageOptions>() - 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: () => <p role="status">Loading page</p>, - }) - let navigationPromise: Promise<void> | undefined - - onTestFinished(async () => { - await act(async () => { - if (lazyOptions.status === 'pending') { - lazyOptions.resolve(lazyPageOptions) - } - await navigationPromise - }) - }) - - render(<RouterProvider router={router} />) - - 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: () => <h1>Index page</h1>, - }) - const loader = createControlledPromise<void>() - const lazyPageOptions = createLazyRoute('/page')({ - pendingComponent: () => <p role="status">Loading lazy page</p>, - component: () => <h1>Page</h1>, - }) - const lazyOptions = createControlledPromise<typeof lazyPageOptions>() - 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: () => <p role="status">Loading default</p>, - }) - let navigation: Promise<void> | undefined - - onTestFinished(async () => { - await act(async () => { - lazyOptions.resolve(lazyPageOptions) - loader.resolve() - await navigation - }) - }) - - render(<RouterProvider router={router} />) - 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<void>() - const lazyPageOptions = createLazyRoute('/page')({ - pendingComponent: () => <p role="status">Loading lazy page</p>, - component: () => <h1>Page</h1>, - }) - const lazyOptions = createControlledPromise<typeof lazyPageOptions>() - const rootRoute = createRootRoute({ component: Outlet }) - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () => <h1>Index page</h1>, - }) - 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: () => <p role="status">Loading default</p>, - }) - - render(<RouterProvider router={router} />) - 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 deleted file mode 100644 index 824fcc1fb7..0000000000 --- a/packages/react-router/tests/issue-4476-react-query-cancellation.test.tsx +++ /dev/null @@ -1,133 +0,0 @@ -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<number>() - 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: () => ( - <> - <Link to="/page-two" preload="intent"> - Page two - </Link> - <Outlet /> - </> - ), - }) - function PageOneComponent() { - const query = useQuery({ - queryKey, - queryFn: () => Promise.resolve(3), - }) - return <div data-testid="page-one">Page one: {query.data}</div> - } - 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 ( - <div data-testid="page-two-error"> - {error instanceof Error ? error.name : String(error)} - </div> - ) - }, - component: () => { - const { data } = pageTwoRoute.useRouteContext() - return <div data-testid="page-two">Page two: {data}</div> - }, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([pageOneRoute, pageTwoRoute]), - history: createMemoryHistory({ initialEntries: ['/'] }), - defaultPreload: 'intent', - defaultPreloadDelay: 0, - defaultPreloadStaleTime: 0, - defaultPendingMs: 0, - defaultPendingComponent: () => { - pendingComponentRendered() - return <div data-testid="page-two-pending">Loading page two</div> - }, - }) - - onTestFinished(() => { - queryGate.resolve(10) - queryClient.clear() - }) - - render( - <QueryClientProvider client={queryClient}> - <RouterProvider router={router} /> - </QueryClientProvider>, - ) - 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 deleted file mode 100644 index e179a1502e..0000000000 --- a/packages/react-router/tests/issue-5778-router-provider-context-preload.test.tsx +++ /dev/null @@ -1,113 +0,0 @@ -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: () => ( - <> - <Link to="/foo" preload="intent"> - Foo - </Link> - <Outlet /> - </> - ), - }) - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () => <div>Home</div>, - }) - const authRoute = createRoute({ - getParentRoute: () => rootRoute, - id: '_authenticated', - beforeLoad: ({ context, cause, preload }) => { - seen.push({ route: 'auth', foo: context.foo, cause, preload }) - }, - component: () => <Outlet />, - }) - const fooRoute = createRoute({ - getParentRoute: () => authRoute, - path: '/foo', - beforeLoad: ({ context, cause, preload }) => { - seen.push({ route: 'foo', foo: context.foo, cause, preload }) - }, - component: () => <div>Foo page</div>, - }) - 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 ( - <> - <output aria-label="Current context">{foo}</output> - <button - onClick={() => { - setFoo('baz') - }} - > - Update context - </button> - <RouterProvider router={router} context={{ foo }} /> - </> - ) - } - - render(<App />) - 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 deleted file mode 100644 index 138e7f5716..0000000000 --- a/packages/react-router/tests/issue-6107-lazy-chunk-error-component.test.tsx +++ /dev/null @@ -1,93 +0,0 @@ -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: () => ( - <> - <Link to="/posts" preload="intent"> - Posts - </Link> - <Outlet /> - </> - ), - }) - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () => <div>Index</div>, - }) - 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 ( - <div data-testid="default-error"> - {error instanceof Error ? error.message : String(error)} - </div> - ) - }, - }) - const preloadRoute = vi.spyOn(router, 'preloadRoute') - - render(<RouterProvider router={router} />) - 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 deleted file mode 100644 index 836ff045bc..0000000000 --- a/packages/react-router/tests/issue-6371-search-default-normalization-abort.test.tsx +++ /dev/null @@ -1,173 +0,0 @@ -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<string>() - const canonicalLocation = createControlledPromise<void>() - const abortedLoaderData = 'discarded aborted loader' - const loaderSignals: Array<AbortSignal> = [] - const loaderLocations: Array<string> = [] - 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<string>((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 <div data-testid="pending-location">{href}</div> - } - - const rootRoute = createRootRoute({ - component: () => <Outlet />, - }) - const aboutRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/about', - validateSearch: (search: Record<string, unknown>) => ({ - page: typeof search.page === 'number' ? search.page : 1, - }), - loader, - component: () => ( - <div data-testid="about-data">{aboutRoute.useLoaderData()}</div> - ), - errorComponent: ({ error }) => { - errorComponentRendered(error) - return ( - <div data-testid="about-error"> - {error instanceof Error ? error.message : String(error)} - </div> - ) - }, - }) - 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(<RouterProvider router={router} />) - - 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: () => <Outlet />, - }) - const aboutRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/about', - validateSearch: (search: Record<string, unknown>) => ({ - page: typeof search.page === 'number' ? search.page : 1, - }), - loader, - component: () => <div>{aboutRoute.useLoaderData()}</div>, - }) - 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(<RouterProvider router={router} />) - - 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 deleted file mode 100644 index 5640cb7477..0000000000 --- a/packages/react-router/tests/issue-7051-force-pending-suspense.test.tsx +++ /dev/null @@ -1,195 +0,0 @@ -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<void>() - - const rootRoute = createRootRoute({ - component: () => <Outlet />, - }) - - const forcePendingRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/force-pending', - pendingMs: 0, - pendingMinMs: 10, - loader: async () => { - if (shouldSuspendReload) { - await reloadGate - } - - return 'done' - }, - component: () => ( - <div data-testid="force-pending-route"> - {forcePendingRoute.useLoaderData()} - </div> - ), - pendingComponent: () => ( - <div data-testid="force-pending-fallback">Pending...</div> - ), - errorComponent: ({ error }) => { - errorComponentRendered(error) - return <div data-testid="force-pending-error">{String(error)}</div> - }, - }) - - const router = createRouter({ - routeTree: rootRoute.addChildren([forcePendingRoute]), - history, - }) - - render(<RouterProvider router={router} />) - - await act(() => router.load()) - expect(await screen.findByTestId('force-pending-route')).toHaveTextContent( - 'done', - ) - - shouldSuspendReload = true - let invalidation!: Promise<void> - 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<void>() - const secondLoaderStarted = createControlledPromise<void>() - const secondLoaderGate = createControlledPromise<void>() - const firstErrorComponentRendered = vi.fn() - let firstSignal: AbortSignal | undefined - - const rootRoute = createRootRoute({ - component: () => <Outlet />, - }) - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () => <div data-testid="home-page">Home page</div>, - }) - const firstRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/first', - pendingMs: 0, - loader: async ({ abortController }) => { - firstSignal = abortController.signal - await new Promise<void>((_resolve, reject) => { - abortController.signal.addEventListener( - 'abort', - () => { - firstLoaderAborted.resolve() - reject(new DOMException('Aborted', 'AbortError')) - }, - { once: true }, - ) - }) - return 'first' - }, - component: () => ( - <div data-testid="first-page">{firstRoute.useLoaderData()}</div> - ), - pendingComponent: () => ( - <div data-testid="first-pending">Pending first route</div> - ), - errorComponent: ({ error }) => { - firstErrorComponentRendered(error) - return <div data-testid="first-error">{String(error)}</div> - }, - }) - const secondRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/second', - loader: async () => { - secondLoaderStarted.resolve() - await secondLoaderGate - return 'second' - }, - component: () => ( - <div data-testid="second-page">{secondRoute.useLoaderData()}</div> - ), - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute, firstRoute, secondRoute]), - history: createMemoryHistory({ initialEntries: ['/'] }), - defaultPreload: false, - }) - - render(<RouterProvider router={router} />) - 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<void> - 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 deleted file mode 100644 index 8edf32c133..0000000000 --- a/packages/react-router/tests/issue-7367-pending-min-redirect.test.tsx +++ /dev/null @@ -1,203 +0,0 @@ -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: () => <Outlet />, - pendingMs: 0, - pendingMinMs: 100, - pendingComponent: () => <div data-testid="pending">loading</div>, - errorComponent: ({ error }) => ( - <pre data-testid="root-error">{String(error)}</pre> - ), - beforeLoad: async () => { - await sleep(50) - if (!hasRedirected) { - hasRedirected = true - throw redirect({ to: '/welcome', replace: true }) - } - }, - }) - - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () => <div data-testid="index-page">Index</div>, - }) - - const welcomeRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/welcome', - component: () => <div data-testid="welcome-page">Welcome</div>, - }) - - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute, welcomeRoute]), - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - - render(<RouterProvider router={router} />) - - // 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<void>() - let shouldRedirect = true - - const rootRoute = createRootRoute({ - component: Outlet, - pendingMs: 0, - pendingMinMs: 100, - pendingComponent: () => <div data-testid="pending">loading</div>, - beforeLoad: async () => { - if (shouldRedirect) { - shouldRedirect = false - await redirectReady - throw redirect({ to: '/welcome', replace: true }) - } - }, - }) - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () => <div>Index</div>, - }) - const welcomeRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/welcome', - component: () => <div data-testid="welcome-page">Welcome</div>, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute, welcomeRoute]), - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - - try { - render(<RouterProvider router={router} />) - 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<void>() - const rootRoute = createRootRoute({ component: Outlet }) - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () => <div data-testid="index-page">Index</div>, - }) - const sourceRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/source', - pendingMs: 0, - pendingMinMs: 100, - pendingComponent: () => <div data-testid="pending">loading</div>, - beforeLoad: async () => { - await redirectReady - throw redirect({ to: '/welcome', replace: true }) - }, - }) - const welcomeRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/welcome', - component: () => <div data-testid="welcome-page">Welcome</div>, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute, sourceRoute, welcomeRoute]), - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - - render(<RouterProvider router={router} />) - 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 deleted file mode 100644 index 23bc0aa5f3..0000000000 --- a/packages/react-router/tests/issue-7635-error-head-after-navigation.test.tsx +++ /dev/null @@ -1,104 +0,0 @@ -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(<HeadContent />, document.head)} - <Link to="/child" search={{ fail: true }}> - Fail app load - </Link> - <Outlet /> - </> - ), - }) - const appRoute = createRoute({ - getParentRoute: () => rootRoute, - id: '_app', - validateSearch: (search: Record<string, unknown>) => ({ - 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 ( - <div data-testid="app-error"> - {error instanceof Error ? error.message : String(error)} - </div> - ) - }, - }) - const childRoute = createRoute({ - getParentRoute: () => appRoute, - path: '/child', - head: childHead, - component: () => <div data-testid="child-content">Child content</div>, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([appRoute.addChildren([childRoute])]), - history: createMemoryHistory({ - initialEntries: ['/child?fail=false'], - }), - }) - - render(<RouterProvider router={router} />) - - 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 deleted file mode 100644 index e80f073896..0000000000 --- a/packages/react-router/tests/issue-7638-invalidate-transition-error.test.tsx +++ /dev/null @@ -1,192 +0,0 @@ -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: () => <Outlet /> }) - const parentAction = vi.fn() - const secondChildLoad = createControlledPromise<void>() - let invalidation: Promise<void> | undefined - - const testRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/test', - component: function TestComponent() { - testRoute.useLoaderData() - const router = useRouter() - const [isPending, startTransition] = React.useTransition() - return ( - <div> - <button - data-testid="invalidate" - disabled={isPending} - onClick={() => - startTransition(() => { - invalidation = router.invalidate() - return invalidation - }) - } - > - {isPending ? 'pending' : 'invalidate'} - </button> - <button data-testid="parent-action" onClick={parentAction}> - parent action - </button> - <Outlet /> - </div> - ) - }, - }) - - 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 <div>child content</div> - }, - }) - - let errorRenders = 0 - const router = createRouter({ - routeTree: rootRoute.addChildren([testRoute.addChildren([testIndexRoute])]), - history: createMemoryHistory({ initialEntries: ['/test'] }), - defaultErrorComponent: (props: ErrorComponentProps) => { - errorRenders++ - return ( - <div data-testid="error-ui"> - error:{' '} - {props.error instanceof Error - ? props.error.message - : String(props.error)} - </div> - ) - }, - }) - - 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(<RouterProvider router={router} />) - - 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 deleted file mode 100644 index 54f6c19c47..0000000000 --- a/packages/react-router/tests/issue-7964-param-parsing-loader.test.tsx +++ /dev/null @@ -1,107 +0,0 @@ -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: () => <div>Home page</div>, - }) - 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 ( - <> - <div data-testid="params"> - Params have {params.parsedParam.recordName} with revision{' '} - {params.parsedParam.revisionNumber} - </div> - <div data-testid="loader-data">Loader data is {loaderData}</div> - </> - ) - }, - }) - const routeTree = rootRoute.addChildren([ - indexRoute, - parsedParamRoute.addChildren([parsedParamIndexRoute]), - ]) - const router = createRouter({ - routeTree, - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - - render(<RouterProvider router={router} />) - 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 deleted file mode 100644 index 04d762df64..0000000000 --- a/packages/react-router/tests/issue-7986-retained-pending.test.tsx +++ /dev/null @@ -1,1019 +0,0 @@ -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<void>((resolve) => setTimeout(resolve, navigationDelay)) -} - -function deferred() { - let resolve!: () => void - const promise = new Promise<void>((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<string, unknown>): { tab?: string } => - typeof search.tab === 'string' ? { tab: search.tab } : {}, - component: Project, - }) - - function Project() { - const { projectId } = projectRoute.useParams() - const { tab } = projectRoute.useSearch() - return ( - <div data-testid="content"> - project={projectId} tab={tab ?? 'default'} - </div> - ) - } - - const router = createRouter({ - routeTree: rootRoute.addChildren([layoutRoute.addChildren([projectRoute])]), - history: createMemoryHistory({ initialEntries: ['/projects/p1'] }), - defaultPendingComponent: () => <div data-testid="pending">Pending</div>, - defaultPendingMs: 0, - defaultPendingMinMs: 1, - }) - - return { - router, - navigationBeforeLoadStarted, - } -} - -test('a search-only navigation retains successful UI while beforeLoad reruns', async () => { - const { router, navigationBeforeLoadStarted } = setup() - render(<RouterProvider router={router} />) - expect(await screen.findByTestId('content')).toHaveTextContent( - 'project=p1 tab=default', - ) - - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) - let navigation!: Promise<void> - 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(<RouterProvider router={router} />) - expect(await screen.findByTestId('content')).toHaveTextContent( - 'project=p1 tab=default', - ) - - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) - let navigation!: Promise<void> - 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<string, unknown>): { 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: () => ( - <div data-testid="content"> - {pageRoute.useLoaderData()} tab= - {pageRoute.useSearch().tab ?? 'default'} - </div> - ), - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([pageRoute]), - history: createMemoryHistory({ initialEntries: ['/page'] }), - defaultPendingComponent: () => <div data-testid="pending">Pending</div>, - defaultPendingMs: 0, - defaultPendingMinMs: 1, - }) - - render(<RouterProvider router={router} />) - expect(await screen.findByTestId('content')).toHaveTextContent( - 'initial tab=default', - ) - - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) - let navigation!: Promise<void> - 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: () => ( - <div data-testid="content">{pageRoute.useLoaderData()}</div> - ), - pendingComponent: () => <div data-testid="pending">Pending</div>, - errorComponent: () => <div data-testid="error">Failed</div>, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([pageRoute]), - history: createMemoryHistory({ initialEntries: ['/page'] }), - defaultPendingMs: 0, - defaultPendingMinMs: 1, - }) - - render(<RouterProvider router={router} />) - expect(await screen.findByTestId('error')).toBeInTheDocument() - - await router.preloadRoute({ to: '/page' }) - expect(loaderCalls).toBe(2) - expect(screen.getByTestId('error')).toBeInTheDocument() - - let navigation!: Promise<void> - 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: () => ( - <div data-testid="content">{pageRoute.useLoaderData()}</div> - ), - pendingComponent: () => <div data-testid="pending">Pending</div>, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([pageRoute]), - history: createMemoryHistory({ initialEntries: ['/page'] }), - defaultPendingMs: 0, - defaultPendingMinMs: 1, - }) - - render(<RouterProvider router={router} />) - 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<void> - 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: () => <div data-testid="error">Parent failed</div>, - }) - 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: () => ( - <div data-testid="content">{childRoute.useLoaderData()}</div> - ), - pendingComponent: () => <div data-testid="pending">Pending child</div>, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), - history: createMemoryHistory({ initialEntries: ['/parent/child'] }), - defaultPendingMs: 0, - defaultPendingMinMs: 1, - }) - - render(<RouterProvider router={router} />) - 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<void> - 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( - () => <div data-testid="missing">Missing</div>, - { - 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: () => <div data-testid="pending">Pending root</div>, - notFoundComponent: Missing, - }) - const pageRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/page', - component: () => <div data-testid="content">Page</div>, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([pageRoute]), - history: createMemoryHistory({ initialEntries: ['/page'] }), - defaultPendingMs: 0, - defaultPendingMinMs: 1, - }) - - render(<RouterProvider router={router} />) - expect(await screen.findByTestId('content')).toBeInTheDocument() - - let navigation!: Promise<void> - 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( - () => <div data-testid="missing">Missing</div>, - { - preload: () => { - terminalStarted.resolve() - return terminalReady.promise - }, - }, - ) - const rootRoute = createRootRoute({ - pendingMs: 0, - pendingMinMs: 0, - pendingComponent: () => <div data-testid="pending">Pending root</div>, - notFoundComponent: Missing, - }) - const router = createRouter({ - routeTree: rootRoute, - history: createMemoryHistory({ initialEntries: ['/missing'] }), - }) - - render(<RouterProvider router={router} />) - 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: () => <div data-testid="root-missing">Root missing</div>, - }) - const parentRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/parent', - beforeLoad: async () => { - if (++parentLoads > 1) { - parentReloadStarted.resolve() - await parentReload.promise - } - }, - component: () => ( - <div> - <div data-testid="parent-content">Parent content</div> - <Outlet /> - </div> - ), - pendingComponent: () => ( - <div data-testid="parent-pending">Parent pending</div> - ), - notFoundComponent: () => ( - <div data-testid="parent-missing">Parent missing</div> - ), - }) - const childRoute = createRoute({ - getParentRoute: () => parentRoute, - path: '/child', - }).lazy(async () => { - lazyStarted.resolve() - await lazyRoute.promise - return createLazyRoute('/parent/child')({ - notFoundComponent: () => ( - <div data-testid="child-missing">Child missing</div> - ), - }) - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), - history: createMemoryHistory({ initialEntries: ['/parent'] }), - defaultPendingComponent: () => ( - <div data-testid="default-pending">Pending</div> - ), - defaultPendingMs: 0, - defaultPendingMinMs: 1, - }) - - render(<RouterProvider router={router} />) - expect(await screen.findByTestId('parent-content')).toBeVisible() - - let navigation!: Promise<void> - 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: () => ( - <div data-testid="content">{pageRoute.useLoaderData()}</div> - ), - pendingComponent: () => <div data-testid="page-pending">Page pending</div>, - }) - const otherRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/other', - loader: async () => { - otherStarted.resolve() - await otherLoader.promise - }, - pendingComponent: () => ( - <div data-testid="other-pending">Other pending</div> - ), - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([pageRoute, otherRoute]), - history: createMemoryHistory({ initialEntries: ['/page'] }), - defaultPendingMs: 0, - defaultPendingMinMs: 1, - }) - - render(<RouterProvider router={router} />) - 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<void> - 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<string, unknown>): { 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: () => ( - <div> - <div data-testid="user">{aRoute.useRouteContext().user}</div> - <Outlet /> - </div> - ), - }) - 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: () => <div data-testid="source">Source</div>, - }) - const eRoute = createRoute({ - getParentRoute: () => aRoute, - path: 'e', - component: () => ( - <div> - <div data-testid="e-user">{eRoute.useRouteContext().user}</div> - <Outlet /> - </div> - ), - }) - const fRoute = createRoute({ - getParentRoute: () => eRoute, - path: 'f', - loader: async () => { - pendingStarted.resolve() - await pendingReady.promise - }, - pendingComponent: () => ( - <div data-testid="f-pending"> - F pending for {fRoute.useRouteContext().user} - </div> - ), - component: Outlet, - }) - const gRoute = createRoute({ - getParentRoute: () => fRoute, - path: 'g', - component: () => <div data-testid="hidden-g">G</div>, - }) - 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(<RouterProvider router={router} />) - expect(await screen.findByTestId('source')).toBeVisible() - expect(screen.getByTestId('user')).toHaveTextContent('Ada') - - let navigation!: Promise<void> - 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<void>() - const parentReload = createControlledPromise<void>() - const parentComponent = createControlledPromise<void>() - const childLoader = createControlledPromise<void>() - let parentLoads = 0 - let parentPreloads = 0 - - const rootRoute = createRootRoute({ component: Outlet }) - const Parent = Object.assign( - () => ( - <div data-testid="parent-content"> - {parentRoute.useLoaderData()} - <Outlet /> - </div> - ), - { - 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: () => ( - <div data-testid="parent-pending">Parent pending</div> - ), - } - : {}), - }) - const sourceRoute = createRoute({ - getParentRoute: () => parentRoute, - path: 'source', - component: () => <div data-testid="source">Source</div>, - }) - const childOptions = createLazyRoute('/parent/child')({ - pendingComponent: () => ( - <div data-testid="child-pending">Child pending</div> - ), - component: () => <div data-testid="child">Child</div>, - }) - const childLazy = createControlledPromise<typeof childOptions>() - 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(<RouterProvider router={router} />) - 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<void>() - const guardReady = createControlledPromise<void>() - const childReady = createControlledPromise<void>() - 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: () => <div data-testid="guard-error">Guard error</div>, - }) - const sourceRoute = createRoute({ - getParentRoute: () => layoutRoute, - path: '/source', - component: () => <div data-testid="source">Source</div>, - }) - const childRoute = createRoute({ - getParentRoute: () => layoutRoute, - path: '/child', - loader: async () => { - childLoads++ - await childReady - }, - pendingMs: 0, - pendingMinMs: 0, - pendingComponent: () => <div data-testid="child-pending">Pending</div>, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([ - layoutRoute.addChildren([sourceRoute, childRoute]), - ]), - history: createMemoryHistory({ initialEntries: ['/source'] }), - }) - - render(<RouterProvider router={router} />) - 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 deleted file mode 100644 index 69399d26c0..0000000000 --- a/packages/react-router/tests/issue-8115-context.test.tsx +++ /dev/null @@ -1,785 +0,0 @@ -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 ( - <div> - <div data-testid="parent-generation">{parentGeneration}</div> - <div data-testid="child-snapshot">{childSnapshotOfParent}</div> - <div data-testid="collision">{collision}</div> - </div> - ) - }, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([childRoute]), - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - - render(<RouterProvider router={router} />) - - 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: () => ( - <div data-testid="child-generation"> - {childRoute.useRouteContext().generation} - </div> - ), - errorComponent: ({ error }) => { - renderedError = error - const context = childRoute.useRouteContext() - - return ( - <div data-testid="child-error-generation">{context.generation}</div> - ) - }, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), - history: createMemoryHistory({ initialEntries: ['/parent/child'] }), - }) - - render(<RouterProvider router={router} />) - - 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<ProviderContext>()() - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - context: ({ context }) => ({ - derivedFromProvider: `derived:${context.providerValue}`, - collision: `route-cached:${context.providerValue}`, - }), - component: () => ( - <pre data-testid="full-context"> - {JSON.stringify(indexRoute.useRouteContext())} - </pre> - ), - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute]), - history: createMemoryHistory({ initialEntries: ['/'] }), - context: providerA, - }) - - const view = render(<RouterProvider router={router} context={providerA} />) - expect(await screen.findByTestId('full-context')).toHaveTextContent( - JSON.stringify({ - providerValue: 'A', - collision: 'route-cached:A', - derivedFromProvider: 'derived:A', - }), - ) - - view.rerender(<RouterProvider router={router} context={providerB} />) - 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: () => <div>Home</div>, - }) - 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 ( - <div data-testid="context"> - {JSON.stringify({ parentValue, childValue })} - </div> - ) - }, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([ - indexRoute, - parentRoute.addChildren([childRoute]), - ]), - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - - render(<RouterProvider router={router} />) - 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<string, unknown>) => ({ - 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 ( - <div> - Parent: {context.parentVersion}; cached child: {context.childSnapshot} - </div> - ) - }, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), - history: createMemoryHistory({ - initialEntries: ['/parent/child?version=1'], - }), - }) - - render(<RouterProvider router={router} />) - - 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<string | undefined> = [] - let clientContextAttempts = 0 - let serverPhase = true - - const createRouteTree = () => { - const rootRoute = createRootRoute({ - component: () => ( - <> - <Outlet /> - <Scripts /> - </> - ), - }) - 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 ( - <div data-testid="route-success"> - Locale: {context.locale ?? 'missing'} - </div> - ) - }, - errorComponent: ({ error }) => ( - <div data-testid="route-error"> - {error instanceof Error ? error.message : String(error)} - </div> - ), - }) - - 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: ( - <html> - <head /> - <body> - <RouterServer router={router} /> - </body> - </html> - ), - }), - ) - 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<Error> = [] - let root: ReturnType<typeof hydrateRoot> | undefined - - try { - await hydrate(clientRouter) - await act(async () => { - root = hydrateRoot(container, <RouterProvider router={clientRouter} />, { - 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<void>() - const childReload = createControlledPromise<void>() - let parentGeneration = 0 - let childLoads = 0 - - const rootRoute = createRootRoute({ component: Outlet }) - const parentRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/parent', - beforeLoad: () => ({ generation: ++parentGeneration }), - component: () => ( - <div> - <div data-testid="parent-generation"> - Parent generation {parentRoute.useRouteContext().generation} - </div> - <Outlet /> - </div> - ), - }) - 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: () => ( - <div data-testid="child-pending-generation"> - Child generation {childRoute.useRouteContext().inheritedGeneration} - </div> - ), - component: () => ( - <div data-testid="child-generation"> - Child generation {childRoute.useRouteContext().inheritedGeneration} - </div> - ), - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), - history: createMemoryHistory({ initialEntries: ['/parent/child'] }), - }) - - render(<RouterProvider router={router} />) - 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<void> | 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 ( - <> - <output data-testid="match-id">{matchId}</output> - <output data-testid="snapshot"> - location: {location.state.issue8115Revision}; inherited:{' '} - {context.inheritedRevision}; self: {context.selfRevision} - </output> - <button - onClick={() => { - void navigate({ - to: '/', - state: { issue8115Revision: 'new' }, - }) - }} - > - Update state - </button> - </> - ) - } - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute]), - history, - }) - - render(<RouterProvider router={router} />) - - 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<void>((resolve) => { - resolveChildLoader = resolve - }) - const rootRenderValues: Array<string | undefined> = [] - - const rootRoute = createRootRoute({ - context: () => ({ locale: 'en' }), - component: () => { - const locale = rootRoute.useRouteContext().locale - rootRenderValues.push(locale) - - return ( - <main> - <p data-testid="root-locale">Locale: {locale ?? 'missing'}</p> - <Outlet /> - </main> - ) - }, - }) - const childRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - loader: () => childLoader, - pendingMs: 0, - pendingComponent: () => <p role="status">Loading child</p>, - component: () => <p>Child content</p>, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([childRoute]), - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - - render(<RouterProvider router={router} />) - - 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<string, unknown>) => ({ - 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 ( - <> - <div data-testid="match-id">{matchId}</div> - <div data-testid="current-search">{search.revision}</div> - <div data-testid="inherited-context">{context.inheritedRevision}</div> - <div data-testid="cached-self-context"> - {context.cachedSelfRevision} - </div> - </> - ) - }, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), - history: createMemoryHistory({ - initialEntries: ['/parent/child?revision=one'], - }), - }) - - render(<RouterProvider router={router} />) - - 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 deleted file mode 100644 index f615bba8d9..0000000000 --- a/packages/react-router/tests/issue-8128-context.test.tsx +++ /dev/null @@ -1,116 +0,0 @@ -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<string | undefined> = [] - - 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 ( - <> - <output data-testid="root-locale"> - Locale: {context.locale ?? 'missing'} - </output> - <Outlet /> - </> - ) - }, - notFoundComponent: () => <div>Not found</div>, - }) - const dashboardRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/dashboard', - component: () => <div>Dashboard</div>, - }) - - const router = createRouter({ - routeTree: rootRoute.addChildren([dashboardRoute]), - history: createMemoryHistory({ - initialEntries: ['/any-not-found-url'], - }), - defaultPendingComponent: () => <div>Loading</div>, - 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<string, unknown> } = { - 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(<RouterProvider router={router} />) - - expect(router.state.matches[0]).toMatchObject({ - status: 'success', - _notFound: true, - context: { locale: 'en' }, - }) - expect(screen.getByText('Not found')).toBeInTheDocument() - - let navigation!: Promise<void> - 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 deleted file mode 100644 index 58c3d8cbc7..0000000000 --- a/packages/react-router/tests/issue-8128-source-notfound-retention-boundary.test.tsx +++ /dev/null @@ -1,305 +0,0 @@ -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<void>((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: () => ( - <section> - <h1>Agent operations</h1> - <Outlet /> - </section> - ), - notFoundComponent: () => <p>Agent page not found</p>, - }) - const agentsRoute = createRoute({ - getParentRoute: () => agentsLayoutRoute, - path: '/agents', - beforeLoad: async () => { - if (gateNextBeforeLoad) { - gateNextBeforeLoad = false - beforeLoadStarted.resolve() - await beforeLoadGate.promise - } - }, - pendingMs: 0, - pendingMinMs: 0, - pendingComponent: () => <p role="status">Loading agents</p>, - component: () => <p>Agents directory</p>, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([ - agentsLayoutRoute.addChildren([agentsRoute]), - ]), - history: createMemoryHistory({ initialEntries: ['/agents'] }), - }) - - let navigation: Promise<void> | undefined - try { - render(<RouterProvider router={router} />) - - 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: () => ( - <section> - <h1>Workspace</h1> - <Outlet /> - </section> - ), - notFoundComponent: () => <p>Workspace page not found</p>, - 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: () => <p role="status">Loading workspace</p>, - }) - const agentsRoute = createRoute({ - getParentRoute: () => workspaceLayoutRoute, - path: '/agents', - validateSearch: (search: Record<string, unknown>) => ({ - 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: () => <p role="status">Loading agents destination</p>, - component: () => ( - <section> - <h2>Agents area</h2> - <Outlet /> - </section> - ), - }) - const groupsRoute = createRoute({ - getParentRoute: () => agentsRoute, - path: 'groups', - beforeLoad: async () => { - groupsBeforeLoadStarted.resolve() - await groupsBeforeLoadGate.promise - }, - pendingMs: 0, - pendingMinMs: 0, - pendingComponent: () => <p role="status">Loading groups</p>, - component: Outlet, - }) - const groupsBoundaryRoute = createRoute({ - getParentRoute: () => groupsRoute, - id: '_groups', - component: Outlet, - notFoundComponent: () => <p>Group page not found</p>, - }) - const knownGroupRoute = createRoute({ - getParentRoute: () => groupsBoundaryRoute, - path: 'known', - component: () => <p>Known group</p>, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([ - workspaceLayoutRoute.addChildren([ - agentsRoute.addChildren([ - groupsRoute.addChildren([ - groupsBoundaryRoute.addChildren([knownGroupRoute]), - ]), - ]), - ]), - ]), - history: createMemoryHistory({ initialEntries: ['/agents'] }), - }) - - let deeperNavigation: Promise<void> | undefined - let agentsNavigation: Promise<void> | undefined - try { - render(<RouterProvider router={router} />) - 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<void> => navigation !== undefined, - ), - ) - }) - } -}) diff --git a/packages/react-router/tests/jest-dom.setup.ts b/packages/react-router/tests/jest-dom.setup.ts deleted file mode 100644 index 8f7cbf15be..0000000000 --- a/packages/react-router/tests/jest-dom.setup.ts +++ /dev/null @@ -1,18 +0,0 @@ -import * as jestDomMatchers from '@testing-library/jest-dom/matchers' -import { expect } from 'vitest' -import type { TestingLibraryMatchers } from '@testing-library/jest-dom/matchers' - -// Workaround for Vitest 5: remove once testing-library/jest-dom#742 is merged -// and released, and go back to `import '@testing-library/jest-dom/vitest'`. -// That entry imports `vitest` from its own install location, which can resolve -// a different Vitest copy than the one running these tests, and its types -// augment Vitest 4's `Assertion<T>` instead of Vitest 5's `Matchers<R, T>`. -// 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<R, T> extends TestingLibraryMatchers<unknown, R> {} -} diff --git a/packages/react-router/tests/lazy/error.tsx b/packages/react-router/tests/lazy/error.tsx index 271f6a058e..6ef7036e33 100644 --- a/packages/react-router/tests/lazy/error.tsx +++ b/packages/react-router/tests/lazy/error.tsx @@ -3,10 +3,6 @@ import { createLazyRoute } from '../../src' export function Route(id: string) { return createLazyRoute(id)({ component: () => <div>About route content</div>, - errorComponent: ({ error }) => ( - <div> - Lazy Error: {error instanceof Error ? error.message : String(error)} - </div> - ), + errorComponent: ({ error }) => <div>Lazy Error: {error.message}</div>, }) } diff --git a/packages/react-router/tests/lazy/normal.tsx b/packages/react-router/tests/lazy/normal.tsx index 675deb83f3..1addf96c74 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: () => <h1 data-testid="lazy-route-page">I'm a normal route</h1>, + component: () => <h1>I'm a normal route</h1>, }) } diff --git a/packages/react-router/tests/link-departing-scope.test.tsx b/packages/react-router/tests/link-departing-scope.test.tsx deleted file mode 100644 index 04d0c3f32d..0000000000 --- a/packages/react-router/tests/link-departing-scope.test.tsx +++ /dev/null @@ -1,1122 +0,0 @@ -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<void> - resolve: () => void -} - -function deferred(): Deferred { - let resolve!: () => void - const promise = new Promise<void>((r) => (resolve = r)) - return { promise, resolve } -} - -type Gates = Partial<Record<'a' | 'b' | 'items', Deferred>> - -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<unknown> = [] - // The `x` of every location the `a-next` link derives from. - const nextFrom: Array<unknown> = [] - 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: () => ( - <> - <Link to="/b" data-testid="root-b"> - root b - </Link> - <Outlet /> - </> - ), - }) - const layout = createRoute({ - getParentRoute: () => root, - id: '_layout', - component: () => ( - <> - <Link to="/b" data-testid="layout-b"> - layout b - </Link> - <Outlet /> - </> - ), - }) - function AComponent() { - const [hash, setHash] = React.useState<string | undefined>(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 ( - <> - <h1>A page</h1> - <Link - to="/a" - data-testid="a-self" - search={(prev: any) => { - counts.aUpdater++ - return prev - }} - > - {() => { - counts.aRenders++ - return 'a self' - }} - </Link> - <Link to="." hash={hash} data-testid="a-dot"> - a dot - </Link> - <Link - to="/a" - search={(prev: any) => { - nextFrom.push(prev.x) - return { x: `${prev.x}-next` } - }} - preload="intent" - preloadDelay={0} - data-testid="a-next" - > - a next - </Link> - {renderPreload ? ( - <Link - to="/a" - search={(prev: any) => ({ x: `${prev.x}-render` })} - preload="render" - data-testid="a-render" - > - a render - </Link> - ) : null} - {extra ? ( - <Link to="." search={(prev: any) => prev} data-testid="a-extra"> - a extra - </Link> - ) : null} - {gone ? null : ( - <Link - to="/a" - data-testid="a-gone" - search={(prev: any) => { - counts.goneUpdater++ - return prev - }} - > - a gone - </Link> - )} - <React.Suspense fallback={<span>suspended</span>}> - <Link - to="/a" - data-testid="a-suspended" - search={(prev: any) => { - counts.suspendedUpdater++ - return prev - }} - > - a suspended - </Link> - <Suspender /> - </React.Suspense> - </> - ) - } - 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: () => <h1>B page</h1>, - }) - const c = createRoute({ - getParentRoute: () => root, - path: '/c', - component: () => <h1>C page</h1>, - }) - const items = createRoute({ - getParentRoute: () => root, - path: '/items/$id', - loader: () => gates.items?.promise, - component: () => ( - <> - <h1>Items page</h1> - <Link to="/items/$id" params={{ id: '1' }} data-testid="item-1"> - item 1 - </Link> - <Link to="/items/$id" params={{ id: '2' }} data-testid="item-2"> - item 2 - </Link> - </> - ), - }) - - const router = createRouter({ - routeTree: root.addChildren([layout.addChildren([a, b]), c, items]), - history: createMemoryHistory({ initialEntries: [initial] }), - }) - - beforeRender?.(router) - const app = <RouterProvider router={router} /> - render(strict ? <React.StrictMode>{app}</React.StrictMode> : 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<unknown> = [] - 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 }) => ( - <> - <Link to="/b" data-testid="wrap-b"> - wrap b - </Link> - {children} - </> - ) - router.update({ ...router.options, InnerWrap }) - render(<RouterProvider router={router} />) - 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: () => ( - <Link - to="/photo" - search={(prev: any) => ({ id: prev.x })} - hash - mask={ - kind === 'mask' - ? ({ to: '.', search: true, hash: true } as any) - : undefined - } - data-testid="masked" - > - masked - </Link> - ), - }) - const b = createRoute({ - getParentRoute: () => root, - path: '/b', - loader: () => gate.b?.promise, - component: () => <h1>B page</h1>, - }) - const photo = createRoute({ - getParentRoute: () => root, - path: '/photo', - component: () => <h1>Photo page</h1>, - }) - 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(<RouterProvider router={router} />) - 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: () => ( - <> - <Link - to="/photo" - search={{ id: 1 }} - mask={ - kind === 'mask' - ? ({ to: '/posts', search: { from: 'photo' } } as any) - : undefined - } - data-testid="masked" - > - {() => { - renders++ - return 'masked' - }} - </Link> - <Outlet /> - </> - ), - }) - const routes = ['a', 'b', 'photo', 'posts'].map((path) => - createRoute({ - getParentRoute: () => root, - path: `/${path}`, - component: () => <h1>{path} page</h1>, - }), - ) - 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(<RouterProvider router={router} />) - 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<WeakRef<object>>) => - 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: () => ( - <> - <Link to="/b" data-testid="root-b"> - root b - </Link> - <Outlet /> - </> - ), - }) - const a = createRoute({ - getParentRoute: () => root, - path: '/a', - component: () => ( - <> - <h1>A page</h1> - <Link to="." search={(prev: any) => prev} data-testid="a-self"> - a self - </Link> - </> - ), - }) - const b = createRoute({ - getParentRoute: () => root, - path: '/b', - component: () => <h1>B page</h1>, - }) - const router = createRouter({ - routeTree: root.addChildren([a, b]), - history: createMemoryHistory({ initialEntries: ['/a'] }), - }) - render(<RouterProvider router={router} />) - 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<WeakRef<object>> = [] - 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<unknown> = [] - const root = createRootRoute({ component: () => <Outlet /> }) - const a = createRoute({ - getParentRoute: () => root, - path: '/a', - component: () => ( - <> - <h1>A page</h1> - <Link - to="/b" - state={true} - preload="intent" - preloadDelay={0} - data-testid="inherit" - > - inherit - </Link> - <Link - to="/b" - state={(prev: any) => ({ tag: `${prev.tag}-updated` }) as any} - data-testid="updater" - > - updater - </Link> - </> - ), - }) - const b = createRoute({ - getParentRoute: () => root, - path: '/b', - loader: ({ location }) => { - bLoads.push((location.state as any).tag) - }, - component: () => <h1>B page</h1>, - }) - const router = createRouter({ - routeTree: root.addChildren([a, b]), - history: createMemoryHistory({ initialEntries: ['/a'] }), - }) - render(<RouterProvider router={router} />) - 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 deleted file mode 100644 index 31daa6d551..0000000000 --- a/packages/react-router/tests/link-destination.test.tsx +++ /dev/null @@ -1,498 +0,0 @@ -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<string, unknown>) => { id: string }, - ) { - const rootRoute = createRootRoute({ - component: () => ( - <> - <Link - to="/target/$id" - params={params} - search={{}} - hash="details" - activeOptions={{ includeSearch: false }} - data-testid="fixed-link" - > - Target - </Link> - <Outlet /> - </> - ), - }) - 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<typeof routeTree, 'always' | 'never'>({ - routeTree, - history: createMemoryHistory({ initialEntries: ['/items/one'] }), - }) - return { router, rootRoute } - } - - test('preserves a fixed destination when unrelated location inputs change', async () => { - const { router } = setupFixedLink() - render(<RouterProvider router={router} />) - - 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(<RouterProvider router={router} />) - - 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<string, unknown>) => ({ - id: `${params.source}-${params.id}`, - })) - const { router } = setupFixedLink({ id: 'fixed' }, stringify) - render(<RouterProvider router={router} />) - - 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(<RouterProvider router={router} />) - - 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 ( - <> - <button onClick={() => rerender((n) => n + 1)}>Rerender</button> - <button onClick={() => setPage((n) => n + 1)}>Next page</button> - <Link - to="/items/$source" - params={{ source: 'one' }} - search={{ filters: { page }, tags: ['a'] }} - data-testid="nested-link" - > - Items - </Link> - <Outlet /> - </> - ) - }, - }) - 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(<RouterProvider router={router} />) - - 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 ( - <> - <button onClick={() => setValue('two')}>Change target</button> - <Link - to="/items/$id" - params={{ id: value }} - hash={value} - data-testid="changing-link" - > - Item - </Link> - <Outlet /> - </> - ) - }, - }) - const itemsRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/items/$id', - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([itemsRoute]), - history: createMemoryHistory({ initialEntries: ['/items/one'] }), - }) - render(<RouterProvider router={router} />) - - 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: () => ( - <> - <Link to="/items/$id" params={{}} data-testid="inherited-link"> - {({ isActive }) => (isActive ? 'Current item' : 'Another item')} - </Link> - <Outlet /> - </> - ), - }) - const itemsRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/items/$id', - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([itemsRoute]), - history: createMemoryHistory({ initialEntries: ['/items/one'] }), - }) - render(<RouterProvider router={router} />) - - 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 ( - <> - <button onClick={() => setId('two')}>Change mask</button> - <Link - to="/target/$id" - params={{ id: 'fixed' }} - mask={{ to: '/visible/$id', params: { id } }} - data-testid="prop-mask" - /> - <Link - to="/target/$id" - params={{ id: 'fixed' }} - mask={inheritedMask as any} - data-testid="inherited-mask" - /> - <Outlet /> - </> - ) - }, - }) - 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(<RouterProvider router={router} />) - - 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<string> = [] - const unblock = router.history.block({ - blockerFn: ({ nextLocation }) => { - blockedTargets.push(nextLocation.pathname) - return true - }, - }) - function Example() { - const [reload, setReload] = React.useState(false) - return ( - <> - <button onClick={() => setReload(true)}>Enable reload</button> - <Link to="/b" reloadDocument={reload}> - Target - </Link> - </> - ) - } - render( - <RouterContextProvider router={router}> - <Example /> - </RouterContextProvider>, - ) - 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 ( - <> - <button onClick={() => setChanged(true)}>Change href</button> - <Link to="/a" href={changed ? '/b' : '/a'}> - Target - </Link> - </> - ) - } - render( - <RouterContextProvider router={router}> - <Example /> - </RouterContextProvider>, - ) - 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 ( - <> - <button onClick={() => setHref('/c')}>Retarget</button> - <Link to="/a" href={href} preload="intent" preloadDelay={50}> - Target - </Link> - </> - ) - } - render( - <RouterContextProvider router={router}> - <Example /> - </RouterContextProvider>, - ) - 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 deleted file mode 100644 index 0095d450a5..0000000000 --- a/packages/react-router/tests/link-events.test.tsx +++ /dev/null @@ -1,190 +0,0 @@ -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) => ( - <RouterContextProvider router={router}> - <Link to={to} onClick={onClick}> - Target - </Link> - </RouterContextProvider> - ) - 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) => ( - <RouterContextProvider router={router}> - <Link to={to} preload="intent" preloadDelay={50}> - Target - </Link> - </RouterContextProvider> - ) - 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 }) => ( - <RouterContextProvider router={router}> - {children} - </RouterContextProvider> - ), - }, - ) - 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<HTMLAnchorElement> & - React.TouchEvent<HTMLAnchorElement> & - React.FocusEvent<HTMLAnchorElement>, - ) - 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 deleted file mode 100644 index 5838d0b8c3..0000000000 --- a/packages/react-router/tests/link-href-safety.test.tsx +++ /dev/null @@ -1,90 +0,0 @@ -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 = ( - <RouterContextProvider router={router}> - <Link - to="/safe" - preload="intent" - preloadDelay={0} - activeProps={activeProps} - inactiveProps={inactiveProps} - > - {({ isActive }) => String(isActive)} - </Link> - </RouterContextProvider> - ) - 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 deleted file mode 100644 index 497464b3f8..0000000000 --- a/packages/react-router/tests/link-hydration.test.tsx +++ /dev/null @@ -1,203 +0,0 @@ -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) => ( - <RouterContextProvider router={contextRouter}> - <Link - to="/target" - hash="other" - activeOptions={{ includeHash }} - activeProps={{ title: 'active' }} - inactiveProps={{ title: 'inactive' }} - data-testid="ordinary" - > - {ordinary} - </Link> - <Link - to="/target" - hash="section" - activeOptions={{ includeHash: true }} - activeProps={{ title: 'active' }} - inactiveProps={{ title: 'inactive' }} - data-testid="hash" - > - {hashSensitive} - </Link> - </RouterContextProvider> - ) - 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<typeof hydrateRoot> | 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<void>((done) => { - resolve = done - }) - const ordinary = vi.fn(() => 'ordinary') - const hashSensitive = vi.fn(({ isActive }: { isActive: boolean }) => - String(isActive), - ) - function DeferredLinks() { - if (!ready) { - throw pending - } - return ( - <> - <Link to="/target">{ordinary}</Link> - <Link to="/target" hash="section" activeOptions={{ includeHash: true }}> - {hashSensitive} - </Link> - </> - ) - } - const tree = (router: typeof clientRouter) => ( - <RouterContextProvider router={router}> - <React.Suspense fallback={<p>Loading</p>}> - <DeferredLinks /> - </React.Suspense> - </RouterContextProvider> - ) - 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<typeof hydrateRoot> | 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 deleted file mode 100644 index 873bbf9e7a..0000000000 --- a/packages/react-router/tests/link-memo.test.tsx +++ /dev/null @@ -1,175 +0,0 @@ -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<HTMLAnchorElement, React.ComponentProps<'a'>>( - (props, ref) => { - hostRenders++ - return <a {...props} ref={ref} /> - }, - ) - const CustomLink = createLink(Host) - const router = await createPostsRouter() - - let rerender = () => {} - let setPostId: React.Dispatch<React.SetStateAction<number>> = () => {} - function Parent() { - const [, setTick] = React.useState(0) - const [postId, set] = React.useState(1) - rerender = () => setTick((tick) => tick + 1) - setPostId = set - return ( - <RouterContextProvider router={router}> - <CustomLink - to="/posts/$postId" - params={{ postId: String(postId) }} - activeProps={{ className: 'current' }} - preload={false} - > - Post - </CustomLink> - </RouterContextProvider> - ) - } - const view = render(<Parent />) - 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 <a {...props} ref={ref} /> - }) - 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<string, unknown> = {} - cyclic.self = cyclic - return ( - <RouterContextProvider router={router}> - <CustomLink - to="/posts/$postId" - params={{ postId: '1' }} - payload={cyclic} - > - <span>Post</span> - </CustomLink> - </RouterContextProvider> - ) - } - render(<Parent />) - 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( - <RouterContextProvider router={router}> - <Link ref={ref} to="/posts/$postId" params={{ postId: '1' }}> - Post - </Link> - </RouterContextProvider>, - ) - 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( - <RouterContextProvider router={router}> - <Link ref={next} to="/posts/$postId" params={{ postId: '1' }}> - Post - </Link> - </RouterContextProvider>, - ) - 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( - <RouterContextProvider router={router}> - <Link ref={ref} to="/posts/$postId" params={{ postId: '1' }}> - Post - </Link> - </RouterContextProvider>, - ) - 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 deleted file mode 100644 index 232a0d8633..0000000000 --- a/packages/react-router/tests/link-path-matching.test.tsx +++ /dev/null @@ -1,58 +0,0 @@ -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 = ( - <RouterContextProvider router={router}> - <Link - to={to} - activeOptions={{ exact }} - inactiveProps={{ className: 'inactive' }} - > - {({ isActive }) => String(isActive)} - </Link> - </RouterContextProvider> - ) - 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 deleted file mode 100644 index eee6906265..0000000000 --- a/packages/react-router/tests/link-selector.test.tsx +++ /dev/null @@ -1,192 +0,0 @@ -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( - <RouterContextProvider router={router}> - <Link to="/posts/$id" params={{ id: '1' }} search={{ page: 1 }}> - Post - </Link> - </RouterContextProvider>, - ) - 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 ( - <RouterContextProvider router={router}> - <Link - to="/posts/$id" - params={{ id }} - search={{ page: 1 }} - disabled={disabled} - activeOptions={{ includeSearch }} - > - Post - </Link> - </RouterContextProvider> - ) - } - 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: () => ( - <Link to="/posts/$id" params={{ id: '1' }} search={{}}> - Post - </Link> - ), - }) - const router = createRouter({ - routeTree: root.addChildren([ - createRoute({ getParentRoute: () => root, path: '/posts/$id' }), - ]), - history, - trailingSlash: 'never', - }) - try { - const view = render(<RouterProvider router={router} />) - 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( - <RouterContextProvider router={router}> - <Link to="/posts/$id/" params={{ id: '1' }} activeOptions={{ exact }}> - Post - </Link> - </RouterContextProvider>, - ) - 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 ( - <RouterContextProvider router={currentRouter}> - <Link to={to}>Destination</Link> - </RouterContextProvider> - ) - } - 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 deleted file mode 100644 index ea45a5e974..0000000000 --- a/packages/react-router/tests/link-state-props.test.tsx +++ /dev/null @@ -1,562 +0,0 @@ -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<HTMLAnchorElement>() - const nativeRef = React.createRef<HTMLAnchorElement>() - const CustomLink = createLink( - React.forwardRef<HTMLAnchorElement, AnchorProps>((props, ref) => { - customProps = props - return ( - <a ref={ref} data-testid="custom"> - {props.children} - </a> - ) - }), - ) - 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 = ( - <RouterContextProvider router={router}> - <Link to="/target" type="text/native" disabled ref={nativeRef}> - Native - </Link> - <CustomLink to="/target" type="text/custom" disabled ref={customRef}> - {({ isActive }) => (isActive ? 'Active custom' : 'Inactive custom')} - </CustomLink> - <Probe /> - </RouterContextProvider> - ) - 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) => ( - <a {...props} data-disabled={String(props.disabled)} ref={ref} /> - )), - ) - const router = createRouter({ - routeTree: createRootRoute(), - history: createMemoryHistory(), - }) - const ref = React.createRef<HTMLAnchorElement>() - 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 = ( - <RouterContextProvider router={router}> - <CustomLink - to="javascript:blocked()" - ref={ref} - search={search} - onClick={baseClick} - inactiveProps={inactiveProps} - > - Target - </CustomLink> - </RouterContextProvider> - ) - 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 = ( - <RouterContextProvider router={router}> - <Link - to="javascript:blocked()" - disabled={disabled} - className="base" - style={{ fontWeight: 700 }} - inactiveProps={inactiveProps} - > - {({ isActive }) => String(isActive)} - </Link> - </RouterContextProvider> - ) - 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<typeof hydrateRoot> | 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) => ( - <RouterContextProvider router={router}> - <Link - to={to} - className="base" - style={{ color: 'black', fontWeight: 700 }} - activeProps={activeProps} - inactiveProps={inactiveProps} - > - Target - </Link> - </RouterContextProvider> - ) - 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) => ( - <RouterContextProvider router={router}> - <Link - to="/active" - mask={masked ? { to: '/masked' } : undefined} - disabled={disabled} - target="_blank" - activeProps={stateProps} - inactiveProps={stateProps} - > - Target - </Link> - </RouterContextProvider> - ) - 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') => ( - <RouterContextProvider router={router}> - <Link - to={to} - data-version={++version} - className="base" - style={{ color: 'black', fontWeight: 700 }} - activeProps={activeProps} - inactiveProps={inactiveProps} - > - Target - </Link> - </RouterContextProvider> - ) - 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<HTMLAnchorElement>() - let resolvedRef: React.Ref<HTMLAnchorElement> | 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 <a {...props}>Override</a> - } - 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(<RouterProvider router={router} />) - const anchor = container.querySelector('a') - expect(anchor).not.toBeNull() - if (!anchor) { - throw new Error('Expected the server-rendered Link') - } - link = anchor - } else { - render(<RouterProvider router={router} />) - 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 6871afc8a4..a04149ed61 100644 --- a/packages/react-router/tests/link.bench.tsx +++ b/packages/react-router/tests/link.bench.tsx @@ -1,6 +1,5 @@ import { render } from '@testing-library/react' -import { describe, test } from 'vitest' -import { getRouteSegments } from '@tanstack/router-core' +import { bench, describe } from 'vitest' import { Link, RouterProvider, @@ -38,16 +37,8 @@ const InterpolatePathLink = ({ to, params, children, -}: React.PropsWithChildren<{ - to: string - params: Record<string, number> -}>) => { - const router = useRouter() - const href = interpolatePath( - to, - getRouteSegments(router.routesByPath[to])!, - params, - ) +}: React.PropsWithChildren<LinkProps>) => { + const href = interpolatePath({ path: to, params }).interpolatedPath return <a href={href}>{children}</a> } @@ -82,8 +73,9 @@ describe.each([ ])('$name', ({ numberOfRoutes, numberOfLinks, matchedParamId }) => { const renderRouter = createRouterRenderer(numberOfRoutes) - test('hardcoded href', async ({ bench }) => { - await bench('hardcoded href', () => { + bench( + 'hardcoded href', + () => { const router = renderRouter( Array.from({ length: numberOfLinks }).map((_, i) => ( <a key={i} href={`/params/${i}`}> @@ -92,13 +84,13 @@ describe.each([ )), ) render(<RouterProvider router={router} />) - }).run({ - warmupIterations: 1, - }) - }) + }, + { warmupIterations: 1 }, + ) - test('interpolate path', async ({ bench }) => { - await bench('interpolate path', () => { + bench( + 'interpolate path', + () => { const router = renderRouter( Array.from({ length: numberOfLinks }).map((_, i) => ( <InterpolatePathLink @@ -111,13 +103,13 @@ describe.each([ )), ) render(<RouterProvider router={router} />) - }).run({ - warmupIterations: 1, - }) - }) + }, + { warmupIterations: 1 }, + ) - test('build location', async ({ bench }) => { - await bench('build location', () => { + bench( + 'build location', + () => { const router = renderRouter( Array.from({ length: numberOfLinks }).map((_, i) => ( <BuildLocationLink @@ -130,13 +122,13 @@ describe.each([ )), ) render(<RouterProvider router={router} />) - }).run({ - warmupIterations: 1, - }) - }) + }, + { warmupIterations: 1 }, + ) - test('link to absolute path', async ({ bench }) => { - await bench('link to absolute path', () => { + bench( + 'link to absolute path', + () => { const router = renderRouter( Array.from({ length: numberOfLinks }).map((_, i) => ( <Link @@ -149,13 +141,13 @@ describe.each([ )), ) render(<RouterProvider router={router} />) - }).run({ - warmupIterations: 1, - }) - }) + }, + { warmupIterations: 1 }, + ) - test('link to relative path', async ({ bench }) => { - await bench('link to relative path', () => { + bench( + 'link to relative path', + () => { const router = renderRouter( Array.from({ length: numberOfLinks }).map((_, i) => { const to = `./params/$param${Math.min(i, matchedParamId)}` @@ -173,13 +165,13 @@ describe.each([ }), ) render(<RouterProvider router={router} />) - }).run({ - warmupIterations: 1, - }) - }) + }, + { warmupIterations: 1 }, + ) - test('link to current path', async ({ bench }) => { - await bench('link to current path', () => { + bench( + 'link to current path', + () => { const router = renderRouter( Array.from({ length: numberOfLinks }).map((_, i) => ( <Link key={i} from="/" search={{ param: i }}> @@ -188,8 +180,7 @@ describe.each([ )), ) render(<RouterProvider router={router} />) - }).run({ - warmupIterations: 1, - }) - }) + }, + { warmupIterations: 1 }, + ) }) diff --git a/packages/react-router/tests/link.test.tsx b/packages/react-router/tests/link.test.tsx index 56c4ece9db..26cd07d988 100644 --- a/packages/react-router/tests/link.test.tsx +++ b/packages/react-router/tests/link.test.tsx @@ -1,5 +1,4 @@ import React from 'react' -import { renderToString } from 'react-dom/server' import { afterEach, beforeEach, describe, expect, it, test, vi } from 'vitest' import { act, @@ -17,7 +16,6 @@ import { trailingSlashOptions } from '@tanstack/router-core' import { Link, Outlet, - RouterContextProvider, RouterProvider, createBrowserHistory, createHashHistory, @@ -29,11 +27,9 @@ import { createRouteMask, createRouter, getRouteApi, - notFound, redirect, retainSearchParams, stripSearchParams, - useLinkProps, useLoaderData, useMatchRoute, useParams, @@ -41,7 +37,6 @@ import { useRouterState, useSearch, } from '../src' -import { composeHandlers } from '../src/link' import { getIntersectionObserverMock, getSearchParamsFromURI, @@ -51,16 +46,12 @@ 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() @@ -68,7 +59,6 @@ beforeEach(() => { }) afterEach(() => { - vi.useRealTimers() history.destroy() window.history.replaceState(null, 'root', '/') vi.resetAllMocks() @@ -77,71 +67,6 @@ 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 () => { /** @@ -243,7 +168,6 @@ 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) @@ -253,96 +177,6 @@ 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: () => ( - <Link - to="/posts" - from="/" - activeProps={{ className: 'active' }} - inactiveProps={{ className: 'inactive' }} - activeOptions={{ - exact: true, - includeHash: true, - includeSearch: true, - }} - preload="intent" - preloadDelay={50} - preloadIntentProximity={123} - hashScrollIntoView={true} - replace={true} - startTransition={true} - resetScroll={true} - viewTransition={true} - ignoreBlocker={true} - params={{}} - search={{ foo: 'bar' }} - hash="details" - state={{}} - mask={{ to: '/posts', hash: 'masked' }} - reloadDocument={true} - unsafeRelative="path" - > - Posts - </Link> - ), - }) - - const postsRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/posts', - component: () => <h1>Posts</h1>, - }) - - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute, postsRoute]), - history, - }) - - render(<RouterProvider router={router} />) - - 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({ @@ -1027,26 +861,6 @@ describe('Link', () => { 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: () => <Link to="../javascript:alert(1)">Continue</Link>, - }) - - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute]), - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - - render(<RouterProvider router={router} />) - - 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 () => { @@ -1151,13 +965,10 @@ describe('Link', () => { expect(indexLink).not.toHaveAttribute('data-status', 'active') expect(indexLink).toHaveAttribute('href', '/') - // 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') + expect(postsLink).toHaveAttribute('data-status', 'active') + expect(postsLink).toHaveAttribute('aria-current', 'page') + expect(postsLink).toHaveClass('active') + expect(postsLink).toHaveAttribute('href', '/posts') }) test('when navigating to /posts with a base url', async () => { @@ -1214,13 +1025,10 @@ describe('Link', () => { expect(indexLink).not.toHaveAttribute('data-status', 'active') expect(indexLink).toHaveAttribute('href', '/app/') - // 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') + expect(postsLink).toHaveAttribute('data-status', 'active') + expect(postsLink).toHaveAttribute('aria-current', 'page') + expect(postsLink).toHaveClass('active') + expect(postsLink).toHaveAttribute('href', '/app/posts') }) test('when navigating to /posts with search', async () => { @@ -2089,115 +1897,6 @@ describe('Link', () => { expect(notFoundComponent).not.toBeCalled() }) - test('404 thrown in child will bubble up to the root with beforeLoad', async () => { - const rootRoute = createRootRoute({ - notFoundComponent: () => <div>Root notFoundComponent</div>, - beforeLoad: () => ({ ok: true }), - }) - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () => { - return ( - <> - <h1>Index</h1> - <Link to="/nonExistingPost">Non existing post</Link> - </> - ) - }, - }) - - 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: () => <div>Existing Post</div>, - }) - - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute, postRoute]), - }) - - render(<RouterProvider router={router} />) - - 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: () => <div>Root notFoundComponent</div>, - loader: async () => { - await sleep(0) - return { ok: true } - }, - }) - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () => { - return ( - <> - <h1>Index</h1> - <Link to="/nonExistingPost">Non existing post</Link> - </> - ) - }, - }) - - 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: () => <div>Existing Post</div>, - }) - - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute, postRoute]), - }) - - render(<RouterProvider router={router} />) - - 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({ @@ -5199,270 +4898,6 @@ 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: () => ( - <> - <Link to="/about" preload="viewport" preloadDelay={50}> - Viewport Link - </Link> - <Link to="/about" preload="intent" preloadDelay={50}> - Intent Link - </Link> - </> - ), - }) - const aboutRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/about', - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute, aboutRoute]), - history, - }) - const preloadRouteSpy = vi.spyOn(router, 'preloadRoute') - - render(<RouterProvider router={router} />) - - 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 ( - <> - <button - onClick={() => - setTo((current) => (current === '/about' ? '/other' : '/about')) - } - > - Change destination - </button> - <button onClick={() => setPreload('intent')}>Use intent</button> - <button onClick={() => setPreload(false)}>Disable preload</button> - <Link to={to} preload={preload} preloadDelay={50}> - Viewport Link - </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(<RouterProvider router={router} />) - - 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() @@ -6809,12 +6244,14 @@ describe('splat routes with empty splat', () => { async (trailingSlash) => { const tail = trailingSlash === 'always' ? '/' : '' - // The links stay mounted across the navigation so they can turn active. - const rootRoute = createRootRoute({ + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', component: () => { return ( <> - <Outlet /> + <h1>Index Route</h1> <Link data-testid="splat-link-with-empty-splat" to="/splat/$" @@ -6843,13 +6280,6 @@ describe('splat routes with empty splat', () => { ) }, }) - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () => { - return <h1>Index Route</h1> - }, - }) const splatRoute = createRoute({ getParentRoute: () => rootRoute, @@ -7855,12 +7285,8 @@ describe('protocolAllowlist', () => { path: '/', component: () => ( <> + <Link to="x-safari-https://example.com" /> <Link - data-testid="custom-protocol-link" - to="x-safari-https://example.com" - /> - <Link - data-testid="intent-protocol-link" to="intent://example.com#Intent;scheme=https;end" reloadDocument /> @@ -7893,18 +7319,18 @@ describe('protocolAllowlist', () => { expect(consoleWarn).not.toHaveBeenCalled() }) - it('should block links when protocol is not in allowlist', async () => { + it('should fallback to relative links when protocol is not in allowlist', async () => { const router = createRouter({ routeTree: rootRoute.addChildren([indexRoute]), history, protocolAllowlist: [], }) render(<RouterProvider router={router} />) - expect( - await screen.findByTestId('custom-protocol-link'), - ).not.toHaveAttribute('href') - expect(screen.getByTestId('intent-protocol-link')).not.toHaveAttribute( + 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).toHaveBeenCalledWith( 'Blocked Link with dangerous protocol: x-safari-https://example.com', @@ -7914,691 +7340,3 @@ describe('protocolAllowlist', () => { ) }) }) - -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 ( - <> - <button onClick={() => setPhase((p) => p + 1)}> - Change destination - </button> - <Link - data-testid="changing-link" - to={to} - hash={ - rewrite && phase === 1 - ? 'external' - : rewrite && phase === 2 - ? 'blocked' - : undefined - } - preload="intent" - preloadDelay={0} - > - {({ isActive }) => String(isActive)} - </Link> - <Outlet /> - </> - ) - }, - }) - const targetRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/target', - component: () => <p>target page</p>, - }) - const nextRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/next', - loader: nextLoader, - component: () => <p>next page</p>, - }) - 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(<RouterProvider router={router} />) - 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 = ( - <RouterContextProvider router={router}> - <Link - to="/target" - mask={{ to: '/mask' }} - preload="intent" - preloadDelay={0} - > - {({ isActive }) => String(isActive)} - </Link> - </RouterContextProvider> - ) - 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: () => ( - <> - <Link data-testid="allowed-link" to="https://example.com"> - {({ isActive }) => String(isActive)} - </Link> - <Link data-testid="dangerous-link" to="javascript:alert(1)"> - {({ isActive }) => String(isActive)} - </Link> - </> - ), - }) - 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( - <RouterProvider router={router} />, - ) - - router.isServer = false - const { container: clientContainer } = render( - <RouterProvider router={router} />, - ) - - 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) => ( - <Link key={to} data-testid={`unsafe-link-${index}`} to={to} /> - ))} - </> - ), - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute]), - history, - }) - - render(<RouterProvider router={router} />) - - 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: () => <Link data-testid="rewritten-link" to="/safe" />, - }) - 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(<RouterProvider router={router} />) - 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( - <RouterContextProvider router={router}> - <Link to="/safe">Safe</Link> - </RouterContextProvider>, - ) - - 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: () => <Link data-testid="custom-history-link" to="/safe" />, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute]), - history: customHistory, - }) - vi.spyOn(console, 'warn').mockImplementation(() => {}) - - render(<RouterProvider router={router} />) - 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: () => ( - <Link data-testid="direct-https-link" to="https://intended.example/" /> - ), - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute]), - history: customHistory, - }) - try { - render(<RouterProvider router={router} />) - 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: () => <Link data-testid="custom-history-link" to="/safe" />, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute]), - history: customHistory, - }) - render(<RouterProvider router={router} />) - 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: () => ( - <Link - data-testid="rewritten-link" - to="/safe" - hash="blocked" - activeProps={{ 'data-active': 'true' }} - inactiveProps={ - { - href: 'javascript:inactive()', - 'data-inactive': 'true', - } as unknown as { 'data-inactive': string } - } - /> - ), - }) - 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(<RouterProvider router={router} />) - 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 <a {...linkProps} data-testid={name} /> - }) - - const rootRoute = createRootRoute({ - component: () => ( - <> - <CountingLink name="unaffected" /> - <CountingLink name="becomesActive" /> - <Link data-testid="go" to="/posts"> - Go - </Link> - <Outlet /> - </> - ), - }) - - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () => <h1>Index</h1>, - }) - - const postsRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/posts', - component: () => <h1>Posts</h1>, - }) - - const elsewhereRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/elsewhere', - component: () => <h1>Elsewhere</h1>, - }) - - 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(<RouterProvider router={router} />) - - 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<string, string | undefined> - }) { - return ( - <Link to="/posts/{-$category}" params={params} data-testid="lnk"> - link - </Link> - ) - } - - const rootRoute = createRootRoute({ component: () => <Outlet /> }) - const postsRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/posts/{-$category}', - component: function Posts() { - const [params, setParams] = React.useState< - Record<string, string | undefined> - >({}) - return ( - <> - <button - data-testid="clear" - onClick={() => setParams({ category: undefined })} - > - clear - </button> - <CategoryLink params={params} /> - </> - ) - }, - }) - - const router = createRouter({ - routeTree: rootRoute.addChildren([postsRoute]), - history: createMemoryHistory({ initialEntries: ['/posts/tech'] }), - }) - - render(<RouterProvider router={router} />) - - 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 <a {...props}>Styled target</a> - } - const rootRoute = createRootRoute({ - component: () => ( - <> - <StyledLink /> - <Outlet /> - </> - ), - }) - 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(<RouterProvider router={router} />) - - 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 b96931d61a..d9b5968d72 100644 --- a/packages/react-router/tests/loaders.test.tsx +++ b/packages/react-router/tests/loaders.test.tsx @@ -647,7 +647,7 @@ test('reproducer #4546', async () => { } }) -test('does not show pending UI when loaders finish before their pending delays', async () => { +test('clears pendingTimeout when match resolves', async () => { const defaultPendingComponentOnMountMock = vi.fn() const nestedPendingComponentOnMountMock = vi.fn() const fooPendingComponentOnMountMock = vi.fn() @@ -716,6 +716,7 @@ test('does not show pending UI when loaders finish before their pending delays', }) render(<RouterProvider router={router} />) + await act(() => router.latestLoadPromise) const linkToFoo = await screen.findByTestId('link-to-foo') fireEvent.click(linkToFoo) const fooElement = await screen.findByText('Nested Foo page') @@ -729,32 +730,20 @@ test('does not show pending UI when loaders finish before their pending delays', expect(fooPendingComponentOnMountMock).not.toHaveBeenCalled() }) -// 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() +test('throw abortError from loader upon initial load with basepath', 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 <div data-testid="index-content">{data.value}</div> - }, - errorComponent: ({ error }) => { - renderedError(error) - return <div data-testid="index-error">indexErrorComponent</div> + loader: async () => { + return Promise.reject(new DOMException('Aborted', 'AbortError')) }, + component: () => <div>Index route content</div>, + errorComponent: () => ( + <div data-testid="index-error">indexErrorComponent</div> + ), }) const routeTree = rootRoute.addChildren([indexRoute]) @@ -762,21 +751,13 @@ test('#7673: a spontaneous loader AbortError renders the boundary without execut render(<RouterProvider router={router} />) - 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') + const indexElement = await screen.findByText('Index route content') + expect(indexElement).toBeInTheDocument() + expect(screen.queryByTestId('index-error')).not.toBeInTheDocument() + expect(window.location.pathname.startsWith('/app')).toBe(true) }) -test('navigating away from a pending route aborts its loader', async () => { +test('cancelMatches after pending timeout', async () => { function getPendingComponent(onMount: () => void) { const PendingComponent = () => { useEffect(() => { @@ -789,7 +770,6 @@ test('navigating away from a pending route aborts its loader', async () => { } const onAbortMock = vi.fn() const fooPendingComponentOnMountMock = vi.fn() - let fooSignal: AbortSignal | undefined const rootRoute = createRootRoute({ component: () => ( <div> @@ -807,18 +787,17 @@ test('navigating away from a pending route aborts its loader', async () => { const fooRoute = createRoute({ getParentRoute: () => rootRoute, path: '/foo', - pendingMs: 0, + pendingMs: WAIT_TIME * 20, loader: async ({ abortController }) => { - fooSignal = abortController.signal await new Promise<void>((resolve) => { - abortController.signal.addEventListener( - 'abort', - () => { - onAbortMock() - resolve() - }, - { once: true }, - ) + const timer = setTimeout(() => { + resolve() + }, WAIT_TIME * 40) + abortController.signal.addEventListener('abort', () => { + onAbortMock() + clearTimeout(timer) + resolve() + }) }) }, pendingComponent: getPendingComponent(fooPendingComponentOnMountMock), @@ -832,22 +811,18 @@ test('navigating away from a pending route aborts its loader', async () => { const routeTree = rootRoute.addChildren([fooRoute, barRoute]) const router = createRouter({ routeTree, history }) render(<RouterProvider router={router} />) + 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() - expect(fooSignal?.aborted).toBe(false) - await act(() => router.navigate({ to: '/bar' })) - const barElement = screen.getByText('Bar page') + const barLink = await screen.findByTestId('link-to-bar') + fireEvent.click(barLink) + const barElement = await screen.findByText('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') + expect(onAbortMock).toHaveBeenCalled() }) test('reproducer for #6388 - rapid navigation between parameterized routes should not trigger errorComponent', async () => { @@ -922,9 +897,7 @@ test('reproducer for #6388 - rapid navigation between parameterized routes shoul errorComponentRenderCount(error) return ( <div data-testid="error-component"> - Error Component:{' '} - {error instanceof Error ? error.message : String(error)} | Name:{' '} - {error instanceof Error ? error.name : typeof error} + Error Component: {error.message} | Name: {error.name} </div> ) }, @@ -939,25 +912,30 @@ test('reproducer for #6388 - rapid navigation between parameterized routes shoul }) render(<RouterProvider router={router} />) + await act(() => router.latestLoadPromise) + + const pendingComponent = screen.findByTestId('pending-component') 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() + expect(await pendingComponent).toBeInTheDocument() const param2Link = await screen.findByTestId('link-to-param-2') fireEvent.click(param2Link) - expect(await screen.findByTestId('pending-component')).toBeInTheDocument() + expect(await pendingComponent).toBeInTheDocument() fireEvent.click(param1Link) - expect(await screen.findByTestId('pending-component')).toBeInTheDocument() + expect(await pendingComponent).toBeInTheDocument() - const paramPage = await screen.findByTestId('param-page') + await act(() => router.latestLoadPromise) expect(onAbortMock).toHaveBeenCalled() expect(errorComponentRenderCount).not.toHaveBeenCalled() expect(screen.queryByTestId('error-component')).not.toBeInTheDocument() - expect(screen.queryByTestId('pending-component')).not.toBeInTheDocument() + expect(await pendingComponent).not.toBeInTheDocument() + const paramPage = await screen.findByTestId('param-page') 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 deleted file mode 100644 index bc947fff05..0000000000 --- a/packages/react-router/tests/match-provider.test.tsx +++ /dev/null @@ -1,90 +0,0 @@ -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 <span data-testid={name}>{match.routeId}</span> -} - -function createTestRouter( - disableGlobalCatchBoundary = false, - isServer = false, -) { - const root = createRootRoute({ - shellComponent: function Shell({ children }) { - const [count, setCount] = React.useState(0) - return ( - <section data-testid="shell"> - <NearestMatch name="shell-match" /> - <button onClick={() => setCount(count + 1)}>Count {count}</button> - {children} - </section> - ) - }, - component: () => ( - <> - <NearestMatch name="root-match" /> - <Outlet /> - </> - ), - }) - const first = createRoute({ - getParentRoute: () => root, - path: '/first', - component: () => <NearestMatch name="leaf-match" />, - }) - const second = createRoute({ - getParentRoute: () => root, - path: '/second', - component: () => <NearestMatch name="leaf-match" />, - }) - 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(<RouterProvider router={router} />) - 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(<RouterProvider router={router} />) - 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/not-found-pending-context.test.tsx b/packages/react-router/tests/not-found-pending-context.test.tsx deleted file mode 100644 index 6d3542f96d..0000000000 --- a/packages/react-router/tests/not-found-pending-context.test.tsx +++ /dev/null @@ -1,118 +0,0 @@ -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<void>((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: () => <p role="status">Loading account</p>, - component: () => { - const context = rootRoute.useRouteContext() - - return ( - <main> - <h1>Account portal</h1> - <output data-testid="owner-context"> - {context.product} / {context.user} / {context.access} - </output> - <Outlet /> - </main> - ) - }, - notFoundComponent: () => { - const context = rootRoute.useRouteContext() - - return ( - <p data-testid="not-found-context"> - Missing page for {context.product} / {context.user} / {context.access} - </p> - ) - }, - }) - const dashboardRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/dashboard', - component: () => <p>Dashboard</p>, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([dashboardRoute]), - history: createMemoryHistory({ initialEntries: ['/dashboard'] }), - context: { product: 'Router Cloud' }, - }) - - let navigation: Promise<void> | undefined - try { - render(<RouterProvider router={router} />) - - 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 deleted file mode 100644 index 5528efabec..0000000000 --- a/packages/react-router/tests/not-found-route-context.test.tsx +++ /dev/null @@ -1,184 +0,0 @@ -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: () => <div>Child content</div>, - notFoundComponent: ChildNotFoundComponent, - }) - - function ParentComponent() { - const context = parentRoute.useRouteContext() - - return ( - <> - <output data-testid="parent-context"> - {[context.routerValue, context.rootValue, context.parentValue].join( - ' / ', - )} - </output> - <Outlet /> - </> - ) - } - - function ChildNotFoundComponent() { - const context = parentRoute.useRouteContext() - - return ( - <output data-testid="not-found-context"> - {[context.routerValue, context.rootValue, context.parentValue].join( - ' / ', - )} - </output> - ) - } - - 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(<RouterProvider router={router} />) - - 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: <RouterServer router={router} />, - }), - ) - - 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: () => ( - <div data-testid="root-not-found">Root not found</div> - ), - }) - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () => <div>Index content</div>, - }) - - function RootComponent() { - const context = rootRoute.useRouteContext() - const loaderData = rootRoute.useLoaderData() - - return ( - <main data-testid="root-component"> - <output data-testid="context-value"> - Context: {context.contextValue ?? 'unavailable'} - </output> - <output data-testid="before-load-value"> - Before load: {context.beforeLoadValue ?? 'unavailable'} - </output> - <output data-testid="loader-value"> - Loader: {loaderData?.loaderValue ?? 'unavailable'} - </output> - <Outlet /> - </main> - ) - } - - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute]), - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - - render(<RouterProvider router={router} />) - - 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 deleted file mode 100644 index 3a648c3326..0000000000 --- a/packages/react-router/tests/not-found-route-lifecycle.test.tsx +++ /dev/null @@ -1,64 +0,0 @@ -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: () => <div>Tenant settings unavailable</div>, - }) - const profileRoute = createRoute({ - getParentRoute: () => unavailableSettingsRoute, - path: 'profile', - onEnter: descendantOnEnter, - component: () => <div>Profile settings</div>, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([ - tenantRoute.addChildren([ - unavailableSettingsRoute.addChildren([profileRoute]), - ]), - ]), - history: createMemoryHistory({ - initialEntries: ['/tenants/acme/settings/profile'], - }), - }) - - render(<RouterProvider router={router} />) - - 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 436c386694..5748f6aab7 100644 --- a/packages/react-router/tests/not-found.test.tsx +++ b/packages/react-router/tests/not-found.test.tsx @@ -1,25 +1,17 @@ import { afterEach, beforeEach, expect, test } from 'vitest' -import { act, cleanup, render, screen } from '@testing-library/react' +import { 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 @@ -35,194 +27,6 @@ afterEach(() => { cleanup() }) -test('navigating to an actively preloaded missing URL renders the global not-found boundary', async () => { - const missingLoaderStarted = createControlledPromise<void>() - const missingLoader = createControlledPromise<void>() - const rootRoute = createRootRoute({ - component: Outlet, - notFoundComponent: () => <div>Missing URL boundary</div>, - loader: ({ location }) => { - if (location.pathname === '/missing') { - missingLoaderStarted.resolve() - return missingLoader - } - return - }, - shouldReload: true, - }) - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () => <div>Home</div>, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute]), - history, - }) - - render(<RouterProvider router={router} />) - 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: () => <div>Root not found</div>, - }) - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () => <div>Home</div>, - }) - const failingRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/lazy-not-found', - beforeLoad: () => { - throw notFound() - }, - }).lazy(() => - Promise.resolve( - createLazyRoute('/lazy-not-found')({ - notFoundComponent: () => <div>Lazy route not found</div>, - }), - ), - ) - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute, failingRoute]), - history, - }) - - render(<RouterProvider router={router} />) - 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 <Scripts /> boundary in the shell. - shellComponent: ({ children }) => ( - <> - {children} - <Scripts /> - </> - ), - component: Outlet, - notFoundComponent: () => <div>Root not found</div>, - }) - const failingRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/lazy-not-found', - beforeLoad: () => { - throw notFound() - }, - }).lazy(() => - Promise.resolve( - createLazyRoute('/lazy-not-found')({ - notFoundComponent: () => <div>Lazy route not found</div>, - }), - ), - ) - 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: <RouterServer router={router} />, - }), - ) - - 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 <Scripts /> boundary in the shell; the - // client render outputs no scripts here. - shellComponent: ({ children }) => ( - <> - {children} - <Scripts /> - </> - ), - component: Outlet, - notFoundComponent: () => <div>Root fuzzy boundary</div>, - }) - const parentRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/parent', - component: Outlet, - notFoundComponent: () => <div>Parent fuzzy boundary</div>, - }) - const childRoute = createRoute({ - getParentRoute: () => parentRoute, - path: '/child', - }).lazy(() => - Promise.resolve( - createLazyRoute('/parent/child')({ - notFoundComponent: () => <div>Lazy child fuzzy boundary</div>, - }), - ), - ) - const routeTree = rootRoute.addChildren([ - parentRoute.addChildren([childRoute]), - ]) - - if (environment === 'client') { - const router = createRouter({ routeTree, history }) - render(<RouterProvider router={router} />) - 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: <RouterServer router={router} />, - }), - ) - - 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, @@ -443,82 +247,6 @@ test('defaultNotFoundComponent and notFoundComponent receives data props via spr expect(errorMessageComponent).toHaveTextContent(customData.message) }) -test('component-thrown bare notFound renders current route notFoundComponent', async () => { - const rootRoute = createRootRoute({ - component: () => <Outlet />, - notFoundComponent: () => <span data-testid="root-not-found">Root</span>, - }) - - const parentRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/parent', - component: () => <Outlet />, - notFoundComponent: () => ( - <span data-testid="parent-not-found">Parent not found</span> - ), - }) - - const childRoute = createRoute({ - getParentRoute: () => parentRoute, - path: '/child', - notFoundComponent: () => ( - <span data-testid="child-not-found">Child not found</span> - ), - component: () => { - throw notFound() - }, - }) - - const router = createRouter({ - routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), - history, - notFoundMode: 'fuzzy', - }) - - render(<RouterProvider router={router} />) - 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: () => <Outlet />, - notFoundComponent: () => <span data-testid="root-not-found">Root</span>, - }) - - const parentRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/parent', - component: () => <Outlet />, - notFoundComponent: () => ( - <span data-testid="parent-not-found">Parent not found</span> - ), - }) - - const childRoute = createRoute({ - getParentRoute: () => parentRoute, - path: '/child', - component: () => { - throw notFound() - }, - }) - - const router = createRouter({ - routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), - history, - notFoundMode: 'fuzzy', - }) - - render(<RouterProvider router={router} />) - 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: () => <Outlet />, 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 deleted file mode 100644 index 76e7a0cb9d..0000000000 --- a/packages/react-router/tests/on-rendered-same-href-state.test.tsx +++ /dev/null @@ -1,66 +0,0 @@ -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: () => <Outlet /> }) - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () => <div>Index</div>, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute]), - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - - render(<RouterProvider router={router} />) - 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 deleted file mode 100644 index 0f5ca3703d..0000000000 --- a/packages/react-router/tests/pending-fallback-promise-replacement.test.tsx +++ /dev/null @@ -1,138 +0,0 @@ -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<void>() - const secondReload = createControlledPromise<void>() - const reloads = [firstReload, secondReload] - let loaderCall = 0 - - const routeOptions = { - pendingMs: 0, - pendingMinMs: 100, - pendingComponent: () => <div data-testid="pending">Loading...</div>, - 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: () => ( - <div data-testid="content"> - Generation {rootRoute.useLoaderData().generation} - </div> - ), - }) - return createRouter({ - routeTree: rootRoute, - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - } - - const rootRoute = createRootRoute({ - component: () => <Outlet />, - }) - const pageRoute = createRoute({ - ...routeOptions, - getParentRoute: () => rootRoute, - path: '/page', - component: () => ( - <div data-testid="content"> - Generation {pageRoute.useLoaderData().generation} - </div> - ), - }) - return createRouter({ - routeTree: rootRoute.addChildren([pageRoute]), - history: createMemoryHistory({ initialEntries: ['/page'] }), - }) - } - const router = makeRouter() - - render(<RouterProvider router={router} />) - expect(await screen.findByText('Generation 1')).toBeInTheDocument() - - vi.useFakeTimers() - - let firstInvalidation!: Promise<void> - 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<void> - 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 deleted file mode 100644 index 5274fb83cc..0000000000 --- a/packages/react-router/tests/pending-route-context.test.tsx +++ /dev/null @@ -1,298 +0,0 @@ -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<void>() - const childBeforeLoadGate = createControlledPromise<void>() - const childLoaderStarted = createControlledPromise<void>() - const childLoaderGate = createControlledPromise<void>() - let navigation: Promise<void> | 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 ( - <main> - <header> - <h1>{context.workspace}</h1> - <output data-testid="root-context"> - Workspace {context.workspace}; role {context.role} - </output> - </header> - <Outlet /> - </main> - ) - } - - function HomeComponent() { - const navigate = homeRoute.useNavigate() - - return ( - <section> - <h2>Home</h2> - <button - onClick={() => { - navigation = navigate({ to: '/reports' }) - }} - > - View reports - </button> - </section> - ) - } - - function ReportsPendingComponent() { - const parentContext = rootRoute.useRouteContext() - - return ( - <section data-testid="reports-pending" role="status"> - Loading reports - <output data-testid="pending-ancestor-context"> - Workspace {parentContext.workspace}; role {parentContext.role} - </output> - </section> - ) - } - - function ReportsComponent() { - const context = reportsRoute.useRouteContext() - - return ( - <section> - <h2>Reports</h2> - <output data-testid="child-context"> - Workspace {context.workspace}; role {context.role}; report{' '} - {context.report}; access {context.access} - </output> - </section> - ) - } - - const router = createRouter({ - routeTree: rootRoute.addChildren([homeRoute, reportsRoute]), - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - const view = render(<RouterProvider router={router} />) - - 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<void>() - const secondChildLoaderGate = createControlledPromise<void>() - const thirdRootBeforeLoadStarted = createControlledPromise<void>() - const thirdRootBeforeLoadGate = createControlledPromise<void>() - let contextGeneration = 0 - let childLoaderGeneration = 0 - - const rootRoute = createRootRoute({ - beforeLoad: async () => { - const generation = ++contextGeneration - - if (generation === 3) { - thirdRootBeforeLoadStarted.resolve() - await thirdRootBeforeLoadGate - } - - return { generation } - }, - component: () => ( - <main> - <output data-testid="root-context"> - Root generation {rootRoute.useRouteContext().generation} - </output> - <Outlet /> - </main> - ), - }) - const childRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - loader: async () => { - if (++childLoaderGeneration === 2) { - secondChildLoaderStarted.resolve() - await secondChildLoaderGate - } - }, - pendingMs: 0, - pendingMinMs: 0, - pendingComponent: () => <p data-testid="child-pending">Loading child</p>, - component: () => <p>Child content</p>, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([childRoute]), - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - const view = render(<RouterProvider router={router} />) - let firstInvalidation: Promise<void> | undefined - let secondInvalidation: Promise<void> | 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<void> => - 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 deleted file mode 100644 index 1679546c79..0000000000 --- a/packages/react-router/tests/preloaded-mount-resolution.test.tsx +++ /dev/null @@ -1,155 +0,0 @@ -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 <div data-testid="home">Home</div> - } - const rootRoute = createRootRoute({ - component: () => <Outlet />, - }) - 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<void>((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<typeof setTimeout> | 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(<RouterProvider router={router} />) - await Promise.race([ - rendered, - new Promise<never>((_, 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<void>() - const beforeLoad = vi.fn() - const loader = vi.fn(() => gate) - const rootRoute = createRootRoute({ component: () => <Outlet /> }) - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - beforeLoad, - loader, - component: () => <div data-testid="home">Home</div>, - }) - 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(<RouterProvider router={router} />) - 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 deleted file mode 100644 index 644c4887e6..0000000000 --- a/packages/react-router/tests/public-presentation-lane-contract.test.tsx +++ /dev/null @@ -1,612 +0,0 @@ -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<string>() - - const rootRoute = createRootRoute({ component: Outlet }) - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () => <div>Home</div>, - }) - const parentRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/parent', - pendingMs: 0, - pendingComponent: () => <div>Loading parent</div>, - loader: () => parentGate, - component: Outlet, - }) - const childRoute = createRoute({ - getParentRoute: () => parentRoute, - path: '/child', - loader: () => 'child data', - component: () => <div>Child content</div>, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([ - indexRoute, - parentRoute.addChildren([childRoute]), - ]), - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - - render(<RouterProvider router={router} />) - expect(await screen.findByText('Home')).toBeInTheDocument() - await waitFor(() => expect(router.state.status).toBe('idle')) - - let navigation!: Promise<void> - 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<void>() - const retry = createControlledPromise<string>() - let attempt = 0 - - const rootRoute = createRootRoute({ component: Outlet }) - const pageRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/page', - pendingMs: 0, - pendingMinMs: 0, - pendingComponent: () => <div>Retrying page</div>, - loader: () => { - if (!attempt++) { - throw new Error('Initial failure') - } - retryStarted.resolve() - return retry - }, - errorComponent: () => <div>Page failed</div>, - component: () => <div>{pageRoute.useLoaderData()}</div>, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([pageRoute]), - history: createMemoryHistory({ initialEntries: ['/page'] }), - }) - const consoleWarn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - - render(<RouterProvider router={router} />) - expect(await screen.findByText('Page failed')).toBeInTheDocument() - - let retryLoad!: Promise<void> - 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<void>() - const secondGate = createControlledPromise<void>() - - const rootRoute = createRootRoute({ component: Outlet }) - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () => <div>Home</div>, - }) - const pageRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/page', - validateSearch: (search: Record<string, unknown>) => ({ - revision: Number(search.revision), - }), - pendingMs: 0, - pendingMinMs: 100, - pendingComponent: () => <div>Loading page</div>, - beforeLoad: ({ search }) => - search.revision === 1 ? firstGate : secondGate, - component: () => { - const search = pageRoute.useSearch() - return <div>Page revision {search.revision}</div> - }, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute, pageRoute]), - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - - render(<RouterProvider router={router} />) - 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<void> - 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<void>() - const childReload = createControlledPromise<void>() - const parentReloadStarted = createControlledPromise<void>() - const parentReload = createControlledPromise<void>() - let childLoads = 0 - - const rootRoute = createRootRoute({ - validateSearch: (search: Record<string, unknown>) => ({ - 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: () => <div>Loading child</div>, - loader: { - staleReloadMode: 'blocking', - handler: () => { - if (childLoads++) { - childReloadStarted.resolve() - return childReload - } - return undefined - }, - }, - component: () => ( - <div>Child revision {childRoute.useSearch().revision}</div> - ), - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), - history: createMemoryHistory({ - initialEntries: ['/parent/child?revision=1'], - }), - }) - - render(<RouterProvider router={router} />) - expect(await screen.findByText('Child revision 1')).toBeInTheDocument() - await waitFor(() => expect(router.state.status).toBe('idle')) - vi.useFakeTimers() - vi.setSystemTime(0) - - let firstNavigation: Promise<void> | undefined - let secondNavigation: Promise<void> | 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<void> => !!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<void>() - const retainedReady = createControlledPromise<void>() - const firstPage = createControlledPromise<void>() - const secondPageStarted = createControlledPromise<void>() - const secondPage = createControlledPromise<void>() - - const rootRoute = createRootRoute({ - validateSearch: (search: Record<string, unknown>) => ({ - revision: Number(search.revision) || 0, - }), - beforeLoad: ({ search }) => { - if (search.revision === 2) { - retainedStarted.resolve() - return retainedReady.then(() => ({ rootRevision: 2 })) - } - return { rootRevision: search.revision } - }, - component: () => ( - <div> - <div>Root revision {rootRoute.useRouteContext().rootRevision}</div> - <Outlet /> - </div> - ), - }) - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () => <div>Home</div>, - }) - const pageRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/page', - pendingMs: 0, - pendingMinMs: 100, - pendingComponent: () => <div>Loading page</div>, - beforeLoad: ({ search }) => { - if (search.revision === 1) { - return firstPage - } - secondPageStarted.resolve() - return secondPage - }, - component: () => ( - <div>Page revision {pageRoute.useSearch().revision}</div> - ), - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute, pageRoute]), - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - - render(<RouterProvider router={router} />) - expect(await screen.findByText('Home')).toBeInTheDocument() - vi.useFakeTimers() - vi.setSystemTime(0) - - let firstNavigation: Promise<void> | undefined - let secondNavigation: Promise<void> | 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<void> => !!navigation, - ), - ) - }) - } - }) - - test('an exact-boundary terminal result supersedes an unrendered pending offer', async () => { - const pendingRenderStarted = createControlledPromise<void>() - const pendingRender = createControlledPromise<void>() - const terminalLoadStarted = createControlledPromise<void>() - const terminalLoad = createControlledPromise<void>() - - const rootRoute = createRootRoute({ - validateSearch: (search: Record<string, unknown>) => ({ - 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: () => <div>Root not found</div>, - component: Outlet, - }) - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () => <div>Home</div>, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute]), - history: createMemoryHistory({ initialEntries: ['/?terminal=false'] }), - }) - - render(<RouterProvider router={router} />) - expect(await screen.findByText('Home')).toBeInTheDocument() - await waitFor(() => expect(router.state.status).toBe('idle')) - vi.useFakeTimers() - vi.setSystemTime(0) - - let navigation: Promise<void> | 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: () => <div>Home</div>, - }) - const firstRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/first', - component: () => <div>First</div>, - }) - const secondRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/second', - component: () => <div>Second</div>, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute, firstRoute, secondRoute]), - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - - render(<RouterProvider router={router} />) - expect(await screen.findByText('Home')).toBeInTheDocument() - await waitFor(() => expect(router.state.status).toBe('idle')) - - const renderedPaths: Array<string> = [] - let successor: Promise<void> | 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 deleted file mode 100644 index 0797fa5264..0000000000 --- a/packages/react-router/tests/react-render-owner-contract.test.tsx +++ /dev/null @@ -1,101 +0,0 @@ -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<void>() - const firstRenderGate = createControlledPromise<void>() - let signaledFirstRender = false - - const rootRoute = createRootRoute({ - validateSearch: (search: Record<string, unknown>) => ({ - 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 <div>Root revision {revision}</div> - }, - }) - const router = createRouter({ - routeTree: rootRoute, - history: createMemoryHistory({ initialEntries: ['/?revision=0'] }), - }) - - render(<RouterProvider router={router} />) - 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<number> = [] - const unsubscribe = router.subscribe('onRendered', (event) => { - renderedRevisions.push( - Number((event.toLocation.search as Record<string, unknown>).revision), - ) - }) - testCleanups.push(unsubscribe) - - let firstNavigation!: Promise<void> - 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 deleted file mode 100644 index b3f4618a28..0000000000 --- a/packages/react-router/tests/redirect-chain-first-load.test.tsx +++ /dev/null @@ -1,110 +0,0 @@ -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: () => <Outlet /> }) - - const userLayout = createRoute({ - id: 'user', - getParentRoute: () => rootRoute, - validateSearch: (search: Record<string, unknown>): { 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: () => <Outlet />, - }) - - const dashboardLayout = createRoute({ - id: 'dashboard', - getParentRoute: () => userLayout, - beforeLoad: async () => { - await sleep(30) - throw redirect({ to: '/intro', replace: true }) - }, - component: () => <Outlet />, - }) - - const homeRoute = createRoute({ - getParentRoute: () => dashboardLayout, - path: '/home', - component: () => <div data-testid="home-page">Home</div>, - }) - - const introLayout = createRoute({ - getParentRoute: () => userLayout, - path: '/intro', - beforeLoad: ({ location }) => { - if (location.pathname !== '/intro/step') { - throw redirect({ to: '/intro/step', replace: true }) - } - }, - component: () => <Outlet />, - }) - - const introIndexRoute = createRoute({ - getParentRoute: () => introLayout, - path: '/', - component: () => <div data-testid="intro-index">Intro index</div>, - }) - - const introStepRoute = createRoute({ - getParentRoute: () => introLayout, - path: 'step', - component: () => <div data-testid="intro-step">Intro step</div>, - }) - - const router = createRouter({ - routeTree: rootRoute.addChildren([ - userLayout.addChildren([ - dashboardLayout.addChildren([homeRoute]), - introLayout.addChildren([introIndexRoute, introStepRoute]), - ]), - ]), - defaultPendingMs: 0, - defaultPendingComponent: () => <div data-testid="pending">loading</div>, - history: createMemoryHistory({ initialEntries: ['/home?flag=true'] }), - }) - - render(<RouterProvider router={router} />) - - 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 ea8cd30dd4..b8b42d5e0e 100644 --- a/packages/react-router/tests/redirect.test.tsx +++ b/packages/react-router/tests/redirect.test.tsx @@ -1,6 +1,4 @@ -import * as React from 'react' import { - act, cleanup, configure, fireEvent, @@ -9,13 +7,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, @@ -28,10 +26,6 @@ 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('/') @@ -50,165 +44,6 @@ 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: () => <div>Index page</div>, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute]), - history, - }) - - render(<RouterProvider router={router} />) - - 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: () => <div>Home</div>, - }) - const sourceRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/source', - beforeLoad: () => { - throw redirect({ - to: '/target', - search: () => { - throw boom - }, - }) - }, - errorComponent: ({ error }) => ( - <div data-testid="source-error">{getErrorMessage(error)}</div> - ), - }) - const targetRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/target', - component: () => <div>Target</div>, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([ - indexRoute, - sourceRoute, - targetRoute, - ]), - history, - }) - - render(<RouterProvider router={router} />) - 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 }) => ( - <div data-testid="root-error">Root: {getErrorMessage(error)}</div> - ), - }) - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - loader, - errorComponent: ({ error }) => ( - <div data-testid="index-error">Index: {getErrorMessage(error)}</div> - ), - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute]), - history, - }) - - render(<RouterProvider router={router} />) - - 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 }) => ( - <div data-testid="root-error">Root: {getErrorMessage(error)}</div> - ), - }) - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - loader: indexLoader, - errorComponent: ({ error }) => ( - <div data-testid="index-error">Index: {getErrorMessage(error)}</div> - ), - }) - const otherRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/other', - loader: otherLoader, - errorComponent: ({ error }) => ( - <div data-testid="other-error">Other: {getErrorMessage(error)}</div> - ), - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute, otherRoute]), - history, - }) - - render(<RouterProvider router={router} />) - - 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() @@ -277,61 +112,6 @@ 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<void>() - const consoleError = vi - .spyOn(console, 'error') - .mockImplementation(() => {}) - - const rootRoute = createRootRoute({ - component: () => <Outlet />, - pendingMs: 0, - pendingComponent: () => <div data-testid="pending">loading</div>, - beforeLoad: async () => { - await beforeLoad - if (!hasRedirected) { - hasRedirected = true - throw redirect({ to: '/posts' }) - } - }, - }) - - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () => <div data-testid="index-page">Index page</div>, - }) - - 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(<RouterProvider router={router} />) - - 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() @@ -484,4 +264,116 @@ 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: { + external: false, + hash: '', + href: '/', + publicHref: '/', + 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/react-router/tests/renderRouterToStream.react19.test.tsx b/packages/react-router/tests/renderRouterToStream.react19.test.tsx deleted file mode 100644 index 426996d60e..0000000000 --- a/packages/react-router/tests/renderRouterToStream.react19.test.tsx +++ /dev/null @@ -1,227 +0,0 @@ -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<AnyRouter> = [] - -afterEach(() => { - for (const router of activeRouters.splice(0)) { - router.serverSsr?.cleanup() - } -}) - -async function buildRouter(dehydratedData: { routerData: Promise<string> }) { - 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<void>((done) => { - resolve = () => { - ready = true - done() - } - }) - - return { - Component() { - if (!ready) { - throw pending - } - return <div id={id}>{text}</div> - }, - resolve, - } -} - -async function readWithTimeout( - reader: ReadableStreamDefaultReader<Uint8Array>, -) { - let timeout: ReturnType<typeof setTimeout> | undefined - try { - return await Promise.race([ - reader.read(), - new Promise<never>((_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<Uint8Array>, - 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<string>((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: ( - <html> - <body> - <RouterContextProvider router={router}> - <Suspense fallback={<p>first-fallback</p>}> - <first.Component /> - </Suspense> - <Suspense fallback={<p>second-fallback</p>}> - <second.Component /> - </Suspense> - <Scripts /> - </RouterContextProvider> - </body> - </html> - ), - }) - const reader = response.body!.getReader() - const decoder = new TextDecoder() - const state = { html: '' } - - try { - // The shell ends with <Scripts />, whose last child is the boundary. - await readUntil(reader, decoder, state, (html) => { - const shell = html.indexOf('second-fallback') - return shell >= 0 && html.indexOf('</script>', 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('</script>', result) >= 0 - }) - - const firstResult = state.html.indexOf('first-resolved') - const reactPatchEnd = - state.html.indexOf('</script>', firstResult) + '</script>'.length - const reactPatch = state.html.slice(firstResult, reactPatchEnd) - expect(reactPatch).toContain('<script') - expect(reactPatch.endsWith('</script>')).toBe(true) - expect(state.html).not.toContain('second-resolved') - expect(state.html).not.toContain('</body></html>') - - 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('</body></html>') - - 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('</body></html>')).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 deleted file mode 100644 index cde31d0b6a..0000000000 --- a/packages/react-router/tests/renderRouterToStream.test.tsx +++ /dev/null @@ -1,895 +0,0 @@ -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<typeof ReactDomServer.renderToReadableStream>[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<typeof RouterSsrServer>() - return { - ...actual, - transformReadableStreamWithRouter: ( - ...args: Parameters<typeof actual.transformReadableStreamWithRouter> - ) => { - routerTransformMocks.readableOptions(args[2]) - return actual.transformReadableStreamWithRouter(...args) - }, - } -}) - -vi.mock('react-dom/server', () => ({ - default: reactDomServerMocks, - ...reactDomServerMocks, -})) - -const actualReactDomServer = await vi.importActual<typeof ReactDomServer>( - '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<string> }) { - 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<ReturnType<typeof renderRouterToStream>>, -) { - 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 `<script${id}${nonce}${streamPart}>${tag.children ?? ''}</script>` -} - -function takeInitialScriptHtml( - router: Awaited<ReturnType<typeof buildRouter>>, -) { - const scripts = router.serverSsr!.takeInitialHydrationScriptTags()! - return [...scripts.before, scripts.boundary].map(renderScript).join('') -} - -async function readWithTimeout( - reader: ReadableStreamDefaultReader<Uint8Array>, -) { - let timeout: ReturnType<typeof setTimeout> | undefined - try { - return await Promise.race([ - reader.read(), - new Promise<never>((_resolve, reject) => { - timeout = setTimeout( - () => reject(new Error('Timed out waiting for streamed HTML')), - 2000, - ) - }), - ]) - } finally { - if (timeout) { - clearTimeout(timeout) - } - } -} - -async function readUntil( - reader: ReadableStreamDefaultReader<Uint8Array>, - 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<Uint8Array>({ - 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<string>((resolve) => { - resolveLateData = resolve - }) - const router = await buildRouter({ lateData }) - const renderedScripts = takeInitialScriptHtml(router) - - let rendererController!: ReadableStreamDefaultController<Uint8Array> - let rendererClosed = false - const rendererStream = Object.assign( - new ReadableStream<Uint8Array>({ - start(controller) { - rendererController = controller - }, - }), - { allReady: new Promise<void>(() => {}) }, - ) - reactDomServerMocks.renderToReadableStream = vi.fn(() => - Promise.resolve(rendererStream), - ) - - const patch = - '<div hidden id="S:0">resolved</div>' + - '<script>applyPatch("B:0","S:0")</script>' - 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( - `<html><body>${renderedScripts}</body></html>${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('</body></html>'), - ) - 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<Uint8Array>({ - 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<Uint8Array>({ - 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<Uint8Array>(), { - 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<void>((resolve) => { - markCancelStarted = resolve - }) - const cancelReadable = vi.fn( - () => - new Promise<void>((resolve) => { - resolveCancel = resolve - markCancelStarted() - }), - ) - const readableStream = Object.assign( - new ReadableStream<Uint8Array>({ - cancel: cancelReadable, - }), - { allReady: new Promise<void>(() => {}) }, - ) - 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<void>((resolve) => { - resolveReady = resolve - }) - const cancelReadable = vi.fn(() => new Promise<void>(() => {})) - const readableStream = Object.assign( - new ReadableStream<Uint8Array>({ 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: <Fatal />, - }), - ).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<unknown> = [] - 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<void>((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('<html><body>shell') - opts.onError(renderError, { - componentStack: '', - }) - destination.end('</body></html>') - }, - } - }, - ) - - 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<typeof actualReactDomServer.renderToPipeableStream>[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<typeof actualReactDomServer.renderToPipeableStream>[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 deleted file mode 100644 index 1ce8ab4822..0000000000 --- a/packages/react-router/tests/root-pending-min.test.tsx +++ /dev/null @@ -1,213 +0,0 @@ -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<void>> = [] - -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<void>() - const rootLoader = vi.fn(() => reloadGate.then(() => ({ generation: 2 }))) - const rootRoute = createRootRoute({ - pendingMs: 0, - pendingMinMs: 100, - pendingComponent: () => <div data-testid="root-pending">Pending</div>, - loader: rootLoader, - component: () => ( - <div data-testid="root-content"> - Generation {rootRoute.useLoaderData().generation} - </div> - ), - }) - 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(<RouterProvider router={router} />) - expect(screen.getByTestId('root-content')).toHaveTextContent('Generation 1') - expect(rootLoader).not.toHaveBeenCalled() - - vi.useFakeTimers() - - let invalidation!: Promise<void> - 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: () => <div>Root pending</div>, - component: function RootComponent() { - const [value] = React.useState(initializers) - React.useEffect(() => { - mounts() - return unmounts - }, []) - return <div data-testid="root-content">{value}</div> - }, - }) - 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(<RouterProvider router={router} />) - 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<typeof hydrateRoot> - await act(async () => { - root = hydrateRoot(container, <RouterProvider router={router} />) - 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: () => <div>Root pending</div>, - component: () => <div>Root content</div>, - }) - 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(<RouterProvider router={router} />) - - 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<void>() - const rootRoute = createRootRoute({ - pendingComponent: () => <div>Server root pending</div>, - shellComponent: ({ children }) => ( - <html> - <head /> - <body>{children}</body> - </html> - ), - component: () => { - throw gate - }, - }) - const router = createRouter({ - routeTree: rootRoute, - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - router.isServer = true - await router.load() - - const html = renderToString(<RouterProvider router={router} />) - - // 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/routeApi.test-d.tsx b/packages/react-router/tests/routeApi.test-d.tsx index d0553a9e0b..587c189fb0 100644 --- a/packages/react-router/tests/routeApi.test-d.tsx +++ b/packages/react-router/tests/routeApi.test-d.tsx @@ -60,12 +60,6 @@ describe('getRouteApi', () => { expectTypeOf(invoiceRouteApi.useParams<DefaultRouter>()).toEqualTypeOf<{ invoiceId: string }>() - - expectTypeOf( - invoiceRouteApi.useParams<DefaultRouter, unknown, boolean, false>({ - shouldThrow: false, - }), - ).toEqualTypeOf<{ invoiceId: string } | undefined>() }) test('useContext', () => { expectTypeOf( @@ -78,12 +72,6 @@ describe('getRouteApi', () => { expectTypeOf(invoiceRouteApi.useSearch<DefaultRouter>()).toEqualTypeOf<{ page: number }>() - - expectTypeOf( - invoiceRouteApi.useSearch<DefaultRouter, unknown, boolean, false>({ - shouldThrow: false, - }), - ).toEqualTypeOf<{ page: number } | undefined>() }) test('useLoaderData', () => { expectTypeOf(invoiceRouteApi.useLoaderData<DefaultRouter>()).toEqualTypeOf<{ @@ -99,25 +87,6 @@ describe('getRouteApi', () => { expectTypeOf(invoiceRouteApi.useMatch<DefaultRouter>()).toEqualTypeOf< MakeRouteMatch<typeof routeTree, '/invoices/$invoiceId'> >() - - expectTypeOf( - invoiceRouteApi.useMatch<DefaultRouter>({ shouldThrow: true }), - ).toEqualTypeOf<MakeRouteMatch<typeof routeTree, '/invoices/$invoiceId'>>() - - expectTypeOf( - invoiceRouteApi.useMatch<DefaultRouter, unknown, boolean, false>({ - shouldThrow: false, - }), - ).toEqualTypeOf< - MakeRouteMatch<typeof routeTree, '/invoices/$invoiceId'> | undefined - >() - - expectTypeOf( - invoiceRouteApi.useMatch<DefaultRouter, string, boolean, false>({ - shouldThrow: false, - select: (match) => match.params.invoiceId, - }), - ).toEqualTypeOf<string | undefined>() }) test('Link', () => { const Link = invoiceRouteApi.Link diff --git a/packages/react-router/tests/routeContext.test.tsx b/packages/react-router/tests/routeContext.test.tsx index e00228e280..d11f86420e 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 () => { - let generation = 0 + const mockContextFn = vi.fn() const rootRoute = createRootRoute() const indexRoute = createRoute({ @@ -153,21 +153,14 @@ describe('context function', () => { path: '/', loaderDeps: ({ search }) => ({ foo: search.foo }), context: ({ deps }) => { - return { - generation: ++generation, - deps: JSON.stringify(deps), - } + mockContextFn(deps) }, component: () => { const navigate = indexRoute.useNavigate() - const context = indexRoute.useRouteContext() return ( <div> <h1>Index page</h1> <h2>search: {JSON.stringify(indexRoute.useSearch())}</h2> - <h3> - context: {context.generation}:{context.deps} - </h3> <button onClick={() => { navigate({ search: (p: any) => ({ ...p, foo: 'foo-1' }) }) @@ -215,37 +208,44 @@ describe('context function', () => { await findByText('Index page') await findByText(`search: ${JSON.stringify({})}`) - await findByText('context: 1:{}') + + expect(mockContextFn).toHaveBeenCalledOnce() + expect(mockContextFn).toHaveBeenCalledWith({}) + mockContextFn.mockClear() await clickButton('foo-1') await findByText(`search: ${JSON.stringify({ foo: 'foo-1' })}`) - await findByText('context: 2:{"foo":"foo-1"}') + expect(mockContextFn).toHaveBeenCalledOnce() + expect(mockContextFn).toHaveBeenCalledWith({ foo: 'foo-1' }) + mockContextFn.mockClear() await clickButton('foo-1') await findByText(`search: ${JSON.stringify({ foo: 'foo-1' })}`) - await findByText('context: 2:{"foo":"foo-1"}') + expect(mockContextFn).not.toHaveBeenCalled() await clickButton('bar-1') await findByText( `search: ${JSON.stringify({ foo: 'foo-1', bar: 'bar-1' })}`, ) - await findByText('context: 2:{"foo":"foo-1"}') + expect(mockContextFn).not.toHaveBeenCalled() await clickButton('foo-2') await findByText( `search: ${JSON.stringify({ foo: 'foo-2', bar: 'bar-1' })}`, ) - await findByText('context: 3:{"foo":"foo-2"}') + expect(mockContextFn).toHaveBeenCalledWith({ foo: 'foo-2' }) + mockContextFn.mockClear() await clickButton('bar-2') await findByText( `search: ${JSON.stringify({ foo: 'foo-2', bar: 'bar-2' })}`, ) - await findByText('context: 3:{"foo":"foo-2"}') + expect(mockContextFn).not.toHaveBeenCalled() await clickButton('clear') await findByText(`search: ${JSON.stringify({})}`) - await findByText('context: 4:{}') + expect(mockContextFn).toHaveBeenCalledOnce() + expect(mockContextFn).toHaveBeenCalledWith({}) }) }) diff --git a/packages/react-router/tests/routeScopedShouldThrow.test.tsx b/packages/react-router/tests/routeScopedShouldThrow.test.tsx deleted file mode 100644 index c1b326f41b..0000000000 --- a/packages/react-router/tests/routeScopedShouldThrow.test.tsx +++ /dev/null @@ -1,76 +0,0 @@ -import { afterEach, expect, test } from 'vitest' -import { cleanup, render, screen } from '@testing-library/react' -import { - Outlet, - RouterProvider, - createLazyRoute, - createMemoryHistory, - createRootRoute, - createRoute, - createRouter, - getRouteApi, -} from '../src' - -afterEach(() => { - window.history.replaceState(null, 'root', '/') - cleanup() -}) - -test('route-scoped hooks render undefined for an inactive route when shouldThrow is false', async () => { - const rootRoute = createRootRoute({ - component: Outlet, - }) - const postsRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/posts/$postId', - validateSearch: () => ({ page: 0 }), - }) - const postsRouteApi = getRouteApi('/posts/$postId') - const lazyPostsRoute = createLazyRoute('/posts/$postId')({}) - - function IndexComponent() { - const routeMatch = postsRoute.useMatch({ shouldThrow: false }) - const routeSearch = postsRoute.useSearch({ shouldThrow: false }) - const routeParams = postsRoute.useParams({ shouldThrow: false }) - const routeApiMatch = postsRouteApi.useMatch({ shouldThrow: false }) - const routeApiSearch = postsRouteApi.useSearch({ shouldThrow: false }) - const routeApiParams = postsRouteApi.useParams({ shouldThrow: false }) - const lazyRouteMatch = lazyPostsRoute.useMatch({ shouldThrow: false }) - const lazyRouteSearch = lazyPostsRoute.useSearch({ shouldThrow: false }) - const lazyRouteParams = lazyPostsRoute.useParams({ shouldThrow: false }) - - return ( - <> - <div data-testid="route-use-match">{String(routeMatch)}</div> - <div data-testid="route-use-search">{String(routeSearch)}</div> - <div data-testid="route-use-params">{String(routeParams)}</div> - <div data-testid="route-api-use-match">{String(routeApiMatch)}</div> - <div data-testid="route-api-use-search">{String(routeApiSearch)}</div> - <div data-testid="route-api-use-params">{String(routeApiParams)}</div> - <div data-testid="lazy-route-use-match">{String(lazyRouteMatch)}</div> - <div data-testid="lazy-route-use-search">{String(lazyRouteSearch)}</div> - <div data-testid="lazy-route-use-params">{String(lazyRouteParams)}</div> - </> - ) - } - - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: IndexComponent, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute, postsRoute]), - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - - render(<RouterProvider router={router} />) - - for (const scope of ['route', 'route-api', 'lazy-route']) { - for (const hook of ['use-match', 'use-search', 'use-params']) { - expect(await screen.findByTestId(`${scope}-${hook}`)).toHaveTextContent( - 'undefined', - ) - } - } -}) diff --git a/packages/react-router/tests/router-client-stream-cleanup.test.tsx b/packages/react-router/tests/router-client-stream-cleanup.test.tsx deleted file mode 100644 index 865b7cd732..0000000000 --- a/packages/react-router/tests/router-client-stream-cleanup.test.tsx +++ /dev/null @@ -1,55 +0,0 @@ -import { act, cleanup, render, screen, waitFor } from '@testing-library/react' -import { afterEach, expect, test, vi } from 'vitest' -import { Component } from 'react' -import { createMemoryHistory } from '@tanstack/history' -import { RouterClient } from '../src/ssr/RouterClient' -import { createRootRoute, createRouter } from '../src' -import type { ReactNode } from 'react' - -const hydrate = vi.hoisted(() => vi.fn()) - -vi.mock('@tanstack/router-core/ssr/client', () => ({ hydrate })) - -class ErrorBoundary extends Component< - { children: ReactNode }, - { error?: Error } -> { - state: { error?: Error } = {} - - static getDerivedStateFromError(error: Error) { - return { error } - } - - render() { - return this.state.error ? this.state.error.message : this.props.children - } -} - -afterEach(() => { - cleanup() - delete window.$_TSR - hydrate.mockReset() -}) - -test('RouterClient signals streaming cleanup without hiding a hydration failure', async () => { - const error = new Error('hydration failed') - hydrate.mockRejectedValue(error) - const rootRoute = createRootRoute({ component: () => <div>Ready</div> }) - const router = createRouter({ - routeTree: rootRoute, - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - const hydrated = vi.fn() - window.$_TSR = { h: hydrated } as any - - await act(async () => { - render( - <ErrorBoundary> - <RouterClient router={router} /> - </ErrorBoundary>, - ) - }) - - await waitFor(() => expect(hydrated).toHaveBeenCalledTimes(1)) - expect(await screen.findByText(error.message)).toBeInTheDocument() -}) diff --git a/packages/react-router/tests/router.test.tsx b/packages/react-router/tests/router.test.tsx index 926e2c3b8f..99a6e36d53 100644 --- a/packages/react-router/tests/router.test.tsx +++ b/packages/react-router/tests/router.test.tsx @@ -8,11 +8,7 @@ import { waitFor, } from '@testing-library/react' import { z } from 'zod' -import { - composeRewrites, - createControlledPromise, - notFound, -} from '@tanstack/router-core' +import { composeRewrites, notFound } from '@tanstack/router-core' import { Link, Outlet, @@ -1529,88 +1525,6 @@ describe('invalidate', () => { ).toBeInTheDocument() expect(screen.queryByTestId('loader-route')).not.toBeInTheDocument() }) - - it('does not render the route component while async loader notFound is waiting for later matches to settle', async () => { - const history = createMemoryHistory({ - initialEntries: ['/parent/child/grandchild'], - }) - - const createControlledPromise = () => { - let resolve!: () => void - const promise = new Promise<void>((r) => { - resolve = r - }) - - return { promise, resolve } - } - - const grandchildLoader = createControlledPromise() - - const rootRoute = createRootRoute({ - component: () => <Outlet />, - notFoundComponent: () => ( - <div data-testid="root-not-found">Root Not Found</div> - ), - }) - - const parentRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/parent', - component: () => <Outlet />, - notFoundComponent: () => ( - <div data-testid="parent-not-found">Parent Not Found</div> - ), - }) - - const childRoute = createRoute({ - getParentRoute: () => parentRoute, - path: '/child', - loader: async () => { - await Promise.resolve() - throw notFound() - }, - component: () => ( - <div data-testid="child-component"> - Child component should not render - </div> - ), - }) - - const grandchildRoute = createRoute({ - getParentRoute: () => childRoute, - path: '/grandchild', - loader: () => grandchildLoader.promise, - component: () => <div data-testid="grandchild-component">Grandchild</div>, - }) - - const router = createRouter({ - routeTree: rootRoute.addChildren([ - parentRoute.addChildren([childRoute.addChildren([grandchildRoute])]), - ]), - history, - defaultPendingMs: 0, - defaultPendingComponent: () => ( - <div data-testid="pending">Loading...</div> - ), - }) - - render(<RouterProvider router={router} />) - - await waitFor(() => { - expect(router.state.location.pathname).toBe('/parent/child/grandchild') - expect(router.state.matches[0]?.routeId).toBe(rootRoute.id) - expect(router.state.matches[1]?.routeId).toBe(parentRoute.id) - expect(router.state.matches[2]?.routeId).toBe(childRoute.id) - }) - - expect(screen.queryByTestId('child-component')).not.toBeInTheDocument() - expect(screen.queryByTestId('parent-not-found')).not.toBeInTheDocument() - - grandchildLoader.resolve() - - expect(await screen.findByTestId('parent-not-found')).toBeInTheDocument() - expect(screen.queryByTestId('child-component')).not.toBeInTheDocument() - }) }) describe('search params in URL', () => { @@ -1857,7 +1771,7 @@ describe('search params in URL', () => { describe.each(testCases)('search param validation', (validateSearch) => { it('does not throw an error when the search param is valid', async () => { - let errorSpy: unknown + let errorSpy: Error | undefined const rootRoute = createRootRoute({ validateSearch, errorComponent: ({ error }) => { @@ -1877,7 +1791,7 @@ describe('search params in URL', () => { }) it('throws an error when the search param is not valid', async () => { - let errorSpy: unknown + let errorSpy: Error | undefined const rootRoute = createRootRoute({ validateSearch, errorComponent: ({ error }) => { @@ -1892,9 +1806,7 @@ describe('search params in URL', () => { await act(() => router.load()) expect(errorSpy).toBeInstanceOf(SearchParamError) - expect( - errorSpy instanceof Error ? errorSpy.cause : undefined, - ).toBeInstanceOf(TestValidationError) + expect(errorSpy?.cause).toBeInstanceOf(TestValidationError) }) }) }) @@ -2211,26 +2123,22 @@ describe('does not strip search params if search validation fails', () => { }) }) -describe('navigation outcomes', () => { - it('should recover from a not-found route when navigating to a valid route', async () => { +describe('statusCode', () => { + it('should reset statusCode to 200 when navigating from 404 to valid route', async () => { const history = createMemoryHistory({ initialEntries: ['/'] }) - const rootRoute = createRootRoute({ - notFoundComponent: () => ( - <div data-testid="root-not-found">Not Found</div> - ), - }) + const rootRoute = createRootRoute() const indexRoute = createRoute({ getParentRoute: () => rootRoute, path: '/', - component: () => <div data-testid="home-page">Home</div>, + component: () => <div>Home</div>, }) const validRoute = createRoute({ getParentRoute: () => rootRoute, path: '/valid', - component: () => <div data-testid="valid-page">Valid Route</div>, + component: () => <div>Valid Route</div>, }) const routeTree = rootRoute.addChildren([indexRoute, validRoute]) @@ -2238,28 +2146,27 @@ describe('navigation outcomes', () => { render(<RouterProvider router={router} />) + expect(router.state.statusCode).toBe(200) + await act(() => router.navigate({ to: '/' })) - expect(await screen.findByTestId('home-page')).toBeInTheDocument() + expect(router.state.statusCode).toBe(200) await act(() => router.navigate({ to: '/non-existing' })) - expect(await screen.findByTestId('root-not-found')).toBeInTheDocument() - expect(screen.queryByTestId('home-page')).not.toBeInTheDocument() + expect(router.state.statusCode).toBe(404) await act(() => router.navigate({ to: '/valid' })) - expect(await screen.findByTestId('valid-page')).toBeInTheDocument() - expect(screen.queryByTestId('root-not-found')).not.toBeInTheDocument() + expect(router.state.statusCode).toBe(200) await act(() => router.navigate({ to: '/another-non-existing' })) - expect(await screen.findByTestId('root-not-found')).toBeInTheDocument() - expect(screen.queryByTestId('valid-page')).not.toBeInTheDocument() + expect(router.state.statusCode).toBe(404) }) describe.each([true, false])( - 'loader and beforeLoad outcomes are rendered (isAsync=%s)', + 'status code is set when loader/beforeLoad throws (isAsync=%s)', async (isAsync) => { const throwingFun = isAsync ? (toThrow: () => void) => async () => { - await Promise.resolve() + await new Promise((resolve) => setTimeout(resolve, 10)) toThrow() } : (toThrow: () => void) => toThrow @@ -2270,19 +2177,15 @@ describe('navigation outcomes', () => { const throwError = throwingFun(() => { throw new Error('test-error') }) - it('should render notFoundComponent when a route loader throws a notFound()', async () => { + it('should set statusCode to 404 when a route loader throws a notFound()', async () => { const history = createMemoryHistory({ initialEntries: ['/'] }) - const rootRoute = createRootRoute({ - notFoundComponent: () => ( - <div data-testid="root-not-found">Root Not Found</div> - ), - }) + const rootRoute = createRootRoute() const indexRoute = createRoute({ getParentRoute: () => rootRoute, path: '/', - component: () => <div data-testid="home-page">Home</div>, + component: () => <div>Home</div>, }) const loaderThrowsRoute = createRoute({ @@ -2293,7 +2196,7 @@ describe('navigation outcomes', () => { <div data-testid="route-component">loader will throw</div> ), notFoundComponent: () => ( - <div data-testid="route-not-found">Route Not Found</div> + <div data-testid="not-found-component">Not Found</div> ), }) @@ -2302,27 +2205,29 @@ describe('navigation outcomes', () => { render(<RouterProvider router={router} />) - expect(await screen.findByTestId('home-page')).toBeInTheDocument() + expect(router.state.statusCode).toBe(200) + await act(() => router.navigate({ to: '/loader-throws-not-found' })) - expect(await screen.findByTestId('route-not-found')).toBeInTheDocument() - expect(screen.queryByTestId('root-not-found')).not.toBeInTheDocument() + expect(router.state.statusCode).toBe(404) + expect( + await screen.findByTestId('not-found-component'), + ).toBeInTheDocument() expect(screen.queryByTestId('route-component')).not.toBeInTheDocument() - expect(screen.queryByTestId('home-page')).not.toBeInTheDocument() }) - it('should render notFoundComponent when a route beforeLoad throws a notFound()', async () => { + it('should set statusCode to 404 when a route beforeLoad throws a notFound()', async () => { const history = createMemoryHistory({ initialEntries: ['/'] }) const rootRoute = createRootRoute({ notFoundComponent: () => ( - <div data-testid="root-not-found">Root Not Found</div> + <div data-testid="not-found-component">Not Found</div> ), }) const indexRoute = createRoute({ getParentRoute: () => rootRoute, path: '/', - component: () => <div data-testid="home-page">Home</div>, + component: () => <div>Home</div>, }) const beforeLoadThrowsRoute = createRoute({ @@ -2333,7 +2238,7 @@ describe('navigation outcomes', () => { <div data-testid="route-component">beforeLoad will throw</div> ), notFoundComponent: () => ( - <div data-testid="route-not-found">Route Not Found</div> + <div data-testid="not-found-component">Not Found</div> ), }) @@ -2345,15 +2250,17 @@ describe('navigation outcomes', () => { render(<RouterProvider router={router} />) - expect(await screen.findByTestId('home-page')).toBeInTheDocument() + expect(router.state.statusCode).toBe(200) + await act(() => router.navigate({ to: '/beforeload-throws-not-found' })) - expect(await screen.findByTestId('route-not-found')).toBeInTheDocument() - expect(screen.queryByTestId('root-not-found')).not.toBeInTheDocument() + expect(router.state.statusCode).toBe(404) + expect( + await screen.findByTestId('not-found-component'), + ).toBeInTheDocument() expect(screen.queryByTestId('route-component')).not.toBeInTheDocument() - expect(screen.queryByTestId('home-page')).not.toBeInTheDocument() }) - it('should render errorComponent when a route loader throws an Error', async () => { + it('should set statusCode to 500 when a route loader throws an Error', async () => { const history = createMemoryHistory({ initialEntries: ['/'] }) const rootRoute = createRootRoute() @@ -2379,12 +2286,15 @@ describe('navigation outcomes', () => { render(<RouterProvider router={router} />) + expect(router.state.statusCode).toBe(200) + await act(() => router.navigate({ to: '/loader-throws-error' })) + expect(router.state.statusCode).toBe(500) expect(await screen.findByTestId('error-component')).toBeInTheDocument() expect(screen.queryByTestId('route-component')).not.toBeInTheDocument() }) - it('should render errorComponent when a route beforeLoad throws an Error', async () => { + it('should set statusCode to 500 when a route beforeLoad throws an Error', async () => { const history = createMemoryHistory({ initialEntries: ['/'] }) const rootRoute = createRootRoute() @@ -2413,7 +2323,10 @@ describe('navigation outcomes', () => { render(<RouterProvider router={router} />) + expect(router.state.statusCode).toBe(200) + await act(() => router.navigate({ to: '/beforeload-throws-error' })) + expect(router.state.statusCode).toBe(500) expect(await screen.findByTestId('error-component')).toBeInTheDocument() expect(screen.queryByTestId('route-component')).not.toBeInTheDocument() }) @@ -2422,7 +2335,7 @@ describe('navigation outcomes', () => { }) describe('notFound in beforeLoad with pendingComponent', () => { - it('renders notFound when child beforeLoad throws and parent has an immediate pending component', async () => { + it('should transition router.state.status to idle when child beforeLoad throws notFound and parent has pendingComponent with pendingMs: 0', async () => { const history = createMemoryHistory({ initialEntries: ['/'] }) const rootRoute = createRootRoute({ @@ -2477,26 +2390,23 @@ describe('notFound in beforeLoad with pendingComponent', () => { render(<RouterProvider router={router} />) - expect(await screen.findByTestId('home-page')).toBeInTheDocument() + // Wait for initial load + await act(() => router.latestLoadPromise) + expect(router.state.status).toBe('idle') + expect(screen.getByTestId('home-page')).toBeInTheDocument() + // Navigate to the child route that throws notFound in beforeLoad await act(() => router.navigate({ to: '/parent/child' })) - expect(await screen.findByTestId('parent-not-found')).toHaveTextContent( - 'Parent Not Found', - ) - expect(screen.queryByTestId('root-not-found')).not.toBeInTheDocument() - expect(screen.queryByTestId('pending-component')).not.toBeInTheDocument() - expect(screen.queryByTestId('child-component')).not.toBeInTheDocument() - expect(screen.queryByTestId('home-page')).not.toBeInTheDocument() - expect(router.state.matches.map((match) => match.routeId)).toEqual([ - rootRoute.id, - parentRoute.id, - childRoute.id, - ]) - expect(router.state.status).toBe('idle') + // The router status should eventually become idle + await waitFor(() => { + expect(router.state.status).toBe('idle') + }) + + expect(router.state.statusCode).toBe(404) }) - it('renders notFound when child beforeLoad throws without a pending component', async () => { + it('should transition router.state.status to idle when child beforeLoad throws notFound and parent has NO pendingComponent', async () => { const history = createMemoryHistory({ initialEntries: ['/'] }) const rootRoute = createRootRoute({ @@ -2529,20 +2439,19 @@ describe('notFound in beforeLoad with pendingComponent', () => { render(<RouterProvider router={router} />) - expect(await screen.findByTestId('home-page')).toBeInTheDocument() + await act(() => router.latestLoadPromise) + expect(router.state.status).toBe('idle') await act(() => router.navigate({ to: '/child' })) - expect(await screen.findByTestId('child-not-found')).toHaveTextContent( - 'Child Not Found', - ) - expect(screen.queryByTestId('root-not-found')).not.toBeInTheDocument() - expect(screen.queryByTestId('child-component')).not.toBeInTheDocument() - expect(screen.queryByTestId('home-page')).not.toBeInTheDocument() - expect(router.state.status).toBe('idle') + await waitFor(() => { + expect(router.state.status).toBe('idle') + }) + + expect(router.state.statusCode).toBe(404) }) - it('renders notFound when nested child beforeLoad throws without a pending component', async () => { + it('should transition router.state.status to idle when nested child beforeLoad throws notFound WITHOUT pendingComponent', async () => { const history = createMemoryHistory({ initialEntries: ['/'] }) const rootRoute = createRootRoute({ @@ -2589,145 +2498,89 @@ describe('notFound in beforeLoad with pendingComponent', () => { render(<RouterProvider router={router} />) - expect(await screen.findByTestId('home-page')).toBeInTheDocument() + await act(() => router.latestLoadPromise) + expect(router.state.status).toBe('idle') await act(() => router.navigate({ to: '/parent/child' })) - expect(await screen.findByTestId('parent-not-found')).toHaveTextContent( - 'Parent Not Found', - ) - expect(screen.queryByTestId('root-not-found')).not.toBeInTheDocument() - expect(screen.queryByTestId('parent-component')).not.toBeInTheDocument() - expect(screen.queryByTestId('child-component')).not.toBeInTheDocument() - expect(screen.queryByTestId('home-page')).not.toBeInTheDocument() - expect(router.state.matches.map((match) => match.routeId)).toEqual([ - rootRoute.id, - parentRoute.id, - childRoute.id, - ]) - expect(router.state.status).toBe('idle') + await waitFor(() => { + expect(router.state.status).toBe('idle') + }) + + expect(router.state.statusCode).toBe(404) }) - it.each(['ancestor', 'child'] as const)( - 'renders the parent notFound after showing %s pending UI', - async (pendingOwner) => { - const history = createMemoryHistory({ initialEntries: ['/'] }) - const beforeLoad = createControlledPromise<void>() + it('should transition router.state.status to idle when child async beforeLoad throws notFound and parent has pendingComponent with pendingMs: 0', async () => { + const history = createMemoryHistory({ initialEntries: ['/'] }) - const rootRoute = createRootRoute({ - component: () => <Outlet />, - notFoundComponent: () => ( - <div data-testid="root-not-found">Root Not Found</div> - ), - }) + const rootRoute = createRootRoute({ + component: () => <Outlet />, + notFoundComponent: () => ( + <div data-testid="root-not-found">Root Not Found</div> + ), + }) - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () => <div data-testid="home-page">Home</div>, - }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => ( + <div data-testid="home-page"> + <Link to="/parent/child">Go to child</Link> + </div> + ), + }) - const parentRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/parent', - ...(pendingOwner === 'ancestor' - ? { - beforeLoad: () => beforeLoad, - pendingMs: 0, - pendingComponent: () => ( - <div data-testid="ancestor-pending">Loading ancestor...</div> - ), - } - : {}), - component: () => ( - <div data-testid="parent-component"> - Parent - <Outlet /> - </div> - ), - notFoundComponent: () => ( - <div data-testid="parent-not-found">Parent Not Found</div> - ), - }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + pendingMs: 0, + pendingComponent: () => ( + <div data-testid="pending-component">Loading...</div> + ), + component: () => ( + <div data-testid="parent-component"> + Parent + <Outlet /> + </div> + ), + notFoundComponent: () => ( + <div data-testid="parent-not-found">Parent Not Found</div> + ), + }) - const childRoute = createRoute({ - getParentRoute: () => parentRoute, - path: '/child', - ...(pendingOwner === 'child' - ? { - pendingMs: 0, - pendingComponent: () => ( - <div data-testid="child-pending">Loading child...</div> - ), - } - : {}), - beforeLoad: async () => { - if (pendingOwner === 'child') { - await beforeLoad - } - throw notFound() - }, - component: () => <div data-testid="child-component">Child</div>, - }) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + beforeLoad: async () => { + await new Promise((resolve) => setTimeout(resolve, 10)) + throw notFound() + }, + component: () => <div data-testid="child-component">Child</div>, + }) - const routeTree = rootRoute.addChildren([ - indexRoute, - parentRoute.addChildren([childRoute]), - ]) - const router = createRouter({ - routeTree, - history, - defaultPendingMinMs: 0, - }) + const routeTree = rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + ]) + const router = createRouter({ routeTree, history }) - render(<RouterProvider router={router} />) + render(<RouterProvider router={router} />) - expect(await screen.findByTestId('home-page')).toBeInTheDocument() + // Wait for initial load + await act(() => router.latestLoadPromise) + expect(router.state.status).toBe('idle') + expect(screen.getByTestId('home-page')).toBeInTheDocument() - vi.useFakeTimers() - let navigation!: Promise<void> - const pendingTestId = `${pendingOwner}-pending` - try { - await act(async () => { - navigation = router.navigate({ to: '/parent/child' }) - await vi.advanceTimersByTimeAsync(0) - }) + // Navigate to the child route that throws notFound in beforeLoad + await act(() => router.navigate({ to: '/parent/child' })) - expect(screen.getByTestId(pendingTestId)).toBeInTheDocument() - if (pendingOwner === 'ancestor') { - expect( - screen.queryByTestId('parent-component'), - ).not.toBeInTheDocument() - } else { - expect(screen.getByTestId('parent-component')).toBeInTheDocument() - } - } finally { - try { - await act(async () => { - beforeLoad.resolve() - await navigation - }) - } finally { - vi.useRealTimers() - } - } - - expect(screen.getByTestId('parent-not-found')).toHaveTextContent( - 'Parent Not Found', - ) - expect(screen.queryByTestId('root-not-found')).not.toBeInTheDocument() - expect(screen.queryByTestId(pendingTestId)).not.toBeInTheDocument() - expect(screen.queryByTestId('parent-component')).not.toBeInTheDocument() - expect(screen.queryByTestId('child-component')).not.toBeInTheDocument() - expect(screen.queryByTestId('home-page')).not.toBeInTheDocument() - expect(router.state.matches.map((match) => match.routeId)).toEqual([ - rootRoute.id, - parentRoute.id, - childRoute.id, - ]) + // The router status should eventually become idle + await waitFor(() => { expect(router.state.status).toBe('idle') - }, - ) + }) + + expect(router.state.statusCode).toBe(404) + }) }) describe('Router rewrite functionality', () => { @@ -2932,6 +2785,7 @@ describe('Router rewrite functionality', () => { }, }) render(<RouterProvider router={router} />) + await router.latestLoadPromise await waitFor(() => { expect(screen.getByTestId('component')).toHaveTextContent('test Users') }) @@ -3287,6 +3141,8 @@ describe('Router rewrite functionality', () => { const navigateBtn = await screen.findByTestId('navigate-btn') fireEvent.click(navigateBtn) + await router.latestLoadPromise + await screen.findByTestId('dashboard') // Router internal state should show the internal path @@ -3674,6 +3530,7 @@ describe('basepath', () => { }) expect(router.state.location.pathname).toBe('/') + expect(router.state.statusCode).toBe(200) }, ) diff --git a/packages/react-router/tests/setupTests.tsx b/packages/react-router/tests/setupTests.tsx index 6ab5039d6e..c3d7ec5cf7 100644 --- a/packages/react-router/tests/setupTests.tsx +++ b/packages/react-router/tests/setupTests.tsx @@ -1,3 +1,4 @@ +import '@testing-library/jest-dom/vitest' import { vi } from 'vitest' // @ts-expect-error diff --git a/packages/react-router/tests/store-updates-during-navigation.test.tsx b/packages/react-router/tests/store-updates-during-navigation.test.tsx index 8a10e06339..0c4c1b4146 100644 --- a/packages/react-router/tests/store-updates-during-navigation.test.tsx +++ b/packages/react-router/tests/store-updates-during-navigation.test.tsx @@ -136,7 +136,7 @@ describe("Store doesn't update *too many* times during navigation", () => { // This number should be as small as possible to minimize the amount of work // that needs to be done during a navigation. // Any change that increases this number should be investigated. - expect(updates).toBe(7) + expect(updates).toBe(8) }) test('redirection in preload', async () => { @@ -154,7 +154,7 @@ describe("Store doesn't update *too many* times during navigation", () => { // This number should be as small as possible to minimize the amount of work // that needs to be done during a navigation. // Any change that increases this number should be investigated. - expect(updates).toBe(2) + expect(updates).toBe(1) }) test('sync beforeLoad', async () => { @@ -196,7 +196,7 @@ describe("Store doesn't update *too many* times during navigation", () => { // This number should be as small as possible to minimize the amount of work // that needs to be done during a navigation. // Any change that increases this number should be investigated. - expect(updates).toBe(3) + expect(updates).toBe(4) }) test('hover preload, then navigate, w/ async loaders', async () => { diff --git a/packages/react-router/tests/transactional-loading.test.tsx b/packages/react-router/tests/transactional-loading.test.tsx deleted file mode 100644 index a6769c6063..0000000000 --- a/packages/react-router/tests/transactional-loading.test.tsx +++ /dev/null @@ -1,328 +0,0 @@ -import { - act, - cleanup, - fireEvent, - render, - screen, - waitFor, -} from '@testing-library/react' -import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' -import { - Link, - Outlet, - RouterProvider, - createBrowserHistory, - createMemoryHistory, - createRootRoute, - createRoute, - createRouter, -} from '../src' -import type { RouterHistory } from '../src' - -type Deferred<T> = { - promise: Promise<T> - resolve: (value: T) => void -} - -function deferred<T>(): Deferred<T> { - let resolve!: (value: T) => void - const promise = new Promise<T>((resolver) => { - resolve = resolver - }) - return { promise, resolve } -} - -let history: RouterHistory - -beforeEach(() => { - history = createBrowserHistory() -}) - -afterEach(() => { - history.destroy() - window.history.replaceState(null, 'root', '/') - cleanup() - vi.useRealTimers() -}) - -describe('transactional route loading', () => { - test('publishes a parent and child background refresh atomically after the child observes fresh parent data', async () => { - const parentRefresh = deferred<string>() - const childRefresh = deferred<void>() - const childObservedFreshParent = deferred<void>() - let parentLoads = 0 - let childLoads = 0 - - const rootRoute = createRootRoute({ - component: () => ( - <> - <Link to="/other">Other route</Link> - <Link to="/parent/child">Data route</Link> - <Outlet /> - </> - ), - }) - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () => <div>Home route</div>, - }) - const otherRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/other', - component: () => <div>Other route content</div>, - }) - const parentRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/parent', - staleTime: 0, - gcTime: 60_000, - loader: async () => { - parentLoads += 1 - if (parentLoads === 1) { - return 'parent-v1' - } - return parentRefresh.promise - }, - component: () => ( - <> - <div>{parentRoute.useLoaderData()}</div> - <Outlet /> - </> - ), - }) - const childRoute = createRoute({ - getParentRoute: () => parentRoute, - path: '/child', - staleTime: 0, - gcTime: 60_000, - loader: async ({ parentMatchPromise }) => { - childLoads += 1 - const parentMatch = await parentMatchPromise - const parentData = parentMatch.loaderData as string - if (childLoads > 1) { - childObservedFreshParent.resolve(undefined) - await childRefresh.promise - } - return `child-saw-${parentData}` - }, - component: () => <div>{childRoute.useLoaderData()}</div>, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([ - indexRoute, - otherRoute, - parentRoute.addChildren([childRoute]), - ]), - history, - }) - - render(<RouterProvider router={router} />) - - expect(await screen.findByText('Home route')).toBeInTheDocument() - await waitFor(() => { - expect(router.state.status).toBe('idle') - expect(router.state.resolvedLocation?.pathname).toBe('/') - }) - fireEvent.click(screen.getByText('Data route')) - - expect(await screen.findByText('parent-v1')).toBeInTheDocument() - expect(await screen.findByText('child-saw-parent-v1')).toBeInTheDocument() - await waitFor(() => { - expect(router.state.status).toBe('idle') - expect(router.state.resolvedLocation?.pathname).toBe('/parent/child') - }) - - fireEvent.click(screen.getByText('Other route')) - expect(await screen.findByText('Other route content')).toBeInTheDocument() - await waitFor(() => { - expect(router.state.status).toBe('idle') - expect(router.state.resolvedLocation?.pathname).toBe('/other') - }) - - fireEvent.click(screen.getByText('Data route')) - - expect(await screen.findByText('parent-v1')).toBeInTheDocument() - expect(await screen.findByText('child-saw-parent-v1')).toBeInTheDocument() - await waitFor(() => { - expect(router.state.status).toBe('idle') - expect(router.state.resolvedLocation?.pathname).toBe('/parent/child') - }) - - await act(async () => { - parentRefresh.resolve('parent-v2') - await childObservedFreshParent.promise - }) - - expect(screen.getByText('parent-v1')).toBeInTheDocument() - expect(screen.getByText('child-saw-parent-v1')).toBeInTheDocument() - expect(screen.queryByText('parent-v2')).not.toBeInTheDocument() - expect(screen.queryByText('child-saw-parent-v2')).not.toBeInTheDocument() - - await act(async () => { - childRefresh.resolve(undefined) - await Promise.resolve() - }) - - await waitFor(() => { - expect(screen.getByText('parent-v2')).toBeInTheDocument() - expect(screen.getByText('child-saw-parent-v2')).toBeInTheDocument() - expect(screen.queryByText('parent-v1')).not.toBeInTheDocument() - expect(screen.queryByText('child-saw-parent-v1')).not.toBeInTheDocument() - }) - }) - - test('renders a leaf error at the leaf boundary when its background refresh fails', async () => { - let loads = 0 - const rootRoute = createRootRoute({ - component: () => ( - <> - <div>Root shell</div> - <Outlet /> - </> - ), - }) - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () => <Link to="/parent/child">Open child</Link>, - }) - const parentRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/parent', - component: () => ( - <> - <div>Parent shell</div> - <Outlet /> - </> - ), - }) - const childRoute = createRoute({ - getParentRoute: () => parentRoute, - path: '/child', - loader: { - staleReloadMode: 'background', - handler: () => { - loads++ - if (loads > 1) { - throw new Error('background refresh failed') - } - return 'child data' - }, - }, - component: () => <div>{childRoute.useLoaderData()}</div>, - errorComponent: () => <div>Child refresh failed</div>, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([ - indexRoute, - parentRoute.addChildren([childRoute]), - ]), - history, - }) - - render(<RouterProvider router={router} />) - fireEvent.click(await screen.findByText('Open child')) - expect(await screen.findByText('child data')).toBeInTheDocument() - await waitFor(() => { - expect(router.state.status).toBe('idle') - expect(router.state.resolvedLocation?.pathname).toBe('/parent/child') - }) - - await act(() => router.invalidate()) - - expect(await screen.findByText('Child refresh failed')).toBeInTheDocument() - expect(screen.getByText('Root shell')).toBeInTheDocument() - expect(screen.getByText('Parent shell')).toBeInTheDocument() - }) - - test('renders the first settled background failure after foreground work completes', async () => { - const rootRefresh = deferred<void>() - const parentStarted = deferred<void>() - const childStarted = deferred<void>() - const parentGate = deferred<void>() - const childGate = deferred<void>() - const parentSettled = deferred<void>() - const childSettled = deferred<void>() - let rootLoads = 0 - let parentLoads = 0 - let childLoads = 0 - - const rootRoute = createRootRoute({ - loader: { - staleReloadMode: 'blocking', - handler: async () => { - if (++rootLoads > 1) { - await rootRefresh.promise - } - }, - }, - component: Outlet, - }) - const parentRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/parent', - loader: { - staleReloadMode: 'background', - handler: async () => { - if (++parentLoads > 1) { - parentStarted.resolve(undefined) - await parentGate.promise - parentSettled.resolve(undefined) - throw new Error('later parent failure') - } - return 'parent data' - }, - }, - component: Outlet, - errorComponent: () => <div>Parent refresh failed</div>, - }) - const childRoute = createRoute({ - getParentRoute: () => parentRoute, - path: '/child', - loader: { - staleReloadMode: 'background', - handler: async () => { - if (++childLoads > 1) { - childStarted.resolve(undefined) - await childGate.promise - childSettled.resolve(undefined) - throw new Error('first child failure') - } - return 'child data' - }, - }, - component: () => <div>{childRoute.useLoaderData()}</div>, - errorComponent: () => <div>Child refresh failed</div>, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), - history: createMemoryHistory({ initialEntries: ['/parent/child'] }), - }) - - render(<RouterProvider router={router} />) - expect(await screen.findByText('child data')).toBeInTheDocument() - await waitFor(() => expect(router.state.status).toBe('idle')) - - let invalidation!: Promise<void> - await act(async () => { - invalidation = router.invalidate() - await Promise.all([parentStarted.promise, childStarted.promise]) - }) - await act(async () => { - childGate.resolve(undefined) - await childSettled.promise - parentGate.resolve(undefined) - await parentSettled.promise - }) - expect(screen.getByText('child data')).toBeInTheDocument() - - await act(async () => { - rootRefresh.resolve(undefined) - await invalidation - }) - - expect(screen.getByText('Child refresh failed')).toBeInTheDocument() - expect(screen.queryByText('Parent refresh failed')).not.toBeInTheDocument() - }) -}) diff --git a/packages/react-router/tests/transitioner-listener-errors.test.tsx b/packages/react-router/tests/transitioner-listener-errors.test.tsx deleted file mode 100644 index 9682b8f60c..0000000000 --- a/packages/react-router/tests/transitioner-listener-errors.test.tsx +++ /dev/null @@ -1,81 +0,0 @@ -import * as React from 'react' -import { act, cleanup, render, screen } from '@testing-library/react' -import { afterEach, expect, test, vi } from 'vitest' -import { - Outlet, - RouterProvider, - createMemoryHistory, - createRootRoute, - createRoute, - createRouter, -} from '../src' - -const testCleanups: Array<() => void | Promise<void>> = [] - -afterEach(async () => { - while (testCleanups.length) { - await testCleanups.pop()!() - } - cleanup() -}) - -test('a throwing load-event listener cannot interrupt route hooks or later navigations', async () => { - const firstOnEnter = vi.fn() - const secondOnEnter = vi.fn() - const listenerError = new Error('onLoad listener failed') - const laterOnLoad = vi.fn() - const loadedPaths: Array<string> = [] - - const rootRoute = createRootRoute({ component: Outlet }) - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () => <div>Index route</div>, - }) - const firstRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/first', - onEnter: firstOnEnter, - component: () => <div>First route</div>, - }) - const secondRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/second', - onEnter: secondOnEnter, - component: () => <div>Second route</div>, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute, firstRoute, secondRoute]), - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - - render(<RouterProvider router={router} />) - expect(await screen.findByText('Index route')).toBeInTheDocument() - - const unsubscribe = router.subscribe('onLoad', (event) => { - if (event.toLocation.pathname === '/first') { - throw listenerError - } - }) - const unsubscribeLater = router.subscribe('onLoad', (event) => { - if (event.toLocation.pathname !== '/') { - loadedPaths.push(event.toLocation.pathname) - laterOnLoad(event) - } - }) - testCleanups.push(unsubscribe, unsubscribeLater) - - await act(() => router.navigate({ to: '/first' })) - - expect(screen.getByText('First route')).toBeInTheDocument() - expect(loadedPaths).toEqual(['/first']) - - unsubscribe() - await act(() => router.navigate({ to: '/second' })) - - expect(screen.getByText('Second route')).toBeInTheDocument() - expect(firstOnEnter).toHaveBeenCalledTimes(1) - expect(secondOnEnter).toHaveBeenCalledTimes(1) - expect(laterOnLoad).toHaveBeenCalledTimes(2) - expect(loadedPaths).toEqual(['/first', '/second']) -}) diff --git a/packages/react-router/tests/transitioner-remount.test.tsx b/packages/react-router/tests/transitioner-remount.test.tsx deleted file mode 100644 index 76cc6393ce..0000000000 --- a/packages/react-router/tests/transitioner-remount.test.tsx +++ /dev/null @@ -1,91 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { cleanup, render, screen, waitFor } from '@testing-library/react' -import { - Outlet, - RouterProvider, - createMemoryHistory, - createRootRoute, - createRoute, - createRouter, -} from '../src' - -afterEach(() => { - cleanup() -}) - -function setup() { - const rootRoute = createRootRoute({ component: () => <Outlet /> }) - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () => <div>Index</div>, - }) - const nextRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/next', - component: () => <div>Next</div>, - }) - const history = createMemoryHistory({ initialEntries: ['/'] }) - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute, nextRoute]), - history, - }) - return { history, router } -} - -describe('Transitioner remount', () => { - // Zombie-router pin: once the provider unmounts, the history subscription - // must be torn down so a later history change never re-drives the router. - it('does not load after the provider unmounts', async () => { - const { history, router } = setup() - const loadSpy = vi.spyOn(router, 'load') - - const first = render(<RouterProvider router={router} />) - expect(await screen.findByText('Index')).toBeInTheDocument() - await waitFor(() => expect(router.state.status).toBe('idle')) - - first.unmount() - loadSpy.mockClear() - - // A history change while unmounted must not reach the router. - history.push('/next') - await new Promise((resolve) => setTimeout(resolve, 0)) - - expect(loadSpy).not.toHaveBeenCalled() - // Raw history advanced... - expect(router.history.location.pathname).toBe('/next') - // ...but the router never processed it, so its committed state stayed put. - expect(router.state.location.pathname).toBe('/') - - loadSpy.mockRestore() - }) - - // Remounting the same router instance must re-establish the subscription so - // navigation keeps working, without leaving a stale duplicate behind. - it('re-subscribes and loads on remount with the same router', async () => { - const { history, router } = setup() - // Spy before the first mount so the subscription captures the spy by - // reference - both the first and second mounts subscribe with it. - const loadSpy = vi.spyOn(router, 'load') - - const first = render(<RouterProvider router={router} />) - expect(await screen.findByText('Index')).toBeInTheDocument() - await waitFor(() => expect(router.state.status).toBe('idle')) - - first.unmount() - - render(<RouterProvider router={router} />) - expect(await screen.findByText('Index')).toBeInTheDocument() - await waitFor(() => expect(router.state.status).toBe('idle')) - - // A push on the remounted provider must drive exactly one load, proving - // the subscription was re-established (and is singular). - loadSpy.mockClear() - history.push('/next') - expect(await screen.findByText('Next')).toBeInTheDocument() - expect(router.state.location.pathname).toBe('/next') - await waitFor(() => expect(loadSpy).toHaveBeenCalledTimes(1)) - - loadSpy.mockRestore() - }) -}) diff --git a/packages/react-router/tests/transitioner-render-ack.test.tsx b/packages/react-router/tests/transitioner-render-ack.test.tsx deleted file mode 100644 index 535a1e0e71..0000000000 --- a/packages/react-router/tests/transitioner-render-ack.test.tsx +++ /dev/null @@ -1,196 +0,0 @@ -import { StrictMode, act } from 'react' -import { cleanup, render, screen, waitFor } from '@testing-library/react' -import { afterEach, expect, test, vi } from 'vitest' -import { - Outlet, - RouterProvider, - createControlledPromise, - createMemoryHistory, - createRootRoute, - createRoute, - createRouter, -} from '../src' - -const testCleanups: Array<() => void> = [] - -afterEach(() => { - while (testCleanups.length) { - testCleanups.pop()!() - } - cleanup() - vi.useRealTimers() -}) - -test('same-location invalidation resolves after its refreshed DOM commits', async () => { - let generation = 0 - const rootRoute = createRootRoute({ component: Outlet }) - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - loader: { - staleReloadMode: 'blocking', - handler: () => ++generation, - }, - component: () => <div>Generation {indexRoute.useLoaderData()}</div>, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute]), - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - - render(<RouterProvider router={router} />) - expect(await screen.findByText('Generation 1')).toBeInTheDocument() - await waitFor(() => { - expect(router.state.status).toBe('idle') - expect(router.state.resolvedLocation?.pathname).toBe('/') - }) - - const refreshedDomWasVisible: Array<boolean> = [] - const unsubscribe = router.subscribe('onResolved', () => { - refreshedDomWasVisible.push(screen.queryByText('Generation 2') !== null) - }) - testCleanups.push(unsubscribe) - - await act(() => router.invalidate()) - expect(screen.getByText('Generation 2')).toBeInTheDocument() - expect(screen.queryByText('Generation 1')).not.toBeInTheDocument() - expect(refreshedDomWasVisible).toEqual([true]) -}) - -test('an immediately completed background refresh cannot replace the acknowledged foreground generation', async () => { - let generation = 0 - const rootRoute = createRootRoute({ component: Outlet }) - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - loader: { - staleReloadMode: 'background', - handler: () => ++generation, - }, - component: () => <div>Generation {indexRoute.useLoaderData()}</div>, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute]), - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - - render(<RouterProvider router={router} />) - expect(await screen.findByText('Generation 1')).toBeInTheDocument() - await waitFor(() => expect(router.state.status).toBe('idle')) - - await act(() => router.invalidate()) - - expect(await screen.findByText('Generation 2')).toBeInTheDocument() - expect(router.state.status).toBe('idle') -}) - -test('a navigation started by route lifecycle keeps the pending minimum of its own render', async () => { - const slowLoader = createControlledPromise<void>() - let nestedNavigation: Promise<void> | undefined - const rootRoute = createRootRoute({ component: Outlet }) - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () => <div>Index</div>, - }) - const redirectorRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/redirector', - onEnter: () => { - nestedNavigation = router.navigate({ to: '/slow' }) - }, - component: () => <div>Redirector</div>, - }) - const slowRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/slow', - pendingMs: 0, - pendingMinMs: 100, - pendingComponent: () => <div>Slow pending</div>, - loader: () => slowLoader, - component: () => <div>Slow done</div>, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute, redirectorRoute, slowRoute]), - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - - render(<RouterProvider router={router} />) - expect(await screen.findByText('Index')).toBeInTheDocument() - await waitFor(() => expect(router.state.status).toBe('idle')) - vi.useFakeTimers() - - let firstNavigation!: Promise<void> - await act(async () => { - firstNavigation = router.navigate({ to: '/redirector' }) - await vi.advanceTimersByTimeAsync(0) - }) - - expect(nestedNavigation).toBeDefined() - expect(screen.getByText('Slow pending')).toBeInTheDocument() - - await act(async () => { - slowLoader.resolve() - await Promise.resolve() - }) - await act(async () => { - await vi.advanceTimersByTimeAsync(99) - }) - expect(screen.getByText('Slow pending')).toBeInTheDocument() - - await act(async () => { - await vi.advanceTimersByTimeAsync(1) - await Promise.all([firstNavigation, nestedNavigation!]) - }) - expect(screen.queryByText('Slow pending')).not.toBeInTheDocument() - expect(screen.getByText('Slow done')).toBeInTheDocument() -}) - -test('StrictMode effect replay preserves renderer commit sequencing', async () => { - const rootRoute = createRootRoute({ component: Outlet }) - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () => <div>Index</div>, - }) - const nextRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/next', - component: () => <div>Next</div>, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute, nextRoute]), - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - - render( - <StrictMode> - <RouterProvider router={router} /> - </StrictMode>, - ) - expect(await screen.findByText('Index')).toBeInTheDocument() - await waitFor(() => { - expect(router.state.status).toBe('idle') - expect(router.state.resolvedLocation?.pathname).toBe('/') - }) - - const eventLog: Array<string> = [] - const unsubscribers = [ - router.subscribe('onResolved', (event) => { - if (event.toLocation.pathname === '/next') { - eventLog.push('onResolved:/next') - } - }), - router.subscribe('onRendered', (event) => { - if (event.toLocation.pathname === '/next') { - eventLog.push('onRendered:/next') - } - }), - ] - testCleanups.push(...unsubscribers) - - await act(() => router.navigate({ to: '/next' })) - expect(eventLog).toEqual(['onResolved:/next', 'onRendered:/next']) - expect(screen.getByText('Next')).toBeInTheDocument() - expect(screen.queryByText('Index')).not.toBeInTheDocument() -}) diff --git a/packages/react-router/tests/useBlocker.test.tsx b/packages/react-router/tests/useBlocker.test.tsx index e13437780e..c11cd054f1 100644 --- a/packages/react-router/tests/useBlocker.test.tsx +++ b/packages/react-router/tests/useBlocker.test.tsx @@ -1,4 +1,5 @@ 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' diff --git a/packages/react-router/tests/useHydrated.test.tsx b/packages/react-router/tests/useHydrated.test.tsx deleted file mode 100644 index 4b7c6ff469..0000000000 --- a/packages/react-router/tests/useHydrated.test.tsx +++ /dev/null @@ -1,63 +0,0 @@ -import React from 'react' -import { hydrateRoot } from 'react-dom/client' -import { renderToString } from 'react-dom/server' -import { act, cleanup, renderHook } from '@testing-library/react' -import { afterEach, expect, test, vi } from 'vitest' -import { ClientOnly, useHydrated } from '../src/ClientOnly' - -afterEach(() => { - cleanup() - vi.restoreAllMocks() -}) - -test('keeps both snapshot getters stable across renders', () => { - const spy = vi.spyOn(React, 'useSyncExternalStore') - const view = renderHook(() => useHydrated()) - const first = spy.mock.calls.at(-1)! - expect(view.result.current).toBe(true) - view.rerender() - const next = spy.mock.calls.at(-1)! - expect(next[0]).toBe(first[0]) - expect(next[1]).toBe(first[1]) - expect(next[2]).toBe(first[2]) - expect(view.result.current).toBe(true) -}) - -test('preserves the server snapshot through hydration before showing client content', async () => { - const values: Array<boolean> = [] - function Probe() { - const hydrated = useHydrated() - values.push(hydrated) - return ( - <div> - <span>{String(hydrated)}</span> - <ClientOnly fallback={<span>Fallback</span>}> - <span>Client content</span> - </ClientOnly> - </div> - ) - } - const container = document.createElement('div') - container.innerHTML = renderToString(<Probe />) - document.body.append(container) - expect(values).toEqual([false]) - expect(container).toHaveTextContent('falseFallback') - values.length = 0 - const onRecoverableError = vi.fn() - let root: ReturnType<typeof hydrateRoot> | undefined - try { - await act(() => { - root = hydrateRoot(container, <Probe />, { onRecoverableError }) - }) - expect(values[0]).toBe(false) - expect(values.at(-1)).toBe(true) - expect(container).toHaveTextContent('trueClient content') - expect(onRecoverableError).not.toHaveBeenCalled() - values.length = 0 - await act(() => root!.render(<Probe />)) - expect(values).toEqual([true]) - } finally { - await act(() => root?.unmount()) - container.remove() - } -}) diff --git a/packages/react-router/tests/useMatch.test.tsx b/packages/react-router/tests/useMatch.test.tsx index f1b8352bb0..9bf809f666 100644 --- a/packages/react-router/tests/useMatch.test.tsx +++ b/packages/react-router/tests/useMatch.test.tsx @@ -1,12 +1,5 @@ -import { useState } from 'react' import { afterEach, describe, expect, test, vi } from 'vitest' -import { - cleanup, - fireEvent, - render, - screen, - waitFor, -} from '@testing-library/react' +import { cleanup, render, screen, waitFor } from '@testing-library/react' import { Link, Outlet, @@ -81,203 +74,6 @@ describe('useMatch', () => { expect(postsTitle).toBeInTheDocument() }, ) - - test('returns undefined from select when match is found', async () => { - const select = vi.fn(() => undefined) - - function RootComponent() { - const match = useMatch({ from: '/posts', select }) - expect(match).toBeUndefined() - return <Outlet /> - } - - setup({ - RootComponent, - history: createMemoryHistory({ initialEntries: ['/posts'] }), - }) - const postsTitle = await screen.findByText('PostsTitle') - expect(postsTitle).toBeInTheDocument() - expect(select).toHaveBeenCalled() - }) - }) - - test('switches subscriptions when the targeted route changes', async () => { - function RootComponent() { - const [from, setFrom] = useState('/posts') - const routeId = useMatch({ - from, - shouldThrow: false, - select: (match) => match.routeId, - }) - - return ( - <> - <div data-testid="targeted-route">{routeId ?? 'absent'}</div> - <button onClick={() => setFrom('/')}>Select index</button> - <button onClick={() => setFrom('/posts')}>Select posts</button> - <Outlet /> - </> - ) - } - - 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 ( - <> - <div data-testid="targeted-match"> - {targetedRevision === undefined - ? 'Targeted absent' - : `Targeted revision ${targetedRevision}`} - </div> - <Link to="/item" search={{ revision: 2 }}> - Revision 2 - </Link> - <Link to="/item" search={{ revision: 3 }}> - Revision 3 - </Link> - <Link to="/other">Other</Link> - <Outlet /> - </> - ) - } - - function ItemComponent() { - const nearestRevision = useMatch({ - strict: false, - shouldThrow: false, - select: (match) => match.loaderData as number, - }) - return <div>Nearest revision {nearestRevision}</div> - } - - const rootRoute = createRootRoute({ component: RootComponent }) - const itemRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/item', - validateSearch: (search: Record<string, unknown>) => ({ - revision: Number(search.revision), - }), - loaderDeps: ({ search }) => ({ revision: search.revision }), - loader: ({ deps }) => deps.revision, - component: ItemComponent, - }) - const otherRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/other', - component: () => <div>Other route</div>, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([itemRoute, otherRoute]), - history: createMemoryHistory({ initialEntries: ['/item?revision=1'] }), - }) - - render(<RouterProvider router={router} />) - 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 ( - <> - <Link to="/other">Other</Link> - <Outlet /> - </> - ) - } - - function ItemComponent() { - const revision = useMatch({ - strict: false, - select: (match) => match.loaderData as number, - }) - return <div>Item revision {revision}</div> - } - - const rootRoute = createRootRoute({ component: RootComponent }) - const itemRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/item', - validateSearch: (search: Record<string, unknown>) => ({ - revision: Number(search.revision), - }), - loaderDeps: ({ search }) => ({ revision: search.revision }), - loader: ({ deps }) => deps.revision, - component: ItemComponent, - }) - const otherRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/other', - component: () => <div>Other route</div>, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([itemRoute, otherRoute]), - history: createMemoryHistory({ initialEntries: ['/item?revision=1'] }), - }) - - render(<RouterProvider router={router} />) - expect(await screen.findByText('Item revision 1')).toBeInTheDocument() - - let returnNavigation: Promise<void> | 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 3acf185b22..b5f473885f 100644 --- a/packages/react-router/tests/useNavigate.test.tsx +++ b/packages/react-router/tests/useNavigate.test.tsx @@ -1,4 +1,5 @@ import React, { act } from 'react' +import '@testing-library/jest-dom/vitest' import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' import { cleanup, @@ -6,7 +7,6 @@ import { fireEvent, render, screen, - waitFor, } from '@testing-library/react' import { z } from 'zod' @@ -2312,11 +2312,9 @@ describe.each([{ basepath: '' }, { basepath: '/basepath' }])( path: 'param/$param', component: function ParamRoute() { const navigate = useNavigate() - const params = paramRoute.useParams() return ( <> <h1>Param Route</h1> - <span data-testid="param-value">{params.param}</span> <button onClick={() => navigate({ from: paramRoute.fullPath, to: './a' }) @@ -2330,7 +2328,7 @@ describe.each([{ basepath: '' }, { basepath: '/basepath' }])( navigate({ to: '.', params: { param: 'bar' } as any }) } > - Navigate to . with param:bar + Navigate to to . with param:bar </button> <Outlet /> </> @@ -2417,9 +2415,9 @@ describe.each([{ basepath: '' }, { basepath: '/basepath' }])( // Click the link and ensure the new location fireEvent.click(parentLink) - await waitFor(() => { - expect(window.location.pathname).toBe(`${basepath}/a`) - }) + await router.latestLoadPromise + + expect(window.location.pathname).toBe(`${basepath}/a`) }) test('should navigate to the parent route and keep params', async () => { @@ -2437,9 +2435,9 @@ describe.each([{ basepath: '' }, { basepath: '/basepath' }])( // Click the link and ensure the new location fireEvent.click(parentLink) - await waitFor(() => { - expect(window.location.pathname).toBe(`${basepath}/param/foo/a`) - }) + await router.latestLoadPromise + + expect(window.location.pathname).toBe(`${basepath}/param/foo/a`) }) test('should navigate to the parent route and change params', async () => { @@ -2459,9 +2457,9 @@ describe.each([{ basepath: '' }, { basepath: '/basepath' }])( // Click the link and ensure the new location fireEvent.click(parentLink) - await waitFor(() => { - expect(window.location.pathname).toBe(`${basepath}/param/bar/a`) - }) + await router.latestLoadPromise + + expect(window.location.pathname).toBe(`${basepath}/param/bar/a`) }) test('should navigate to a relative link based on render location with basepath', async () => { @@ -2478,9 +2476,9 @@ describe.each([{ basepath: '' }, { basepath: '/basepath' }])( // Click the link and ensure the new location fireEvent.click(relativeLink) - await waitFor(() => { - expect(window.location.pathname).toBe(`${basepath}/param/foo/a`) - }) + await router.latestLoadPromise + + expect(window.location.pathname).toBe(`${basepath}/param/foo/a`) }) test('should navigate to a parent link based on render location', async () => { @@ -2499,9 +2497,9 @@ describe.each([{ basepath: '' }, { basepath: '/basepath' }])( // Click the link and ensure the new location fireEvent.click(relativeLink) - await waitFor(() => { - expect(window.location.pathname).toBe(`${basepath}/param/foo`) - }) + await router.latestLoadPromise + + expect(window.location.pathname).toBe(`${basepath}/param/foo`) }) test('should navigate to a parent link based on active location', async () => { @@ -2517,9 +2515,9 @@ describe.each([{ basepath: '' }, { basepath: '/basepath' }])( // Click the link and ensure the new location fireEvent.click(relativeLink) - await waitFor(() => { - expect(window.location.pathname).toBe(`${basepath}/param/foo/a`) - }) + await router.latestLoadPromise + + expect(window.location.pathname).toBe(`${basepath}/param/foo/a`) }) test('should navigate to same route with different params', async () => { @@ -2529,18 +2527,15 @@ describe.each([{ basepath: '' }, { basepath: '/basepath' }])( await act(async () => { history.push(`${basepath}/param/foo/a/b`) + await router.latestLoadPromise }) - await waitFor(() => { - expect(window.location.pathname).toBe(`${basepath}/param/foo/a/b`) - }) - expect(await screen.findByTestId('param-value')).toHaveTextContent('foo') + expect(window.location.pathname).toBe(`${basepath}/param/foo/a/b`) - const btn = await screen.findByTestId('btn-param-bar') + const btn = screen.getByTestId('btn-param-bar') fireEvent.click(btn) - await waitFor(() => { - expect(screen.getByTestId('param-value')).toHaveTextContent('bar') - expect(window.location.pathname).toBe(`${basepath}/param/bar/a/b`) - }) + await router.latestLoadPromise + + expect(window.location.pathname).toBe(`${basepath}/param/bar/a/b`) }) }, ) diff --git a/packages/react-router/tests/useParams.test.tsx b/packages/react-router/tests/useParams.test.tsx index 19cf096ea0..22ac646cd8 100644 --- a/packages/react-router/tests/useParams.test.tsx +++ b/packages/react-router/tests/useParams.test.tsx @@ -189,8 +189,7 @@ 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() - // Dev-only buildLocation roundtrip validation uses normal matching for links. - expect(mockedfn).toHaveBeenCalled() + expect(mockedfn).not.toHaveBeenCalled() mockedfn.mockClear() await act(() => fireEvent.click(firstPostLink)) diff --git a/packages/react-router/tests/utils.ts b/packages/react-router/tests/utils.ts index da96eb2d95..cdc7ff82bd 100644 --- a/packages/react-router/tests/utils.ts +++ b/packages/react-router/tests/utils.ts @@ -20,25 +20,20 @@ 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<number> 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 deleted file mode 100644 index 92be18587f..0000000000 --- a/packages/react-router/tsconfig.build.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "rootDir": "./src" - }, - "include": ["src"] -} diff --git a/packages/react-router/tsconfig.json b/packages/react-router/tsconfig.json index f406bf1c09..372bb7b491 100644 --- a/packages/react-router/tsconfig.json +++ b/packages/react-router/tsconfig.json @@ -2,8 +2,7 @@ "extends": "../../tsconfig.json", "compilerOptions": { "jsx": "react-jsx", - "jsxImportSource": "react", - "types": ["node"] + "jsxImportSource": "react" }, "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 798d9b74e4..b9e14f9072 100644 --- a/packages/react-router/vite.config.ts +++ b/packages/react-router/vite.config.ts @@ -18,17 +18,15 @@ const config = defineConfig({ watch: false, environment: 'jsdom', typecheck: { enabled: true }, - setupFiles: ['./tests/jest-dom.setup.ts', './tests/setupTests.tsx'], + setupFiles: ['./tests/setupTests.tsx'], }, }) export default mergeConfig( config, tanstackViteConfig({ - tsconfigPath: './tsconfig.build.json', entry: [ './src/index.tsx', - './src/index.rsc.ts', './src/index.dev.tsx', './src/ssr/client.ts', './src/ssr/server.ts', diff --git a/packages/react-start-client/CHANGELOG.md b/packages/react-start-client/CHANGELOG.md index 1cb31dea24..3de3441bf9 100644 --- a/packages/react-start-client/CHANGELOG.md +++ b/packages/react-start-client/CHANGELOG.md @@ -1,725 +1,5 @@ # @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 diff --git a/packages/react-start-client/package.json b/packages/react-start-client/package.json index b919d47b92..d098b360a0 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.168.45", + "version": "1.166.16", "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": "node ../../node_modules/typescript59/lib/tsc.js", - "test:types:ts60": "tsc6", - "test:types:ts70": "tsc", + "test:types:ts59": "tsc", "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", "build": "vite build" }, @@ -48,18 +48,6 @@ "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, @@ -73,25 +61,14 @@ "dependencies": { "@tanstack/react-router": "workspace:*", "@tanstack/router-core": "workspace:*", - "@tanstack/start-client-core": "workspace:*" + "@tanstack/start-client-core": "workspace:*", + "tiny-invariant": "^1.3.3", + "tiny-warning": "^1.0.3" }, "devDependencies": { - "@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:" + "@testing-library/react": "^16.2.0", + "@vitejs/plugin-react": "^4.3.4", + "vite": "*" }, "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 deleted file mode 100644 index e92042a0d7..0000000000 --- a/packages/react-start-client/src/GenericHydrate.tsx +++ /dev/null @@ -1,436 +0,0 @@ -'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<void> } -type PrefetchController = { - abortController: AbortController - hydrationRequested: boolean - hydrationListeners: Set<() => void> - hydrationResolvePending: boolean - started: boolean - promise?: Promise<void> - cleanup?: () => void -} - -const dynamicType = 'dynamic' -const dynamicHydrateStrategy = { - _t: dynamicType, - _d: () => true, -} satisfies HydrationStrategy<typeof dynamicType, false> - -function shouldDeferHydration(strategy: HydrationStrategy) { - return strategy._d ? strategy._d() : strategy._t !== 'load' -} - -function useLatest<T>(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<HydrationStrategy | undefined>( - 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<unknown>() - const latestRef = useLatest({ - prefetch: props.prefetch, - preload: props.p, - }) - const gateRef = React.useRef<HydrationGateRecord | undefined>(undefined) - const markerElementRef = React.useRef<HTMLDivElement | null>(null) - const shouldPreserveServerHTMLRef = React.useRef<boolean | undefined>( - undefined, - ) - const shouldDeferInitialHydrationRef = React.useRef<boolean | undefined>( - undefined, - ) - const didPrefetchRef = React.useRef(false) - const prefetchControllerRef = React.useRef<PrefetchController | undefined>( - 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 ? ( - <div - style={{ display: 'contents' }} - dangerouslySetInnerHTML={{ __html: html }} - /> - ) : null - })() - : (props.fallback ?? null) - const markerAttributes = - markerHydrateType === dynamicType ? undefined : hydrateStrategy._a?.() - - const hydrateType = hydrateStrategy._t! - - if (hydrateType === 'never' && !shouldPreserveServerHTML) { - return ( - <div - ref={markerRef} - {...{ - [hydrateIdAttribute]: gate.id, - [hydrateWhenAttribute]: markerHydrateType, - ...markerAttributes, - }} - > - {props.fallback ?? null} - </div> - ) - } - - return ( - <div - ref={markerRef} - {...{ - [hydrateIdAttribute]: gate.id, - [hydrateWhenAttribute]: markerHydrateType, - ...markerAttributes, - }} - > - <React.Suspense fallback={fallback}> - <HydrationGate gate={gate}> - <HydratedBoundary - id={gate.id} - onHydrated={props.onHydrated} - onStrategyHydrated={(id) => { - markerElementRef.current?.removeAttribute(hydrateWhenAttribute) - hydrateStrategy._o?.(id) - }} - > - {props.children} - </HydratedBoundary> - </HydrationGate> - </React.Suspense> - </div> - ) -} diff --git a/packages/react-start-client/src/Hydrate.tsx b/packages/react-start-client/src/Hydrate.tsx deleted file mode 100644 index 019730f3be..0000000000 --- a/packages/react-start-client/src/Hydrate.tsx +++ /dev/null @@ -1,107 +0,0 @@ -'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<TWhen, TCanPrefetch> & { - _h: (this: ReactHydrationStrategy, props: HydrateProps) => React.JSX.Element -} - -export type HydrationStrategy< - TWhen extends HydrationWhen = HydrationWhen, - TCanPrefetch extends boolean = boolean, -> = ReactHydrationStrategy<TWhen, TCanPrefetch> - -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<void> -} - -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 ( - <div - {...{ - [hydrateIdAttribute]: id, - [hydrateWhenAttribute]: dynamicType, - }} - > - <React.Suspense fallback={props.fallback ?? null}> - {props.children} - </React.Suspense> - </div> - ) -} - -/* @__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 <ServerDynamicHydrate {...props} /> - } - - 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 21f1fa2039..22f4848de7 100644 --- a/packages/react-start-client/src/hydrateStart.ts +++ b/packages/react-start-client/src/hydrateStart.ts @@ -4,6 +4,9 @@ import type { AnyRouter } from '@tanstack/router-core' /** * React-specific wrapper for hydrateStart that signals hydration completion */ -export function hydrateStart(): Promise<AnyRouter> { - return coreHydrateStart().finally(() => window.$_TSR?.h()) +export async function hydrateStart(): Promise<AnyRouter> { + const router = await coreHydrateStart() + // Signal that router hydration is complete so cleanup can happen if stream has ended + window.$_TSR?.h() + return router } diff --git a/packages/react-start-client/src/hydration.ts b/packages/react-start-client/src/hydration.ts deleted file mode 100644 index fad458175c..0000000000 --- a/packages/react-start-client/src/hydration.ts +++ /dev/null @@ -1,22 +0,0 @@ -'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 deleted file mode 100644 index 5ee6d3c3d6..0000000000 --- a/packages/react-start-client/src/hydration/generic.ts +++ /dev/null @@ -1,43 +0,0 @@ -'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 deleted file mode 100644 index 58c7f265eb..0000000000 --- a/packages/react-start-client/src/hydration/idle.ts +++ /dev/null @@ -1,22 +0,0 @@ -'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 deleted file mode 100644 index 006f4e6952..0000000000 --- a/packages/react-start-client/src/hydration/load.tsx +++ /dev/null @@ -1,49 +0,0 @@ -'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 ( - <div> - <React.Suspense fallback={props.fallback ?? null}> - <HydratedBoundary onHydrated={props.onHydrated}> - {props.children} - </HydratedBoundary> - </React.Suspense> - </div> - ) -} - -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 deleted file mode 100644 index 250a8ed1ae..0000000000 --- a/packages/react-start-client/src/hydration/never.tsx +++ /dev/null @@ -1,97 +0,0 @@ -'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<void>(() => {}) - -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<boolean | undefined>( - 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 ? ( - <div - style={{ display: 'contents' }} - dangerouslySetInnerHTML={{ __html: html }} - /> - ) : ( - (props.fallback ?? null) - ) - })() - - return ( - <div {...markerProps}> - <React.Suspense fallback={fallback}> - <NeverGate>{props.children}</NeverGate> - </React.Suspense> - </div> - ) -} - -/* @__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 deleted file mode 100644 index b295d77462..0000000000 --- a/packages/react-start-client/src/hydration/visible.tsx +++ /dev/null @@ -1,141 +0,0 @@ -'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<void> - 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<HTMLDivElement | null>(null) - const [gate] = React.useState<VisibleGate>(() => { - let resolvePromise!: () => void - const nextGate: VisibleGate = { - p: new Promise<void>((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 ( - <div ref={markerRef}> - <React.Suspense fallback={props.fallback}> - <HydrationBoundary g={gate} o={props.onHydrated}> - {props.children} - </HydrationBoundary> - </React.Suspense> - </div> - ) -} - -/* @__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 26e7195c39..6c8a836f08 100644 --- a/packages/react-start-client/src/index.tsx +++ b/packages/react-start-client/src/index.tsx @@ -1,4 +1,3 @@ -'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 new file mode 100644 index 0000000000..4832f074b6 --- /dev/null +++ b/packages/react-start-client/src/renderRSC.tsx @@ -0,0 +1,89 @@ +// 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 deleted file mode 100644 index 2e3726edfa..0000000000 --- a/packages/react-start-client/src/tests/Hydrate.test-d.tsx +++ /dev/null @@ -1,147 +0,0 @@ -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<HydrateProps>() -}) - -test('HydrateOptions supports reusable spread props', () => { - const belowFoldProps = { - when: () => visible({ rootMargin: '800px' }), - } satisfies HydrateOptions - - expectTypeOf(belowFoldProps).toMatchTypeOf<HydrateOptions>() - - const withFunctionPrefetch = { - when: visible(), - split: false, - prefetch: (ctx) => { - expectTypeOf(ctx.element).toEqualTypeOf<Element | null>() - expectTypeOf(ctx.signal).toEqualTypeOf<AbortSignal>() - expectTypeOf(ctx.preload).returns.toEqualTypeOf<Promise<void>>() - expectTypeOf(ctx.waitFor).returns.toEqualTypeOf< - Promise<'prefetch' | 'hydrate' | 'abort'> - >() - }, - } satisfies HydrateOptions - - expectTypeOf(withFunctionPrefetch).toMatchTypeOf<HydrateOptions>() -}) - -test('Hydrate props are exact for strategy and prefetch forms', () => { - expectTypeOf< - Extract<HydrateProps, { prefetch?: never }> - >().branded.toEqualTypeOf<SplitHydrateProps>() - expectTypeOf< - Extract<HydrateProps, { prefetch: HydrationPrefetchStrategy }> - >().branded.toEqualTypeOf<PrefetchHydrateProps>() - expectTypeOf< - Extract<HydrateProps, { prefetch: HydrationPrefetchFunction }> - >().branded.toEqualTypeOf<FunctionPrefetchHydrateProps>() -}) - -test('Hydrate requires a strategy', () => { - expectTypeOf<{ - when: HydrationStrategy - children: ReactNode - }>().toMatchTypeOf<HydrateProps>() - - expectTypeOf<{ - when: () => HydrationStrategy - children: ReactNode - }>().toMatchTypeOf<HydrateProps>() - - expectTypeOf<{ - children: ReactNode - }>().not.toMatchTypeOf<HydrateProps>() - - expectTypeOf<{ - when: () => true - children: ReactNode - }>().not.toMatchTypeOf<HydrateProps>() - - expectTypeOf<{ - when: false - children: ReactNode - }>().not.toMatchTypeOf<HydrateProps>() -}) - -test('Hydrate requires a framework-renderable strategy', () => { - expectTypeOf<CoreHydrationStrategy>().not.toMatchTypeOf<HydrationStrategy>() - expectTypeOf<ReturnType<typeof visible>>().toMatchTypeOf<HydrationStrategy>() - - expectTypeOf<{ - when: CoreHydrationStrategy - children: ReactNode - }>().not.toMatchTypeOf<HydrateProps>() -}) - -test('Hydrate enforces prefetch only with split boundaries', () => { - expectTypeOf<{ - when: HydrationStrategy - prefetch: HydrationPrefetchStrategy - children: ReactNode - }>().toMatchTypeOf<HydrateProps>() - - expectTypeOf<{ - when: HydrationStrategy - prefetch: HydrationPrefetchStrategy - split: true - children: ReactNode - }>().toMatchTypeOf<HydrateProps>() - - expectTypeOf<{ - when: HydrationStrategy - prefetch: HydrationPrefetchStrategy - split: false - children: ReactNode - }>().not.toMatchTypeOf<HydrateProps>() - - expectTypeOf<{ - when: HydrationStrategy - prefetch: HydrationPrefetchFunction - split: false - children: ReactNode - }>().toMatchTypeOf<HydrateProps>() - - expectTypeOf<{ - when: HydrationStrategy - prefetch: HydrationPrefetchFunction - children: ReactNode - }>().toMatchTypeOf<HydrateProps>() -}) diff --git a/packages/react-start-client/src/tests/Hydrate.test.tsx b/packages/react-start-client/src/tests/Hydrate.test.tsx deleted file mode 100644 index 0e7abe502a..0000000000 --- a/packages/react-start-client/src/tests/Hydrate.test.tsx +++ /dev/null @@ -1,763 +0,0 @@ -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<void>; 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 ( - <button - data-testid="child" - data-hydrated={hydrated ? 'true' : 'false'} - onClick={() => setCount((prev) => prev + 1)} - > - {count} - </button> - ) -} - -function NamedInteractiveChild(props: { id: string }) { - const [hydrated, setHydrated] = React.useState(false) - - React.useEffect(() => { - setHydrated(true) - }, []) - - return ( - <button - data-testid={`child-${props.id}`} - data-hydrated={hydrated ? 'true' : 'false'} - > - {props.id} - </button> - ) -} - -function createSuspendingChild() { - let resolve!: () => void - let resolved = false - const promise = new Promise<void>((resolvePromise) => { - resolve = () => { - resolved = true - resolvePromise() - } - }) - - function SuspendingChild() { - if (!resolved) { - throw promise - } - - return <div data-testid="child">child</div> - } - - 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<typeof hydrateRoot> - await act(async () => { - root = hydrateRoot(container, ui) - await Promise.resolve() - }) - - return { container, html, root } -} - -async function unmountHydratedRoot( - root: ReturnType<typeof hydrateRoot>, - 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( - <Hydrate - when={interaction({ events: 'dblclick' })} - fallback={<div data-testid="fallback">fallback</div>} - > - <InteractiveChild /> - </Hydrate>, - ) - - 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( - <Hydrate - when={interaction({ events: ['contextmenu', 'dblclick'] })} - fallback={<div data-testid="fallback">fallback</div>} - > - <InteractiveChild /> - </Hydrate>, - ) - - 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( - <Hydrate when={never()}> - <InteractiveChild /> - </Hydrate>, - ) - - expect(screen.queryByTestId('child')).toBeNull() - }) - - it('shows fallback for a client-only mount while children suspend', async () => { - const { resolve, SuspendingChild } = createSuspendingChild() - - await renderAsync( - <Hydrate - when={load()} - fallback={<div data-testid="fallback">fallback</div>} - > - <SuspendingChild /> - </Hydrate>, - ) - - 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( - <Hydrate - when={never()} - fallback={<div data-testid="fallback">fallback</div>} - > - <InteractiveChild /> - </Hydrate>, - ) - - 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( - <> - <InternalHydrate when={interaction()} h="shared-boundary"> - <NamedInteractiveChild id="one" /> - </InternalHydrate> - <InternalHydrate when={interaction()} h="shared-boundary"> - <NamedInteractiveChild id="two" /> - </InternalHydrate> - </>, - ) - - 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 = ( - <Hydrate when={load()} onHydrated={onHydrated}> - <div data-testid="child">child</div> - </Hydrate> - ) - - 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<typeof hydrateRoot> - 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( - <InternalHydrate - when={interaction()} - prefetch={idle({ timeout: 1 })} - p={preload} - > - <InteractiveChild /> - </InternalHydrate>, - ) - - 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( - <Hydrate when={when}> - <InteractiveChild /> - </Hydrate>, - ) - 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<typeof hydrateRoot> - try { - await act(async () => { - root = hydrateRoot( - container, - <Hydrate when={when}> - <InteractiveChild /> - </Hydrate>, - ) - 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( - <Hydrate when={when}> - <InteractiveChild /> - </Hydrate>, - ) - 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<typeof hydrateRoot> - try { - await act(async () => { - root = hydrateRoot( - container, - <Hydrate when={when}> - <InteractiveChild /> - </Hydrate>, - ) - 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<void>((resolve) => { - resolvePrefetch = resolve - }) - const waitReasons: Array<string> = [] - const neverPrefetches = { - _t: 'idle', - _s: () => () => {}, - } as HydrationPrefetchStrategy<'idle'> - - const { container, root } = await hydrateFromServer( - <InternalHydrate - when={interaction()} - prefetch={async ({ waitFor, preload }) => { - waitReasons.push(await waitFor(neverPrefetches)) - await preload() - await prefetchBlocker - }} - p={preload} - > - <InteractiveChild /> - </InternalHydrate>, - ) - - 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 ( - <> - <button data-testid="ready" onClick={() => setReady(true)}> - ready - </button> - <Hydrate when={condition(ready)}> - <InteractiveChild /> - </Hydrate> - </> - ) - } - - const { container, root } = await hydrateFromServer(<ConditionHarness />) - - 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<void>((resolve) => { - resolvePrefetch = resolve - }) - - const { container, root } = await hydrateFromServer( - <InternalHydrate - when={interaction()} - prefetch={() => { - void prefetchBlocker - }} - > - <InteractiveChild /> - </InternalHydrate>, - ) - - 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<AbortSignal> = [] - - const { container, root } = await hydrateFromServer( - <InternalHydrate - when={interaction()} - prefetch={({ signal }) => { - signals.push(signal) - return new Promise<void>(() => {}) - }} - > - <InteractiveChild /> - </InternalHydrate>, - ) - - 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( - <Hydrate when={idle({ timeout: 1000 })}> - <Hydrate when={interaction()}> - <InteractiveChild /> - </Hydrate> - </Hydrate>, - ) - - 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) => ( - <Hydrate - when={visible()} - fallback={<p>fallback</p>} - onHydrated={onHydrated} - > - <p>child</p> - </Hydrate> - ) - vi.stubGlobal('window', undefined) - const html = renderToString(app()) - vi.unstubAllGlobals() - const failed: Array<{ tasks: number; errors: Array<string> }> = [] - 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<string> = [] - const hydrated = new Promise<void>((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 b020676956..e7d8c7be08 100644 --- a/packages/react-start-client/src/tests/createServerFn.test-d.tsx +++ b/packages/react-start-client/src/tests/createServerFn.test-d.tsx @@ -24,9 +24,7 @@ test('createServerFn returns async array', () => { return result }) - expectTypeOf<ReturnType<typeof serverFn>>().toEqualTypeOf< - Promise<Array<{ a: number }>> - >() + expectTypeOf(serverFn()).toEqualTypeOf<Promise<Array<{ a: number }>>>() }) test('createServerFn returns sync array', () => { @@ -35,9 +33,7 @@ test('createServerFn returns sync array', () => { return result }) - expectTypeOf<ReturnType<typeof serverFn>>().toEqualTypeOf< - Promise<Array<{ a: number }>> - >() + expectTypeOf(serverFn()).toEqualTypeOf<Promise<Array<{ a: number }>>>() }) test('createServerFn returns async union', () => { @@ -46,9 +42,7 @@ test('createServerFn returns async union', () => { return result }) - expectTypeOf<ReturnType<typeof serverFn>>().toEqualTypeOf< - Promise<string | number> - >() + expectTypeOf(serverFn()).toEqualTypeOf<Promise<string | number>>() }) test('createServerFn returns sync union', () => { @@ -57,7 +51,5 @@ test('createServerFn returns sync union', () => { return result }) - expectTypeOf<ReturnType<typeof serverFn>>().toEqualTypeOf< - Promise<string | number> - >() + expectTypeOf(serverFn()).toEqualTypeOf<Promise<string | number>>() }) diff --git a/packages/react-start-client/src/tests/hydrateStart.test.ts b/packages/react-start-client/src/tests/hydrateStart.test.ts deleted file mode 100644 index 2d34400009..0000000000 --- a/packages/react-start-client/src/tests/hydrateStart.test.ts +++ /dev/null @@ -1,33 +0,0 @@ -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 deleted file mode 100644 index 92be18587f..0000000000 --- a/packages/react-start-client/tsconfig.build.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "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 1ffe6f0c62..51dda9abf2 100644 --- a/packages/react-start-client/tsconfig.json +++ b/packages/react-start-client/tsconfig.json @@ -2,8 +2,7 @@ "extends": "../../tsconfig.json", "compilerOptions": { "jsx": "react-jsx", - "module": "esnext", - "types": ["node"] + "module": "esnext" }, "include": ["src", "vite.config.ts"] } diff --git a/packages/react-start-client/vite.config.ts b/packages/react-start-client/vite.config.ts index 19e0d79d19..f3f7ba2f12 100644 --- a/packages/react-start-client/vite.config.ts +++ b/packages/react-start-client/vite.config.ts @@ -18,9 +18,8 @@ const config = defineConfig({ export default mergeConfig( config, tanstackViteConfig({ - tsconfigPath: './tsconfig.build.json', srcDir: './src', - entry: ['./src/index.tsx', './src/Hydrate.tsx', './src/hydration.ts'], + entry: './src/index.tsx', cjs: false, }), ) diff --git a/packages/react-start-rsc/CHANGELOG.md b/packages/react-start-rsc/CHANGELOG.md deleted file mode 100644 index fae6bcabee..0000000000 --- a/packages/react-start-rsc/CHANGELOG.md +++ /dev/null @@ -1,1114 +0,0 @@ -# @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<any>`. ([#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 deleted file mode 100644 index daf1baa88a..0000000000 --- a/packages/react-start-rsc/eslint.config.js +++ /dev/null @@ -1,58 +0,0 @@ -// @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 deleted file mode 100644 index 40b1847068..0000000000 --- a/packages/react-start-rsc/package.json +++ /dev/null @@ -1,146 +0,0 @@ -{ - "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 deleted file mode 100644 index 01e494049e..0000000000 --- a/packages/react-start-rsc/src/ClientSlot.tsx +++ /dev/null @@ -1,34 +0,0 @@ -'use client' - -import { useSlotContext } from './SlotContext' - -export interface ClientSlotProps { - slot: string - args: Array<unknown> -} - -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 deleted file mode 100644 index e6c81aa69a..0000000000 --- a/packages/react-start-rsc/src/CompositeComponent.tsx +++ /dev/null @@ -1,165 +0,0 @@ -'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<string, unknown>): { - 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<string> - slotProps?: Record<string, unknown> -}): 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<string, unknown>)[key] - } - - if (tree === null || tree === undefined) return null - - const { implementations, strict } = splitSlotProps(slotProps) - - return ( - <SlotProvider implementations={implementations} strict={strict}> - {tree as React.ReactNode} - </SlotProvider> - ) -} - -function CompositeRenderComponent({ - getTree, - path, - slotProps, - cssHrefs, - jsPreloads, -}: { - getTree: () => unknown - path: Array<string> - slotProps?: Record<string, unknown> - cssHrefs?: ReadonlySet<string> - jsPreloads?: ReadonlySet<string> -}): 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 ( - <> - <Suspense fallback={<EmptyFallback />}> - <CompositeRenderInner - getTree={getTree} - path={path} - slotProps={slotProps} - /> - </Suspense> - </> - ) -} - -/** - * 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) => ( - * <div> - * <header>{props.header('Dashboard')}</header> - * <main>{props.children}</main> - * </div> - * )) - * - * // In route component - * return ( - * <CompositeComponent src={src} header={(title) => <h1>{title}</h1>}> - * <p>Main content</p> - * </CompositeComponent> - * ) - * ``` - */ -export function CompositeComponent<TComp extends AnyCompositeComponent>( - props: CompositeComponentProps<TComp>, -): TComp['~types']['return'] { - const { src, ...slotProps } = props - - const stream = src[SERVER_COMPONENT_STREAM] - - if (!stream) { - throw new Error( - '[tanstack/start] <CompositeComponent> 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] <CompositeComponent> missing getTree on RSC src. ' + - 'Make sure src comes from createCompositeComponent().', - ) - } - - return ( - <CompositeRenderComponent - getTree={getTree} - path={path} - slotProps={slotProps} - cssHrefs={cssHrefs} - jsPreloads={jsPreloads} - /> - ) -} - -export type CompositeComponentProps<TComp extends AnyCompositeComponent> = { - src: TComp -} & TComp['~types']['props'] diff --git a/packages/react-start-rsc/src/ReplayableStream.ts b/packages/react-start-rsc/src/ReplayableStream.ts deleted file mode 100644 index 4c3e878c79..0000000000 --- a/packages/react-start-rsc/src/ReplayableStream.ts +++ /dev/null @@ -1,249 +0,0 @@ -/** - * 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<T = Uint8Array> { - // Marker for cross-environment instance checking - readonly [REPLAYABLE_STREAM_MARKER] = true - - private chunks: Array<T> = [] - private done = false - private error: unknown = null - private waiter: PromiseWithResolvers<void> | null = null - private aborted = false - private released = false - - private sourceReader: ReadableStreamDefaultReader<T> | null = null - private abortSignal: AbortSignal | undefined - private abortListener: (() => void) | null = null - - constructor( - private source: ReadableStream<T>, - 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<void> { - if (this.done || this.released) return Promise.resolve() - if (!this.waiter) { - this.waiter = Promise.withResolvers<void>() - } - 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<T> { - if (this.released) { - return new ReadableStream<T>({ - start(controller) { - controller.close() - }, - }) - } - - let index = 0 - - return new ReadableStream<T>({ - 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 deleted file mode 100644 index 430f24ad0f..0000000000 --- a/packages/react-start-rsc/src/RscNodeRenderer.tsx +++ /dev/null @@ -1,76 +0,0 @@ -'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<string> -}): 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<string, unknown>)[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<string> - | undefined - const jsPreloads = data[SERVER_COMPONENT_JS_PRELOADS] as - | ReadonlySet<string> - | undefined - - const path = (data[RSC_PROXY_PATH] as Array<string> | 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 ( - <> - <Suspense fallback={<EmptyFallback />}> - <RscNodeRenderInner getTree={getTree} path={path} /> - </Suspense> - </> - ) -} diff --git a/packages/react-start-rsc/src/ServerComponentTypes.ts b/packages/react-start-rsc/src/ServerComponentTypes.ts deleted file mode 100644 index 5e1fa32a52..0000000000 --- a/packages/react-start-rsc/src/ServerComponentTypes.ts +++ /dev/null @@ -1,216 +0,0 @@ -import type { - Constrain, - LooseAsyncReturnType, - LooseReturnType, - ValidateSerializable, -} from '@tanstack/router-core' -import type { ComponentProps, ComponentType } from 'react' - -export interface ServerComponentStream { - createReplayStream: () => ReadableStream<Uint8Array> -} - -// 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 <CompositeComponent src={...} />) -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<any> -} - -/** - * 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<TComp> = Constrain< - TComp, - ( - props: ValidateCompositeComponentProps<TComp>, - ) => ValidateCompositeComponentReturnType<TComp> -> - -export type ValidateCompositeComponentProps<TComp> = unknown extends TComp - ? TComp - : ValidateCompositeComponentPropsObject<CompositeComponentProps<TComp>> - -export type ValidateCompositeComponentPropsObject<TProps> = - unknown extends TProps - ? TProps - : { - [TKey in keyof TProps]: ValidateCompositeComponentProp<TProps[TKey]> - } - -export type CompositeComponentProps<TComp> = TComp extends ( - props: infer TProps, -) => any - ? TProps - : unknown - -export type ValidateCompositeComponentProp<TProp> = TProp extends ( - ...args: Array<any> -) => any - ? (...args: ValidateReactSerializable<Parameters<TProp>>) => React.ReactNode - : TProp extends ComponentType<any> - ? ComponentType<ValidateReactSerializable<ComponentProps<TProp>>> - : TProp extends React.ReactNode - ? TProp - : React.ReactNode - -export type ValidateReactSerializable<T> = ValidateSerializable< - T, - ReactSerializable -> - -export type ReactSerializable = - | number - | string - | bigint - | boolean - | null - | undefined - | React.ReactNode - -export type ValidateCompositeComponentReturnType<TComp> = unknown extends TComp - ? React.ReactNode - : ValidateCompositeComponentResult<LooseReturnType<TComp>> - -export type ValidateCompositeComponentResult<TNode> = - ValidateServerComponentResult<TNode> - -export type ValidateServerComponentResult<TNode> = - TNode extends Promise<any> - ? ValidateCompositeComponentPromiseResult<TNode> - : TNode extends React.ReactNode - ? TNode - : TNode extends (...args: Array<any>) => any - ? React.ReactNode - : TNode extends object - ? ValidateCompositeComponentObjectResult<TNode> - : React.ReactNode - -export type ValidateCompositeComponentPromiseResult<TPromise> = - TPromise extends Promise<infer T> - ? Promise<ValidateCompositeComponentResult<T>> - : never - -export type ValidateCompositeComponentObjectResult<TObject> = { - [TKey in keyof TObject]: ValidateCompositeComponentResult<TObject[TKey]> -} - -export type CompositeComponentResult<TComp> = CompositeComponentBuilder< - TComp, - LooseAsyncReturnType<TComp> -> - -export type CompositeComponentBuilder<TComp, TReturn> = - TReturn extends React.ReactNode - ? CompositeComponent<TComp, TReturn> - : { - [TKey in keyof TReturn]: CompositeComponentBuilder<TComp, TReturn[TKey]> - } - -export interface CompositeComponent<in out TComp, in out TReturn> { - '~types': { - props: CompositeComponentProps<TComp> - return: TReturn - } - - [SERVER_COMPONENT_STREAM]?: ServerComponentStream - - /** - * Root decoded tree getter. - */ - [RSC_PROXY_GET_TREE]?: () => unknown - /** - * Nested selection path (eg ['content','Stats']). - * Used by <CompositeComponent/> to render a sub-tree. - */ - [RSC_PROXY_PATH]?: Array<string> - /** - * CSS hrefs collected from the RSC stream. - * Can be used for preloading in <head> or emitting 103 Early Hints. - */ - [SERVER_COMPONENT_CSS_HREFS]?: ReadonlySet<string> - - /** - * 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<string> - - /** - * 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<RscSlotUsageEvent> -} - -export type ValidateRenderableServerComponent<TNode> = - ValidateServerComponentResult<TNode> - -export type RenderableServerComponentBuilder<T> = T extends React.ReactNode - ? RenderableServerComponent<T> - : { [TKey in keyof T]: RenderableServerComponentBuilder<T[TKey]> } - -export type RenderableServerComponent<TNode extends React.ReactNode> = TNode & - RenderableServerComponentAttributes<TNode> - -export interface RenderableServerComponentAttributes<TNode> { - '~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<any, any> - -export type AnyRenderableServerComponent = - RenderableServerComponentAttributes<any> diff --git a/packages/react-start-rsc/src/SlotContext.tsx b/packages/react-start-rsc/src/SlotContext.tsx deleted file mode 100644 index a3d0f867a1..0000000000 --- a/packages/react-start-rsc/src/SlotContext.tsx +++ /dev/null @@ -1,42 +0,0 @@ -'use client' - -import { createContext, use } from 'react' -import type { SlotImplementations } from './types' - -export interface SlotContextValue { - implementations: SlotImplementations - strict: boolean -} - -const SlotContext = createContext<SlotContextValue | null>(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 ( - <SlotContext value={{ implementations, strict: strict ?? false }}> - {children} - </SlotContext> - ) -} diff --git a/packages/react-start-rsc/src/awaitLazyElements.ts b/packages/react-start-rsc/src/awaitLazyElements.ts deleted file mode 100644 index a0d8c5774e..0000000000 --- a/packages/react-start-rsc/src/awaitLazyElements.ts +++ /dev/null @@ -1,94 +0,0 @@ -import { ReactElement, ReactLazy, ReactSuspense } from './reactSymbols' - -/** - * Optional callback for collecting CSS hrefs during tree traversal. - * Only called server-side when processing <link rel="stylesheet" data-rsc-css-href> - */ -export type CssHrefCollector = (href: string) => void - -/** - * Yields pending lazy element payloads from a tree, stopping at Suspense boundaries. - * Also collects CSS hrefs from <link rel="stylesheet" data-rsc-css-href> elements. - */ -function* findPendingLazyPayloads( - obj: unknown, - seen = new Set(), - cssCollector?: CssHrefCollector, -): Generator<PromiseLike<unknown>> { - 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 <link rel="stylesheet" data-rsc-css-href> - // 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 <link rel="stylesheet" data-rsc-css-href> - * elements for preloading in <head>. - * - * @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<void> { - 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 deleted file mode 100644 index 8dd058ae15..0000000000 --- a/packages/react-start-rsc/src/createCompositeComponent.stub.ts +++ /dev/null @@ -1,20 +0,0 @@ -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<TComp>( - _component: ValidateCompositeComponent<TComp>, -): Promise<CompositeComponentResult<TComp>> { - 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 deleted file mode 100644 index 02a840dc64..0000000000 --- a/packages/react-start-rsc/src/createCompositeComponent.ts +++ /dev/null @@ -1,341 +0,0 @@ -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 `<CompositeComponent src={...} />`. - * - * @example - * ```tsx - * const src = await createCompositeComponent((props) => ( - * <div> - * <header>{props.header('Dashboard')}</header> - * <main>{props.children}</main> - * </div> - * )) - * - * // In route component - * return ( - * <CompositeComponent src={src} header={(title) => <h1>{title}</h1>}> - * <p>Main content</p> - * </CompositeComponent> - * ) - * ``` - */ -export async function createCompositeComponent<TComp>( - component: ValidateCompositeComponent<TComp>, - options?: RscCssEnvelopeOptions, -): Promise<CompositeComponentResult<TComp>> { - const isDev = process.env.NODE_ENV === 'development' - - // Dev-only: stream slot usage events (slot + raw args) - const slotUsagesEmitter = isDev - ? createReadableStreamEmitter<RscSlotUsageEvent>() - : 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<TComp> - } - - // 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<TComp> -} - -/** - * Creates a composite handle for server function responses. - * No proxy needed - the client will decode and create its own proxy. - */ -function createCompositeHandle( - flightStream: ReadableStream<Uint8Array>, - options?: { - slotUsagesStream?: ReadableStream<RscSlotUsageEvent> - }, -): 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<any>) => React.ReactNode) - | React.ReactNode - | undefined - children?: React.ReactNode -} - -interface SlotProxyResult<TSlotProps extends object> { - proxy: TSlotProps & SlotPropsBase -} - -/** - * Proxy that turns property access into ClientSlot renders. - * Also tracks accessed slot names for devtools. - */ -function createSlotProxy<TSlotProps extends object>(options?: { - onSlotCall?: (name: string, args: Array<any>) => void -}): SlotProxyResult<TSlotProps> { - const cache = new Map<string, (...args: Array<any>) => 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<any>) => { - options?.onSlotCall?.(prop, args) - return createElement(ClientSlot, { slot: prop, args }) - } - cache.set(prop, fn) - } - return fn - }, - }) - - return { - proxy, - } -} - -function createReadableStreamEmitter<T>(): { - stream: ReadableStream<T> - emit: (value: T) => void - close: () => void -} { - let closed = false - const queue: Array<T> = [] - let controller: ReadableStreamDefaultController<T> | null = null - - const stream = new ReadableStream<T>({ - 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<T>( - source: ReadableStream<T>, - handlers: { - onDone?: () => void - onCancel?: () => void - onError?: () => void - }, -): ReadableStream<T> { - const reader = source.getReader() - let finished = false - - const finish = () => { - if (finished) return - finished = true - handlers.onDone?.() - try { - reader.releaseLock() - } catch { - // Ignore - } - } - - return new ReadableStream<T>({ - 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 deleted file mode 100644 index e5e1481848..0000000000 --- a/packages/react-start-rsc/src/createRscProxy.tsx +++ /dev/null @@ -1,294 +0,0 @@ -'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<string> // CSS hrefs collected from the RSC stream - jsPreloads?: ReadonlySet<string> // JS hrefs collected from the RSC stream - renderable?: boolean // If true, proxy masquerades as React element - slotUsagesStream?: ReadableStream<RscSlotUsageEvent> // 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 `<CompositeComponent src={...} />`. - */ -export function createRscProxy<T>( - 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<RscSlotUsageEvent> | 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<string> - stream: unknown | undefined - cssHrefs: ReadonlySet<string> | undefined - jsPreloads: ReadonlySet<string> | undefined - renderable: boolean - slotUsages: Array<RscSlotUsageEvent> | undefined - slotUsagesStream: ReadableStream<RscSlotUsageEvent> | 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<string, any>() - - 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<string>, - stream: unknown | undefined, - cssHrefs: ReadonlySet<string> | undefined, - jsPreloads: ReadonlySet<string> | undefined, -): any { - return createRscProxyInternal({ - getTree, - path, - stream, - cssHrefs, - jsPreloads, - renderable: true, - slotUsages: undefined, - slotUsagesStream: undefined, - }) -} - -function createRscProxyWithPath( - getTree: () => unknown, - path: Array<string>, - stream: unknown | undefined, - cssHrefs: ReadonlySet<string> | undefined, - jsPreloads: ReadonlySet<string> | undefined, - slotUsages: Array<RscSlotUsageEvent> | undefined, - slotUsagesStream: ReadableStream<RscSlotUsageEvent> | undefined, -): any { - return createRscProxyInternal({ - getTree, - path, - stream, - cssHrefs, - jsPreloads, - renderable: false, - slotUsages, - slotUsagesStream, - }) -} - -async function consumeSlotUsages( - stream: ReadableStream<RscSlotUsageEvent>, - slotUsages: Array<RscSlotUsageEvent>, -): Promise<void> { - 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 deleted file mode 100644 index 2616b96f44..0000000000 --- a/packages/react-start-rsc/src/createServerComponentFromStream.ts +++ /dev/null @@ -1,138 +0,0 @@ -'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<string> - jsPreloads?: Iterable<string> -} - -/** - * 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<Uint8Array>, - 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 `<CompositeComponent src={...} />` - */ -export function createCompositeFromStream( - stream: ReadableStream<Uint8Array>, - options?: { - slotUsagesStream?: ReadableStream<RscSlotUsageEvent> - } & 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<Uint8Array>, - options?: StreamDecodeOptions, -): { - getTree: () => unknown - streamWrapper: ServerComponentStream - cssHrefs: Set<string> - jsPreloads: Set<string> | 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<unknown> | 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 deleted file mode 100644 index be20ea26af..0000000000 --- a/packages/react-start-rsc/src/entry/rsc.tsx +++ /dev/null @@ -1,23 +0,0 @@ -/** - * 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<Uint8Array> { - 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 deleted file mode 100644 index 00f2a2ee02..0000000000 --- a/packages/react-start-rsc/src/entry/virtual-modules.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -// 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<any>) => Promise<any> - export function getServerFnById( - id: string, - access: ServerFnLookupAccess, - ): Promise<ServerFn> -} diff --git a/packages/react-start-rsc/src/flight.rsc.ts b/packages/react-start-rsc/src/flight.rsc.ts deleted file mode 100644 index 8fabd523e2..0000000000 --- a/packages/react-start-rsc/src/flight.rsc.ts +++ /dev/null @@ -1,17 +0,0 @@ -/** - * 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(<MyServerComponent />) - * 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 deleted file mode 100644 index 872eec6f10..0000000000 --- a/packages/react-start-rsc/src/flight.stub.ts +++ /dev/null @@ -1,15 +0,0 @@ -/** - * 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<Uint8Array> { - 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 deleted file mode 100644 index 1639120322..0000000000 --- a/packages/react-start-rsc/src/flight.ts +++ /dev/null @@ -1,68 +0,0 @@ -/** - * 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<Uint8Array>): Promise<React.ReactNode> => { - const { createFromReadableStream: decode } = - await import('virtual:tanstack-rsc-ssr-decode') - return decode(stream) as React.ReactNode - }, - ) - .client( - async (stream: ReadableStream<Uint8Array>): Promise<React.ReactNode> => { - 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<Response>): Promise<React.ReactNode> => { - 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 deleted file mode 100644 index 258d41eb5c..0000000000 --- a/packages/react-start-rsc/src/global.d.ts +++ /dev/null @@ -1,99 +0,0 @@ -/// <reference types="vite/client" /> - -declare module '@rspack/core/rsc/ssr' { - export function setOnClientReference( - callback: - | ((reference: { - id: string - deps: { js: Array<string>; css: Array<string> } - runtime: 'rsbuild' - }) => void) - | null - | undefined, - ): void - export function getManifest(): { - moduleCssFiles?: Record<string, Array<string>> - [key: string]: unknown - } -} - -declare module '@rspack/core/rsc/browser' { - export function getManifest(): { - moduleCssFiles?: Record<string, Array<string>> - [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<T>( - data: T, - options?: object, - ): ReadableStream<Uint8Array> - export function createFromReadableStream<T = unknown>( - stream: ReadableStream<Uint8Array>, - options?: object, - ): Promise<T> - export function createTemporaryReferenceSet(): object - export function decodeReply<T = unknown>( - body: string | FormData, - options?: object, - ): Promise<T> - export function loadServerAction(id: string): Promise<(...args: any) => any> - export function decodeAction<T = unknown>( - body: FormData, - serverManifest?: unknown, - ): Promise<() => T> - export function decodeFormState<T = unknown>( - actionResult: T, - body: FormData, - serverManifest?: unknown, - ): Promise<unknown> -} - -declare module 'virtual:tanstack-rsc-browser-decode' { - export function createFromReadableStream<T = unknown>( - stream: ReadableStream<Uint8Array>, - options?: object, - ): Promise<T> - export function createFromFetch<T = unknown>( - response: Promise<Response>, - ): Promise<T> -} - -declare module 'virtual:tanstack-rsc-ssr-decode' { - export function setOnClientReference( - callback: - | ((reference: { - id: string - deps: { js: Array<string>; css: Array<string> } - runtime?: 'rsbuild' - }) => void) - | undefined, - ): void - export function createFromReadableStream<T = unknown>( - stream: ReadableStream<Uint8Array>, - options?: object, - ): Promise<T> -} - -/** - * 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 deleted file mode 100644 index 6873fc4a0e..0000000000 --- a/packages/react-start-rsc/src/index.rsc.ts +++ /dev/null @@ -1,31 +0,0 @@ -// 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 deleted file mode 100644 index f70e324082..0000000000 --- a/packages/react-start-rsc/src/index.ts +++ /dev/null @@ -1,32 +0,0 @@ -// 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 deleted file mode 100644 index 15b882ccd7..0000000000 --- a/packages/react-start-rsc/src/plugin/rscCssTransform.ts +++ /dev/null @@ -1,150 +0,0 @@ -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<StartCompilerImportTransform> { - 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 deleted file mode 100644 index 9aa9523c6a..0000000000 --- a/packages/react-start-rsc/src/plugin/vite.ts +++ /dev/null @@ -1,238 +0,0 @@ -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 deleted file mode 100644 index 3507e6368f..0000000000 --- a/packages/react-start-rsc/src/react-server-dom-rspack.d.ts +++ /dev/null @@ -1,57 +0,0 @@ -/** - * 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<T = unknown>( - stream: ReadableStream<Uint8Array>, - options?: object, - ): Promise<T> -} - -declare module 'react-server-dom-rspack/client.browser' { - export function createFromReadableStream<T = unknown>( - stream: ReadableStream<Uint8Array>, - options?: object, - ): Promise<T> - - export function createFromFetch<T = unknown>( - fetchPromise: Promise<Response>, - options?: object, - ): Promise<T> -} - -declare module 'react-server-dom-rspack/server' { - export function renderToReadableStream<T>( - data: T, - options?: object, - ): ReadableStream<Uint8Array> - - export function createFromReadableStream<T = unknown>( - stream: ReadableStream<Uint8Array>, - options?: object, - ): Promise<T> - - export function createTemporaryReferenceSet(): object - - export function decodeReply<T = unknown>( - body: string | FormData, - options?: object, - ): Promise<T> - - export function loadServerAction(id: string): Promise<(...args: any) => any> - - export function decodeAction<T = unknown>( - body: FormData, - serverManifest?: unknown, - ): Promise<() => T> - - export function decodeFormState<T = unknown>( - actionResult: T, - body: FormData, - serverManifest?: unknown, - ): Promise<unknown> -} diff --git a/packages/react-start-rsc/src/reactSymbols.ts b/packages/react-start-rsc/src/reactSymbols.ts deleted file mode 100644 index c4349a6afc..0000000000 --- a/packages/react-start-rsc/src/reactSymbols.ts +++ /dev/null @@ -1,6 +0,0 @@ -// 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 deleted file mode 100644 index aefff84206..0000000000 --- a/packages/react-start-rsc/src/renderServerComponent.stub.ts +++ /dev/null @@ -1,26 +0,0 @@ -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<TNode>( - _node: ValidateRenderableServerComponent<TNode>, -): Promise<RenderableServerComponentBuilder<TNode>> { - // 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 deleted file mode 100644 index 4ef6037821..0000000000 --- a/packages/react-start-rsc/src/renderServerComponent.ts +++ /dev/null @@ -1,112 +0,0 @@ -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(<MyServerComponent foo="bar" />) - * - * // In the route component - * return ( - * <div> - * {data} - * {data.sidebar.Menu} - * </div> - * ) - * ``` - */ -export async function renderServerComponent<TNode>( - node: ValidateRenderableServerComponent<TNode>, - options?: RscCssEnvelopeOptions, -): Promise<RenderableServerComponentBuilder<TNode>> { - 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<TNode> - } - - // Server function call path: return a handle for serialization - return createRenderableHandle( - flightStream, - ) as unknown as RenderableServerComponentBuilder<TNode> -} - -/** - * Creates a renderable handle for server function responses. - * Tagged with RENDERABLE_RSC for the serialization adapter. - */ -function createRenderableHandle( - flightStream: ReadableStream<Uint8Array>, -): 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 deleted file mode 100644 index 040e3e6bd9..0000000000 --- a/packages/react-start-rsc/src/rsbuild/browser-decode.ts +++ /dev/null @@ -1,11 +0,0 @@ -/** - * 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 deleted file mode 100644 index 30054d9144..0000000000 --- a/packages/react-start-rsc/src/rsbuild/ssr-decode.ts +++ /dev/null @@ -1,128 +0,0 @@ -/** - * 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<string> - css: Array<string> -} - -type OnClientReference = (reference: { - id: string - deps: ClientReferenceDeps - runtime: 'rsbuild' -}) => void - -type ImportManifestEntry = { - id: string - chunks: Array<string> - cssFiles?: Array<string> - name: string - async?: boolean -} - -type ClientManifest = Record<string, ImportManifestEntry> -type ServerConsumerModuleMap = null | Record< - string, - Record<string, ImportManifestEntry> -> -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<string, ClientReferenceDeps> | 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<T = unknown>( - stream: ReadableStream<Uint8Array>, - options?: object, -): Promise<T> { - return decodeFlightStream<T>(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 deleted file mode 100644 index 54e1ac4932..0000000000 --- a/packages/react-start-rsc/src/rscCssEnvelope.ts +++ /dev/null @@ -1,38 +0,0 @@ -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<TValue>( - value: TValue, - options?: RscCssEnvelopeOptions, -): TValue | Record<string, unknown> { - 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<string, unknown> - 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 deleted file mode 100644 index 2969c926cf..0000000000 --- a/packages/react-start-rsc/src/rscSsrHandler.ts +++ /dev/null @@ -1,39 +0,0 @@ -import type { - RscSlotUsageEvent, - ServerComponentStream, -} from './ServerComponentTypes' - -/** - * Result from decoding an RSC stream for SSR. - */ -export interface RscDecodeResult { - tree: unknown - cssHrefs?: Set<string> - jsPreloads?: Set<string> -} - -/** - * 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<RscDecodeResult> - /** 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<RscSlotUsageEvent>, - ) => 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 deleted file mode 100644 index 5bf8fd7d79..0000000000 --- a/packages/react-start-rsc/src/serialization.client.ts +++ /dev/null @@ -1,54 +0,0 @@ -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<Uint8Array> - slotUsagesStream?: ReadableStream<RscSlotUsageEvent> - cssHrefs?: Array<string> - jsPreloads?: Array<string> -} - -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 deleted file mode 100644 index ee9ad0eca8..0000000000 --- a/packages/react-start-rsc/src/serialization.server.ts +++ /dev/null @@ -1,230 +0,0 @@ -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<Set<string>>() -const proxyJsCollectorStorage = new AsyncLocalStorage<Set<string>>() - -setOnClientReference( - ({ - deps, - runtime, - }: { - deps: { js: Array<string>; css: Array<string> } - 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<string>() - 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<RscDecodeResult> { - 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<string>() - const proxyJsCollector = new Set<string>() - - 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<any> - | 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 deleted file mode 100644 index ad6d17491e..0000000000 --- a/packages/react-start-rsc/src/slotUsageSanitizer.ts +++ /dev/null @@ -1,62 +0,0 @@ -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<object>, - 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<string, unknown> = {} - for (const [k, v] of Object.entries(value as Record<string, unknown>)) { - out[k] = sanitizeSlotArg(v, seen, depth + 1) - } - return out - } - - return value -} - -export function sanitizeSlotArgs(args: Array<any>): Array<any> { - const seen = new WeakSet<object>() - 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 deleted file mode 100644 index 061a53edba..0000000000 --- a/packages/react-start-rsc/src/types.ts +++ /dev/null @@ -1,15 +0,0 @@ -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<string, unknown> diff --git a/packages/react-start-rsc/tests/ClientSlot.test.tsx b/packages/react-start-rsc/tests/ClientSlot.test.tsx deleted file mode 100644 index fa6fef2e9c..0000000000 --- a/packages/react-start-rsc/tests/ClientSlot.test.tsx +++ /dev/null @@ -1,213 +0,0 @@ -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(<ClientSlot slot="test" args={[]} />) - }).toThrow('ClientSlot must be rendered within SlotProvider') - - spy.mockRestore() - }) - }) - - describe('missing implementations', () => { - it('should return null for missing slot in non-strict mode', () => { - render( - <SlotProvider implementations={{}} strict={false}> - <div data-testid="container"> - <ClientSlot slot="missing" args={[]} /> - </div> - </SlotProvider>, - ) - - // 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( - <SlotProvider implementations={{}} strict={true}> - <ClientSlot slot="missing" args={[]} /> - </SlotProvider>, - ) - }).toThrow('Missing slot implementation for "missing"') - - spy.mockRestore() - }) - }) - - describe('non-function implementations', () => { - it('should render string directly', () => { - render( - <SlotProvider implementations={{ greeting: 'Hello World' }}> - <div data-testid="slot"> - <ClientSlot slot="greeting" args={[]} /> - </div> - </SlotProvider>, - ) - - expect(screen.getByTestId('slot').textContent).toBe('Hello World') - }) - - it('should render number directly', () => { - render( - <SlotProvider implementations={{ count: 42 }}> - <div data-testid="slot"> - <ClientSlot slot="count" args={[]} /> - </div> - </SlotProvider>, - ) - - expect(screen.getByTestId('slot').textContent).toBe('42') - }) - - it('should render React element directly', () => { - render( - <SlotProvider implementations={{ element: <span>Element</span> }}> - <div data-testid="slot"> - <ClientSlot slot="element" args={[]} /> - </div> - </SlotProvider>, - ) - - expect(screen.getByTestId('slot').textContent).toBe('Element') - }) - - it('should render children slot', () => { - render( - <SlotProvider implementations={{ children: <div>Child content</div> }}> - <div data-testid="slot"> - <ClientSlot slot="children" args={[]} /> - </div> - </SlotProvider>, - ) - - expect(screen.getByTestId('slot').textContent).toBe('Child content') - }) - }) - - describe('function implementations', () => { - it('should call function with no args', () => { - render( - <SlotProvider implementations={{ render: () => 'No args result' }}> - <div data-testid="slot"> - <ClientSlot slot="render" args={[]} /> - </div> - </SlotProvider>, - ) - - expect(screen.getByTestId('slot').textContent).toBe('No args result') - }) - - it('should call function with single arg', () => { - render( - <SlotProvider - implementations={{ render: (name: string) => `Hello ${name}` }} - > - <div data-testid="slot"> - <ClientSlot slot="render" args={['World']} /> - </div> - </SlotProvider>, - ) - - expect(screen.getByTestId('slot').textContent).toBe('Hello World') - }) - - it('should call function with multiple args', () => { - render( - <SlotProvider - implementations={{ - render: (a: number, b: number, c: number) => `Sum: ${a + b + c}`, - }} - > - <div data-testid="slot"> - <ClientSlot slot="render" args={[1, 2, 3]} /> - </div> - </SlotProvider>, - ) - - expect(screen.getByTestId('slot').textContent).toBe('Sum: 6') - }) - - it('should call function returning React element', () => { - render( - <SlotProvider - implementations={{ - render: (item: { id: number; name: string }) => ( - <span key={item.id}>{item.name}</span> - ), - }} - > - <div data-testid="slot"> - <ClientSlot slot="render" args={[{ id: 1, name: 'Item One' }]} /> - </div> - </SlotProvider>, - ) - - expect(screen.getByTestId('slot').textContent).toBe('Item One') - }) - - it('should handle function returning null', () => { - render( - <SlotProvider implementations={{ render: () => null }}> - <div data-testid="slot"> - <ClientSlot slot="render" args={[]} /> - </div> - </SlotProvider>, - ) - - expect(screen.getByTestId('slot').children).toHaveLength(0) - }) - }) - - describe('edge cases', () => { - it('should handle undefined args gracefully', () => { - render( - <SlotProvider - implementations={{ - render: (...args: Array<unknown>) => `Args: ${args.length}`, - }} - > - <div data-testid="slot"> - <ClientSlot slot="render" args={[undefined, undefined]} /> - </div> - </SlotProvider>, - ) - - expect(screen.getByTestId('slot').textContent).toBe('Args: 2') - }) - - it('should handle complex object args', () => { - interface ComplexArg { - nested: { deep: { value: string } } - } - - render( - <SlotProvider - implementations={{ - render: (obj: ComplexArg) => obj.nested.deep.value, - }} - > - <div data-testid="slot"> - <ClientSlot - slot="render" - args={[{ nested: { deep: { value: 'Deep value' } } }]} - /> - </div> - </SlotProvider>, - ) - - 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 deleted file mode 100644 index b6493e75a8..0000000000 --- a/packages/react-start-rsc/tests/CompositeComponent.types.test-d.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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<Post> - - expectTypeOf(CompositeComponent).toBeFunction() - - type Props = ComponentProps<typeof CompositeComponent<typeof src>> - - // Type-level: ensure inferred props include slots - type Expected = { - src: typeof src - children?: React.ReactNode - header: (title: string) => React.ReactNode - footer: () => React.ReactNode - } - - expectTypeOf<Props>().branded.toEqualTypeOf<Expected>() -}) diff --git a/packages/react-start-rsc/tests/ReplayableStream.test.ts b/packages/react-start-rsc/tests/ReplayableStream.test.ts deleted file mode 100644 index 4c4e40566e..0000000000 --- a/packages/react-start-rsc/tests/ReplayableStream.test.ts +++ /dev/null @@ -1,536 +0,0 @@ -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<Uint8Array>({ - 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<Uint8Array> = [] - 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<Uint8Array>({ - 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<Uint8Array> = [] - const chunks2: Array<Uint8Array> = [] - - // 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<Uint8Array>({ - 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<Uint8Array> = [] - 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<Uint8Array>({ - 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<Uint8Array>({ - 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<Uint8Array>({ - 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<Uint8Array>({ - 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<Uint8Array>({ - 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<Uint8Array>({ - 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<Uint8Array>({ - 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<Uint8Array> = [] - 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<Uint8Array>({ - 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<Uint8Array>({ - 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<Uint8Array> = [] - 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<Uint8Array>({ - 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<Uint8Array>({ - 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<Uint8Array>({ - 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<Uint8Array>({ - 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<void>((resolve) => { - resolveCancel = resolve - }) - - const source = new ReadableStream<Uint8Array>({ - 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<Uint8Array>({ - 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<Uint8Array>({ - 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 deleted file mode 100644 index 8c39d1dfe8..0000000000 --- a/packages/react-start-rsc/tests/ServerComponent.test.tsx +++ /dev/null @@ -1,118 +0,0 @@ -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<Uint8Array>({ - start(controller) { - controller.enqueue(new Uint8Array([1, 2, 3])) - controller.close() - }, - }) - - let createdReadableStream: ReadableStream<Uint8Array> | undefined - let resolvePromise: (value: React.ReactNode) => void - - const decodePromise = new Promise<React.ReactNode>((resolve) => { - resolvePromise = resolve - }) - - const decodeMock = browserDecode as unknown as ReturnType<typeof vi.fn> - decodeMock.mockImplementation((rs: ReadableStream<Uint8Array>) => { - createdReadableStream = rs - return decodePromise - }) - - const Component = createServerComponentFromStream(stream) - - const { CompositeComponent } = await import('../src/CompositeComponent') - - await act(async () => { - render( - <React.Suspense fallback={<div>loading</div>}> - <CompositeComponent src={Component as any} /> - <CompositeComponent src={Component as any} /> - </React.Suspense>, - ) - - // 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<Uint8Array>({ - start(controller) { - controller.close() - }, - }) - - const decodeMock = browserDecode as unknown as ReturnType<typeof vi.fn> - 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 deleted file mode 100644 index 9590e44f8c..0000000000 --- a/packages/react-start-rsc/tests/SlotContext.test.tsx +++ /dev/null @@ -1,114 +0,0 @@ -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 <div data-testid="result">{JSON.stringify(ctx)}</div> - } - - render( - <SlotProvider implementations={{ foo: 'bar' }}> - <Consumer /> - </SlotProvider>, - ) - - 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 <div data-testid="strict">{String(ctx?.strict)}</div> - } - - render( - <SlotProvider implementations={{}} strict={true}> - <Consumer /> - </SlotProvider>, - ) - - expect(screen.getByTestId('strict').textContent).toBe('true') - }) - - it('should default strict to false', () => { - function Consumer() { - const ctx = useSlotContext() - return <div data-testid="strict">{String(ctx?.strict)}</div> - } - - render( - <SlotProvider implementations={{}}> - <Consumer /> - </SlotProvider>, - ) - - expect(screen.getByTestId('strict').textContent).toBe('false') - }) - - it('should render children', () => { - render( - <SlotProvider implementations={{}}> - <div data-testid="child">Child content</div> - </SlotProvider>, - ) - - expect(screen.getByTestId('child').textContent).toBe('Child content') - }) - }) - - describe('useSlotContext', () => { - it('should return null outside of SlotProvider', () => { - function Consumer() { - const ctx = useSlotContext() - return ( - <div data-testid="ctx">{ctx === null ? 'null' : 'has value'}</div> - ) - } - - render(<Consumer />) - - 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 <div data-testid="deep">{nested?.deep}</div> - } - - render( - <SlotProvider implementations={{ nested: { deep: 'value' } }}> - <Consumer /> - </SlotProvider>, - ) - - 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 <div data-testid="fn-result">{fn?.(42)}</div> - } - - render( - <SlotProvider - implementations={{ renderItem: (n: number) => `Item ${n}` }} - > - <Consumer /> - </SlotProvider>, - ) - - 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 deleted file mode 100644 index 3a17c54135..0000000000 --- a/packages/react-start-rsc/tests/createRscProxy.test.tsx +++ /dev/null @@ -1,252 +0,0 @@ -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<string | symbol> = [] - 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 <Component /> - } - - render(<Wrapper />) - - 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 <Component /> - } - - // This should render without errors even with minimal props - render(<Wrapper />) - - 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 deleted file mode 100644 index 320ef4f30a..0000000000 --- a/packages/react-start-rsc/tests/createServerComponent.test-d.tsx +++ /dev/null @@ -1,98 +0,0 @@ -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<Post> - - const node = null as unknown as JSX.Element - expectTypeOf(node).toEqualTypeOf<JSX.Element>() -}) - -test('when a server component is created with props but no slots', () => { - type Post = (props: { num: number }) => React.ReactNode - type PostComponent = CompositeComponentResult<Post> - - const node = null as unknown as JSX.Element - expectTypeOf(node).toEqualTypeOf<JSX.Element>() - expectTypeOf(null as unknown as typeof CompositeComponent<PostComponent>) - .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<Post> - - const node = null as unknown as JSX.Element - expectTypeOf(node).toEqualTypeOf<JSX.Element>() - expectTypeOf(null as unknown as typeof CompositeComponent<PostComponent>) - .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<Post> - - const node = null as unknown as JSX.Element - expectTypeOf(node).toEqualTypeOf<JSX.Element>() - - expectTypeOf(null as unknown as typeof CompositeComponent<PostComponent>) - .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<Post> - - const node = null as unknown as JSX.Element - expectTypeOf(node).toEqualTypeOf<JSX.Element>() - - expectTypeOf(null as unknown as typeof CompositeComponent<PostComponent>) - .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<ValidateCompositeComponent<Post>>().toEqualTypeOf< - (props: { - render: (props: { - func: 'Function is not serializable' - }) => React.ReactNode - }) => React.ReactNode - >() -}) - -test('when server component type has incorrect return type', () => { - expectTypeOf<ValidateCompositeComponent<() => 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 deleted file mode 100644 index 5d9f6f59b4..0000000000 --- a/packages/react-start-rsc/tests/renderServerComponent.types.test-d.tsx +++ /dev/null @@ -1,30 +0,0 @@ -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<typeof dataPromise> - - // nested selection - expectTypeOf<Data>().toHaveProperty('foo') - expectTypeOf<Data['foo']>().toHaveProperty('bar') - - // also: directly renderable at top-level - type MustBeRenderable = true - expectTypeOf<MustBeRenderable>().toEqualTypeOf<true>() -}) diff --git a/packages/react-start-rsc/tests/rscCssTransform.test.tsx b/packages/react-start-rsc/tests/rscCssTransform.test.tsx deleted file mode 100644 index afc4686e94..0000000000 --- a/packages/react-start-rsc/tests/rscCssTransform.test.tsx +++ /dev/null @@ -1,215 +0,0 @@ -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(<Card kind="renderable" />) - export const composite = createCompositeComponent(() => ({ - Card: <Card kind="composite" />, - })) - export const stream = renderToReadableStream(<Card kind="stream" />) - `, - }) - - expect(code).toMatchInlineSnapshot(` - "import { createCompositeComponent, renderServerComponent, renderToReadableStream } from '@tanstack/react-start/rsc'; - export const renderable = renderServerComponent(<Card kind="renderable" />, { - __tanstackStartRscCss: import.meta.viteRsc.loadCss() - }); - export const composite = createCompositeComponent(() => ({ - Card: <Card kind="composite" /> - }), { - __tanstackStartRscCss: import.meta.viteRsc.loadCss() - }); - export const stream = renderToReadableStream(<>{import.meta.viteRsc.loadCss()}<Card kind="stream" /></>);" - `) - }) - - 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 = <Card /> - export const existingOptions = renderServerComponent(<Card />, { - alreadyConfigured: true, - }) - export const nonJsxStream = renderToReadableStream(node) - `, - }) - - expect(code).toMatchInlineSnapshot(` - "import { renderServerComponent, renderToReadableStream } from '@tanstack/react-start/rsc'; - const node = <Card />; - export const existingOptions = renderServerComponent(<Card />, { - 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(<Card />) - ` - - 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(<Card />);", - "providerCode": "import { renderServerComponent } from '@tanstack/react-start/rsc'; - export const renderable = renderServerComponent(<Card />, { - __tanstackStartRscCss: import.meta.rspackRsc.loadCss() - });", - } - `) - }) - - test('detects transform imports without enabling them outside server builds', () => { - const compilerTransforms: Array<StartCompilerImportTransform> = - createRscCssCompilerTransforms({ - loadCssExpression: 'import.meta.viteRsc.loadCss()', - }) - - const code = ` - import { renderServerComponent } from '@tanstack/react-start/rsc' - export const renderable = renderServerComponent(<Card />) - ` - - 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(<Card />) - `, - }) - - expect(code).toContain( - '__tanstackStartRscCss: import.meta.viteRsc.loadCss()', - ) - }) - - test.each([ - { wrapped: '(<Card />)', bare: '<Card />' }, - { wrapped: '<Card /> as any', bare: '<Card />' }, - { wrapped: '<Card />!', bare: '<Card />' }, - { wrapped: '(<><Card /></>) satisfies unknown', bare: '<><Card /></>' }, - ])( - '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 ? <A /> : <B />) - 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 deleted file mode 100644 index 82055721d7..0000000000 --- a/packages/react-start-rsc/tests/setup.ts +++ /dev/null @@ -1,7 +0,0 @@ -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 deleted file mode 100644 index 8e611ace3b..0000000000 --- a/packages/react-start-rsc/tsconfig.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "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 deleted file mode 100644 index c8dfcf917b..0000000000 --- a/packages/react-start-rsc/vite.config.ts +++ /dev/null @@ -1,58 +0,0 @@ -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 index 86d7854a59..195e37f7b7 100644 --- a/packages/react-start-server/CHANGELOG.md +++ b/packages/react-start-server/CHANGELOG.md @@ -1,811 +1,5 @@ # @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 diff --git a/packages/react-start-server/package.json b/packages/react-start-server/package.json index a725b70d9c..0cabf96298 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.167.52", + "version": "1.166.16", "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": "node ../../node_modules/typescript59/lib/tsc.js", - "test:types:ts60": "tsc6", - "test:types:ts70": "tsc", + "test:types:ts59": "tsc", "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", "build": "vite build" }, @@ -58,27 +58,18 @@ "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": "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:" + "@vitejs/plugin-react": "^4.3.4", + "react": "^19.0.0", + "react-dom": "^19.0.0", + "typescript": "^5.7.2", + "vite": "*" }, "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 deleted file mode 100644 index 92be18587f..0000000000 --- a/packages/react-start-server/tsconfig.build.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "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 214b8cbc42..47efd2c2c0 100644 --- a/packages/react-start-server/vite.config.ts +++ b/packages/react-start-server/vite.config.ts @@ -15,7 +15,6 @@ 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 index 9d6432f985..d635cd63eb 100644 --- a/packages/react-start/CHANGELOG.md +++ b/packages/react-start/CHANGELOG.md @@ -1,1491 +1,5 @@ # @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/<package>#<skill>`) 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 diff --git a/packages/react-start/README.md b/packages/react-start/README.md index e614561c15..4ead3764b3 100644 --- a/packages/react-start/README.md +++ b/packages/react-start/README.md @@ -2,21 +2,7 @@ # TanStack React Start -<picture> - <source - media="(prefers-color-scheme: dark)" - srcset="https://tanstack.com/api/readme/start.png?framework=react&theme=dark" - /> - <source - media="(prefers-color-scheme: light)" - srcset="https://tanstack.com/api/readme/start.png?framework=react" - /> - <img - src="https://tanstack.com/api/readme/start.png?framework=react" - alt="TanStack React Start" - width="900" - /> -</picture> +![TanStack React Start Header](https://raw.githubusercontent.com/TanStack/router/main/media/header_start.png) 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. diff --git a/packages/react-start/bin/intent.js b/packages/react-start/bin/intent.js new file mode 100755 index 0000000000..5b08532885 --- /dev/null +++ b/packages/react-start/bin/intent.js @@ -0,0 +1,25 @@ +#!/usr/bin/env node +// Auto-generated by @tanstack/intent setup +// Exposes the intent end-user CLI for consumers of this library. +// Commit this file, then add to your package.json: +// "bin": { "intent": "./bin/intent.js" } +try { + await import('@tanstack/intent/intent-library') +} catch (e) { + const isModuleNotFound = + e?.code === 'ERR_MODULE_NOT_FOUND' || e?.code === 'MODULE_NOT_FOUND' + const missingIntentLibrary = + typeof e?.message === 'string' && e.message.includes('@tanstack/intent') + + if (isModuleNotFound && missingIntentLibrary) { + console.error('@tanstack/intent is not installed.') + console.error('') + console.error('Install it as a dev dependency:') + console.error(' npm add -D @tanstack/intent') + console.error('') + console.error('Or run directly:') + console.error(' npx @tanstack/intent@latest list') + process.exit(1) + } + throw e +} diff --git a/packages/react-start/package.json b/packages/react-start/package.json index 6d51a4c6d0..fbd5604971 100644 --- a/packages/react-start/package.json +++ b/packages/react-start/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/react-start", - "version": "1.169.6", + "version": "1.167.2", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", @@ -26,17 +26,13 @@ "scripts": { "clean": "rimraf ./dist && rimraf ./coverage", "test": "pnpm test:build", - "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", + "test:build": "exit 0; vitest", "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" @@ -48,12 +44,6 @@ "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", @@ -61,10 +51,6 @@ } }, "./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" @@ -88,52 +74,12 @@ "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", @@ -160,47 +106,24 @@ "node": ">=22.12.0" }, "dependencies": { - "@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/router-utils": "workspace:^", "@tanstack/start-plugin-core": "workspace:*", + "@tanstack/react-router": "workspace:*", + "@tanstack/start-client-core": "workspace:*", "@tanstack/start-server-core": "workspace:*", - "pathe": "catalog:" + "pathe": "^2.0.3" }, "peerDependencies": { - "@rsbuild/core": "^2.0.5", "react": ">=18.0.0 || >=19.0.0", "react-dom": ">=18.0.0 || >=19.0.0", - "vite": ">=8.0.0" - }, - "peerDependenciesMeta": { - "@rsbuild/core": { - "optional": true - }, - "@vitejs/plugin-rsc": { - "optional": true - }, - "vite": { - "optional": true - } + "vite": ">=7.0.0" }, "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:" + "@tanstack/intent": "^0.0.14" + }, + "bin": { + "intent": "./bin/intent.js" } } diff --git a/packages/react-start/skills/_artifacts/domain_map.yaml b/packages/react-start/skills/_artifacts/domain_map.yaml index 4e790903a6..b5e84d4dfb 100644 --- a/packages/react-start/skills/_artifacts/domain_map.yaml +++ b/packages/react-start/skills/_artifacts/domain_map.yaml @@ -1,13 +1,13 @@ # domain_map.yaml # Generated by skill-domain-discovery # Library: TanStack Start -# Version: 1.168.32 +# Version: 1.166.2 # Date: 2026-03-07 # Status: reviewed library: name: '@tanstack/react-start' - version: '1.168.32' + version: '1.166.2' repository: 'https://github.com/TanStack/router' description: >- Full-stack React framework built on TanStack Router and Vite. Adds @@ -134,7 +134,7 @@ skills: - '@tanstack/start-server-core' covers: - createServerFn (GET/POST) - - validator (Zod or function) + - inputValidator (Zod or function) - useServerFn hook - Server context utilities (getRequest, getRequestHeader, setResponseHeader, setResponseStatus) - Error handling (throw errors, redirect, notFound) @@ -189,15 +189,6 @@ skills: 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, @@ -213,39 +204,6 @@ skills: 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' @@ -271,7 +229,7 @@ skills: - Middleware factories - Fetch override precedence - Header merging - - Method order enforcement (middleware → validator → client → server) + - Method order enforcement (middleware → inputValidator → client → server) tasks: - 'Add authentication middleware' - 'Pass context through middleware chain' @@ -289,7 +247,7 @@ skills: - mistake: 'Wrong middleware method order' mechanism: >- - TypeScript enforces method order: middleware → validator + TypeScript enforces method order: middleware → inputValidator → client → server. Wrong order causes type errors and runtime failures. source: 'docs/start/framework/react/guide/middleware.md' @@ -396,23 +354,6 @@ skills: 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' @@ -446,39 +387,6 @@ skills: 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' @@ -536,65 +444,6 @@ skills: 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'] diff --git a/packages/react-start/skills/_artifacts/skill_spec.md b/packages/react-start/skills/_artifacts/skill_spec.md index f550196da8..11b6843bb0 100644 --- a/packages/react-start/skills/_artifacts/skill_spec.md +++ b/packages/react-start/skills/_artifacts/skill_spec.md @@ -4,26 +4,25 @@ TanStack Start is a full-stack React framework built on TanStack Router and Vite ## 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 | +| 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 | ## 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 | +| server-functions | core | server-functions | createServerFn, validation, useServerFn, streaming | 4 | | 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 | +| execution-model | core | execution-model | Isomorphic defaults, environment functions, env vars | 4 | +| server-routes | core | server-routes | server property, HTTP handlers, createHandlers | 2 | | 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 | @@ -37,18 +36,14 @@ TanStack Start is a full-stack React framework built on TanStack Router and Vite | 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) +### server-functions (4 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 | +| # | Mistake | Priority | Source | +| --- | --------------------------------------------------------------------------- | -------- | --------------------------- | +| 1 | Putting server-only code in loaders instead of server functions | CRITICAL | maintainer interview | +| 2 | Generating Next.js/Remix server patterns ("use server", getServerSideProps) | CRITICAL | maintainer interview | +| 3 | Using dynamic imports for server functions | HIGH | docs/guide/server-functions | +| 4 | Not using useServerFn for component calls | MEDIUM | docs/guide/server-functions | ### middleware (3 failure modes) @@ -58,7 +53,7 @@ TanStack Start is a full-stack React framework built on TanStack Router and Vite | 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) +### execution-model (4 failure modes) | # | Mistake | Priority | Source | | --- | ------------------------------------------------- | -------- | -------------------------------- | @@ -66,17 +61,13 @@ TanStack Start is a full-stack React framework built on TanStack Router and Vite | 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) +### server-routes (2 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 | +| # | Mistake | Priority | Source | +| --- | ---------------------------------------- | -------- | ------------------------ | +| 1 | Duplicate route path resolution | MEDIUM | docs/guide/server-routes | +| 2 | Forgetting to await request body methods | MEDIUM | docs/guide/server-routes | ### deployment (3 failure modes) @@ -86,14 +77,6 @@ TanStack Start is a full-stack React framework built on TanStack Router and Vite | 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 | diff --git a/packages/react-start/skills/_artifacts/skill_tree.yaml b/packages/react-start/skills/_artifacts/skill_tree.yaml index 3078228f73..cf743b067c 100644 --- a/packages/react-start/skills/_artifacts/skill_tree.yaml +++ b/packages/react-start/skills/_artifacts/skill_tree.yaml @@ -1,7 +1,7 @@ # skills/_artifacts/start_skill_tree.yaml library: name: '@tanstack/react-start' - version: '1.168.32' + version: '1.166.2' repository: 'https://github.com/TanStack/router' description: >- Full-stack React framework built on TanStack Router and Vite. @@ -37,7 +37,7 @@ skills: path: 'skills/start-core/server-functions/SKILL.md' package: 'packages/start-client-core' description: >- - createServerFn (GET/POST), validator (Zod or function), + createServerFn (GET/POST), inputValidator (Zod or function), useServerFn hook, server context utilities (getRequest, getRequestHeader, setResponseHeader, setResponseStatus), error handling (throw errors, redirect, notFound), streaming @@ -137,25 +137,6 @@ skills: - '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' diff --git a/packages/react-start/skills/lifecycle/migrate-from-nextjs/SKILL.md b/packages/react-start/skills/lifecycle/migrate-from-nextjs/SKILL.md index 81b020713b..00f86ad376 100644 --- a/packages/react-start/skills/lifecycle/migrate-from-nextjs/SKILL.md +++ b/packages/react-start/skills/lifecycle/migrate-from-nextjs/SKILL.md @@ -1,14 +1,13 @@ --- -name: migrate-from-nextjs +name: lifecycle/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' +type: lifecycle +library: tanstack-start +library_version: '1.166.2' requires: - start-core - react-start @@ -221,7 +220,7 @@ TanStack Start: import { createServerFn } from '@tanstack/react-start' export const createPost = createServerFn({ method: 'POST' }) - .validator((data) => { + .inputValidator((data) => { if (!(data instanceof FormData)) throw new Error('Expected FormData') return { title: data.get('title')?.toString() || '' } }) @@ -432,5 +431,5 @@ export const myAction = createServerFn({ method: 'POST' }) ## 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 +- [start-core/server-functions](../../../../start-client-core/skills/start-core/server-functions/SKILL.md) — server function patterns +- [start-core/execution-model](../../../../start-client-core/skills/start-core/execution-model/SKILL.md) — isomorphic execution diff --git a/packages/react-start/skills/react-start/SKILL.md b/packages/react-start/skills/react-start/SKILL.md index 988373f107..e3067e9e05 100644 --- a/packages/react-start/skills/react-start/SKILL.md +++ b/packages/react-start/skills/react-start/SKILL.md @@ -5,11 +5,10 @@ description: >- 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 +type: framework +library: tanstack-start +library_version: '1.166.2' +framework: react requires: - start-core sources: @@ -19,9 +18,9 @@ sources: # 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. +This skill builds on start-core. Read [start-core](../../../start-client-core/skills/start-core/SKILL.md) first for foundational concepts. -For React Server Components patterns, see [react-start/server-components](./server-components/SKILL.md). +This skill covers the React-specific bindings, setup, and patterns for TanStack Start. > **CRITICAL**: All code is ISOMORPHIC by default. Loaders run on BOTH server and client. Use `createServerFn` for server-only logic. @@ -29,16 +28,6 @@ For React Server Components patterns, see [react-start/server-components](./serv > **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: @@ -190,7 +179,7 @@ Use `useServerFn` to call server functions from React components with proper int import { createServerFn, useServerFn } from '@tanstack/react-start' const updatePost = createServerFn({ method: 'POST' }) - .validator((data: { id: string; title: string }) => data) + .inputValidator((data: { id: string; title: string }) => data) .handler(async ({ data }) => { await db.posts.update(data.id, { title: data.title }) return { success: true } @@ -291,6 +280,6 @@ Without `<Scripts />` in the root route's `<body>`, client JavaScript doesn't lo ## 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 +- [start-core](../../../start-client-core/skills/start-core/SKILL.md) — core Start concepts +- [router-core](../../../router-core/skills/router-core/SKILL.md) — routing fundamentals +- [react-router](../../../react-router/skills/react-router/SKILL.md) — 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 deleted file mode 100644 index 81561824a0..0000000000 --- a/packages/react-start/skills/react-start/server-components/SKILL.md +++ /dev/null @@ -1,128 +0,0 @@ ---- -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` + `<CompositeComponent src={...} />` -- 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 deleted file mode 100644 index f416b832ad..0000000000 --- a/packages/react-start/skills/react-start/server-components/docs/architecture.md +++ /dev/null @@ -1,84 +0,0 @@ -# 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 deleted file mode 100644 index f48ba02d5b..0000000000 --- a/packages/react-start/skills/react-start/server-components/docs/caching-refresh-ssr.md +++ /dev/null @@ -1,140 +0,0 @@ -# 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 deleted file mode 100644 index 738e07c632..0000000000 --- a/packages/react-start/skills/react-start/server-components/docs/composite-components.md +++ /dev/null @@ -1,115 +0,0 @@ -# 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: - -- `<CompositeComponent src={...} ... />` 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 }) => ( - <div> - {React.Children.map(props.children, (child) => - React.cloneElement(child, { extra: 'prop' }), - )} - </div> -)) -``` - -Correct rewrite: - -```tsx -createCompositeComponent<{ - renderItem?: (data: { extra: string }) => React.ReactNode -}>((props) => <div>{props.renderItem?.({ extra: 'prop' })}</div>) -``` - -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 deleted file mode 100644 index ded96096da..0000000000 --- a/packages/react-start/skills/react-start/server-components/docs/current-api-notes.md +++ /dev/null @@ -1,74 +0,0 @@ -# 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 deleted file mode 100644 index f6435747c1..0000000000 --- a/packages/react-start/skills/react-start/server-components/docs/debugging-review.md +++ /dev/null @@ -1,141 +0,0 @@ -# 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 deleted file mode 100644 index 3755c01f78..0000000000 --- a/packages/react-start/skills/react-start/server-components/docs/sources.md +++ /dev/null @@ -1,39 +0,0 @@ -# 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 deleted file mode 100644 index eb4a308abb..0000000000 --- a/packages/react-start/skills/react-start/server-components/examples/01-renderable-route-loader.tsx +++ /dev/null @@ -1,28 +0,0 @@ -// 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 <h1>Hello from TanStack Start RSC</h1> -} - -const getGreeting = createServerFn({ method: 'GET' }).handler(async () => { - const Renderable = await renderServerComponent(<Greeting />) - 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 deleted file mode 100644 index 0656abd40b..0000000000 --- a/packages/react-start/skills/react-start/server-components/examples/02-composite-slots.tsx +++ /dev/null @@ -1,124 +0,0 @@ -// 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) => ( - <article className="card"> - <h1>{post.title}</h1> - <p>{post.body}</p> - - <footer> - {props.renderActions?.({ - postId: post.id, - authorId: post.authorId, - })} - </footer> - - <section>{props.children}</section> - </article> - )) - - 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 ( - <CompositeComponent - src={src} - renderActions={({ postId, authorId }) => ( - <PostActions postId={postId} authorId={authorId} /> - )} - > - <Comments /> - </CompositeComponent> - ) -} - -function Comments() { - return <div>Interactive comments go here</div> -} - -function PostActions(props: { postId: string; authorId: string }) { - return ( - <button type="button"> - Moderate {props.postId} / {props.authorId} - </button> - ) -} - -// 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) => ( - <section className="product-card"> - <h2>{product.name}</h2> - {props.AddToCart ? ( - <props.AddToCart productId={product.id} price={product.price} /> - ) : null} - </section> - )) - - return { src } - }) - -function AddToCartButton(props: { productId: string; price: number }) { - return ( - <button type="button"> - Add {props.productId} at {props.price} - </button> - ) -} - -// Example usage somewhere else: -// const { src } = await getProductCard({ data: { productId: 'p-1' } }) -// <CompositeComponent src={src} AddToCart={AddToCartButton} /> 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 deleted file mode 100644 index d891e2230d..0000000000 --- a/packages/react-start/skills/react-start/server-components/examples/03-query-owned-rsc.tsx +++ /dev/null @@ -1,100 +0,0 @@ -// 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<void> - } -} - -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) => ( - <article> - <h1>{post.title}</h1> - <p>{post.body}</p> - <footer>{props.renderActions?.({ postId: post.id })}</footer> - </article> - )) - - 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 ( - <CompositeComponent - src={data.src} - renderActions={({ postId }) => ( - <button type="button" onClick={handleRename}> - Refresh {postId} - </button> - )} - /> - ) -} 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 deleted file mode 100644 index a068c3c001..0000000000 --- a/packages/react-start/skills/react-start/server-components/examples/04-selective-ssr-data-only.tsx +++ /dev/null @@ -1,72 +0,0 @@ -// 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) => ( - <section> - <h1>Users: {stats.totalUsers}</h1> - {props.renderChart?.({ series: stats.series })} - </section> - )) - - 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 ( - <CompositeComponent - src={Dashboard.src} - renderChart={({ series }) => ( - <ResponsiveChart data={series} width={width} /> - )} - /> - ) -} - -// Replace with your real chart component -function ResponsiveChart(props: { - data: Array<{ x: number; y: number }> - width: number -}) { - return ( - <pre> - {JSON.stringify({ width: props.width, points: props.data.length })} - </pre> - ) -} 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 deleted file mode 100644 index cfa50490b4..0000000000 --- a/packages/react-start/skills/react-start/server-components/examples/05-ssr-false-browser-loader.tsx +++ /dev/null @@ -1,40 +0,0 @@ -// 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( - <ToolPalette savedState={data.savedState} />, - ) - - 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 ( - <section> - <h1>Canvas tools</h1> - <pre>{props.savedState ?? 'no saved state'}</pre> - </section> - ) -} 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 deleted file mode 100644 index 17415d00a8..0000000000 --- a/packages/react-start/skills/react-start/server-components/examples/06-low-level-flight-api-route.tsx +++ /dev/null @@ -1,40 +0,0 @@ -// 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(<div>Server rendered content</div>) -}) - -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/default-entry/server.ts b/packages/react-start/src/default-entry/server.ts index 638ac3c0a6..8e734a7e49 100644 --- a/packages/react-start/src/default-entry/server.ts +++ b/packages/react-start/src/default-entry/server.ts @@ -1,7 +1,6 @@ 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' @@ -11,8 +10,12 @@ 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<Register> } -// Bind the shared request context and fallback error handling to React's Register. -export const createServerEntry: (entry: ServerEntry) => ServerEntry = - createCoreServerEntry<Register> +export function createServerEntry(entry: ServerEntry): ServerEntry { + return { + async fetch(...args) { + return await entry.fetch(...args) + }, + } +} export default createServerEntry({ fetch }) diff --git a/packages/react-start/src/hydration.ts b/packages/react-start/src/hydration.ts deleted file mode 100644 index e86169e71d..0000000000 --- a/packages/react-start/src/hydration.ts +++ /dev/null @@ -1,18 +0,0 @@ -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 6ea839a967..8b51b6c783 100644 --- a/packages/react-start/src/index.ts +++ b/packages/react-start/src/index.ts @@ -1,34 +1,2 @@ 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 deleted file mode 100644 index 7e0fcbb6c2..0000000000 --- a/packages/react-start/src/plugin/rsbuild.ts +++ /dev/null @@ -1,79 +0,0 @@ -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 deleted file mode 100644 index aba8a7ba65..0000000000 --- a/packages/react-start/src/plugin/shared.ts +++ /dev/null @@ -1,22 +0,0 @@ -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 8849f39ea6..3d47aad887 100644 --- a/packages/react-start/src/plugin/vite.ts +++ b/packages/react-start/src/plugin/vite.ts @@ -1,72 +1,36 @@ +import { fileURLToPath } from 'node:url' import { - 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' + TanStackStartVitePluginCore, + VITE_ENVIRONMENT_NAMES, +} from '@tanstack/start-plugin-core' import path from 'pathe' -import { reactStartDefaultEntryPaths, reactStartPluginDir } from './shared' +import type { TanStackStartInputConfig } from '@tanstack/start-plugin-core' 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(reactStartPluginDir, '../../../../')) === - 'packages' + path.basename(path.resolve(currentDir, '../../../../')) === 'packages' export function tanstackStart( - options?: TanStackStartViteInputConfig & { rsc?: { enabled?: boolean } }, + options?: TanStackStartInputConfig, ): Array<PluginOption> { - 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<string> = [ - 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: [ @@ -75,49 +39,52 @@ 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 || - reactRouterInNoExternal + options.resolve?.noExternal === true || !isInsideRouterMonoRepo ? undefined : ['@tanstack/react-router', '@tanstack/react-router-devtools'], }, - 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, + 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, } }, }, - rscConfig ? reactStartRscVitePlugin() : null, - tanStackStartVite(corePluginOpts, options), + TanStackStartVitePluginCore( + { + framework: 'react', + defaultEntryPaths, + }, + options, + ), ] } diff --git a/packages/react-start/src/rsbuild/browser-decode.ts b/packages/react-start/src/rsbuild/browser-decode.ts deleted file mode 100644 index 5232414e97..0000000000 --- a/packages/react-start/src/rsbuild/browser-decode.ts +++ /dev/null @@ -1 +0,0 @@ -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 deleted file mode 100644 index aa56c87e13..0000000000 --- a/packages/react-start/src/rsbuild/ssr-decode.ts +++ /dev/null @@ -1 +0,0 @@ -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 deleted file mode 100644 index b6624de42a..0000000000 --- a/packages/react-start/src/rsc.rsc.ts +++ /dev/null @@ -1,2 +0,0 @@ -// 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 deleted file mode 100644 index 481210a6ab..0000000000 --- a/packages/react-start/src/rsc.tsx +++ /dev/null @@ -1,3 +0,0 @@ -// 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 deleted file mode 100644 index 0b7890f4eb..0000000000 --- a/packages/react-start/src/rsc/serialization/client.ts +++ /dev/null @@ -1 +0,0 @@ -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 deleted file mode 100644 index 74edf24cb8..0000000000 --- a/packages/react-start/src/rsc/serialization/server.ts +++ /dev/null @@ -1 +0,0 @@ -export { rscSerializationAdapter } from '@tanstack/react-start-rsc/serialization.server' diff --git a/packages/react-start/src/server.rsc.ts b/packages/react-start/src/server.rsc.ts deleted file mode 100644 index d1fd428186..0000000000 --- a/packages/react-start/src/server.rsc.ts +++ /dev/null @@ -1 +0,0 @@ -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 66f3525937..37e2294be6 100644 --- a/packages/react-start/src/useServerFn.ts +++ b/packages/react-start/src/useServerFn.ts @@ -18,7 +18,7 @@ export function useServerFn<T extends (...deps: Array<any>) => Promise<any>>( return res } catch (err) { if (isRedirect(err)) { - err.options._fromLocation = router.stores.location.get() + err.options._fromLocation = router.stores.location.state return router.navigate(router.resolveRedirect(err).options) } diff --git a/packages/react-start/tsconfig.build.json b/packages/react-start/tsconfig.build.json deleted file mode 100644 index 92be18587f..0000000000 --- a/packages/react-start/tsconfig.build.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "rootDir": "./src" - }, - "include": ["src"] -} diff --git a/packages/react-start/tsconfig.json b/packages/react-start/tsconfig.json index c07753e18c..81f8715af3 100644 --- a/packages/react-start/tsconfig.json +++ b/packages/react-start/tsconfig.json @@ -2,8 +2,7 @@ "extends": "../../tsconfig.json", "compilerOptions": { "jsx": "react-jsx", - "module": "esnext", - "types": ["node"] + "module": "esnext" }, "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 deleted file mode 100644 index fca708fa0e..0000000000 --- a/packages/react-start/tsconfig.server-entry.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "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 8b64d36cc7..819215514d 100644 --- a/packages/react-start/vite.config.server-entry.ts +++ b/packages/react-start/vite.config.server-entry.ts @@ -1,7 +1,6 @@ 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 652e4ef842..6393ad96e9 100644 --- a/packages/react-start/vite.config.ts +++ b/packages/react-start/vite.config.ts @@ -21,25 +21,15 @@ 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', diff --git a/packages/router-cli/CHANGELOG.md b/packages/router-cli/CHANGELOG.md index 67101c3e51..f588583b74 100644 --- a/packages/router-cli/CHANGELOG.md +++ b/packages/router-cli/CHANGELOG.md @@ -1,542 +1,5 @@ # @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 diff --git a/packages/router-cli/package.json b/packages/router-cli/package.json index 51a729d79b..59c25c0096 100644 --- a/packages/router-cli/package.json +++ b/packages/router-cli/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/router-cli", - "version": "1.168.0", + "version": "1.166.16", "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": "node ../../node_modules/typescript59/lib/tsc.js", - "test:types:ts60": "tsc6", - "test:types:ts70": "tsc", + "test:types:ts59": "tsc", "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", "build": "vite build" }, @@ -63,20 +63,15 @@ "bin/**" ], "engines": { - "node": "^20.19.0 || >=22.12.0" + "node": ">=20.19" }, "dependencies": { "@tanstack/router-generator": "workspace:*", - "cac": "^7.1.0", - "chokidar": "catalog:" + "chokidar": "^3.6.0", + "yargs": "^17.7.2" }, "devDependencies": { - "@types/node": ">=20", - "vite": "catalog:", - "@tanstack/vite-config": "catalog:", - "vitest": "catalog:", - "@arethetypeswrong/cli": "catalog:", - "publint": "catalog:", - "rimraf": "catalog:" + "@types/yargs": "^17.0.33", + "vite": "*" } } diff --git a/packages/router-cli/src/index.ts b/packages/router-cli/src/index.ts index 7610fde457..eca5a9ff0e 100644 --- a/packages/router-cli/src/index.ts +++ b/packages/router-cli/src/index.ts @@ -1,51 +1,25 @@ -import { cac } from 'cac' +import yargs from 'yargs' +import { hideBin } from 'yargs/helpers' import { getConfig } from '@tanstack/router-generator' import { generate } from './generate' import { watch } from './watch' -declare const __TSR_VERSION__: string - main() export function main() { - const cli = cac('tsr') - - cli - .command('generate', 'Generate the routes for a project') - .action(async () => { + yargs(hideBin(process.argv)) + .scriptName('tsr') + .usage('$0 <cmd> [args]') + .command('generate', 'Generate the routes for a project', async () => { const config = getConfig() await generate(config, process.cwd()) }) - - cli .command( 'watch', 'Continuously watch and generate the routes for a project', + () => { + watch(process.cwd()) + }, ) - .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() - } + .help().argv } diff --git a/packages/router-cli/tsconfig.build.json b/packages/router-cli/tsconfig.build.json deleted file mode 100644 index 92be18587f..0000000000 --- a/packages/router-cli/tsconfig.build.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "rootDir": "./src" - }, - "include": ["src"] -} diff --git a/packages/router-cli/tsconfig.json b/packages/router-cli/tsconfig.json index 09d7037393..b36d1bf924 100644 --- a/packages/router-cli/tsconfig.json +++ b/packages/router-cli/tsconfig.json @@ -1,7 +1,4 @@ { "extends": "../../tsconfig.json", - "include": ["src", "vite.config.ts"], - "compilerOptions": { - "types": ["node"] - } + "include": ["src", "vite.config.ts"] } diff --git a/packages/router-cli/vite.config.ts b/packages/router-cli/vite.config.ts index 0eac9e6ed4..0ef0ed9c10 100644 --- a/packages/router-cli/vite.config.ts +++ b/packages/router-cli/vite.config.ts @@ -1,17 +1,11 @@ import { defineConfig, mergeConfig } from 'vitest/config' import { tanstackViteConfig } from '@tanstack/vite-config' -import packageJson from './package.json' -const config = defineConfig({ - define: { - __TSR_VERSION__: JSON.stringify(packageJson.version), - }, -}) +const config = defineConfig({}) 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 deleted file mode 100644 index 7402f0bdfe..0000000000 --- a/packages/router-core/AGENTS.md +++ /dev/null @@ -1,12 +0,0 @@ -# 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 index b01991e223..700a290054 100644 --- a/packages/router-core/CHANGELOG.md +++ b/packages/router-core/CHANGELOG.md @@ -1,614 +1,5 @@ # @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/<package>#<skill>`) 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 `<Scripts>` 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 `<Await>` without a `fallback` no longer holds the streamed shell; it renders inside the nearest `<Suspense>` 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<TError>` 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<boolean>` (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 diff --git a/packages/router-core/INTERNALS.md b/packages/router-core/INTERNALS.md deleted file mode 100644 index 4ef0dfa031..0000000000 --- a/packages/router-core/INTERNALS.md +++ /dev/null @@ -1,1410 +0,0 @@ -# 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 deleted file mode 100644 index 6628455c0a..0000000000 --- a/packages/router-core/benchmarks/ssr-streaming/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/results/ diff --git a/packages/router-core/benchmarks/ssr-streaming/README.md b/packages/router-core/benchmarks/ssr-streaming/README.md deleted file mode 100644 index bda5d4ee12..0000000000 --- a/packages/router-core/benchmarks/ssr-streaming/README.md +++ /dev/null @@ -1,162 +0,0 @@ -# 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 deleted file mode 100644 index 2d1f2245c2..0000000000 --- a/packages/router-core/benchmarks/ssr-streaming/run.mjs +++ /dev/null @@ -1,860 +0,0 @@ -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 deleted file mode 100644 index 5a12fe2920..0000000000 --- a/packages/router-core/benchmarks/ssr-streaming/worker.ts +++ /dev/null @@ -1,2254 +0,0 @@ -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 = - '<script id="$tsr-stream-barrier">document.currentScript.remove();/*$tsr-stream-boundary*/</script>' -const SHELL_PREFIX = '<!doctype html><html><body><main>done</main>' -const PREFIX = `${SHELL_PREFIX}${BARRIER}` -const SUFFIX = '</body></html>' -const SCRIPT_OPEN = '<script>' -const SCRIPT_CLOSE = ';document.currentScript.remove()</script>' -const REACT_PATCH_PREFIX = '<div hidden id="S:0">' -const REACT_PATCH_SUFFIX = '</div><script>$RC("B:0","S:0")</script>' -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 = - '<div hidden id="S:0">x</div><script>$RC("B:0","S:0")</script>' -const SMALL_SOLID_RECORD = '<template id="solid-patch">x</template>' -const COALESCED_PATCH = '<script>applyPatch()</script>' -const COALESCED_LAST_PATCH = '<script>lastPatch()</script>' -const COALESCED_FILLER = '<div class="body">ordinary text</div>' -// 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<AppStreamValue>, - options?: { rendererSafePoint?: RendererSafePoint }, -) => ReadableStream<Uint8Array> - -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<typeof createHash>, - 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<typeof createHash>, - 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 = '<div><span>x</span></div>' - 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<string, ReturnType<typeof expected>>() - -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<Uint8Array> { - 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<Uint8Array> { - if (scenario.kind === 'coalesced-close') { - yield* coalescedCloseApplicationBytes(scenario) - return - } - if (scenario.kind === 'closing') { - yield Buffer.from(SHELL_PREFIX) - yield* repeatedPatternBytes('<div><span>x</span></div>', 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<Scenario, { kind: 'coalesced-close' }>, -) { - 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<Scenario, { kind: 'renderer-records' }>, -) { - 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<AppStreamValue>, - onEof?: () => void, - beforeEof?: Promise<void>, - onBeforeEof?: () => void, -) { - return new ReadableStream<AppStreamValue>({ - 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<Scenario, { kind: 'application-string' }>, -) { - 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<string>) => void>() - const htmlListeners = new Set<(html: string) => void>() - const finishedListeners = new Set<() => void>() - const pendingScripts: Array<string> = [] - const bufferedHtml: Array<string> = [] - const hydrationSources: Array<string | undefined> = [] - 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<void>((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<string>) => 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<void>, - 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<void>((resolve) => { - resolveProducerComplete = resolve - }) - if (!hasLateScripts) { - resolveProducerComplete() - } - let resolveAppContentConsumed!: () => void - const appContentConsumed = new Promise<void>((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<Uint8Array>) - : 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<void>((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<number>): 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<ReturnType<typeof run>> - -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<WarmBatch>, -) { - 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<number>) { - 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<string>, - requestedModes: Array<string>, - warmups: number, - iterations: number, - batchRequests: number, -) { - const results = [] - const comparisons = [] - - for (const scenarioName of scenarioNames) { - const scenario = parseScenario(scenarioName) - const availableModes: Array<Mode> = - 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<WarmBatch>> = { - baseline: [], - worktree: [], - } - const elapsedRatios: Array<number> = [] - const wallElapsedRatios: Array<number> = [] - 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<string>, - requestedModes: Array<string>, - 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<string>, -) => HydrationOwner - -type HydrationOwnerExpected = { - records: number - recordBytes: number - bytes: number - digest: string -} - -const hydrationOwnerExpectedCache = new Map<string, HydrationOwnerExpected>() - -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<string>, - 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<number>> = { - origin: [], - worktree: [], - } - const wall: Record<'origin' | 'worktree', Array<number>> = { - origin: [], - worktree: [], - } - const samples = [] - const firstResult: Partial< - Record<'origin' | 'worktree', ReturnType<typeof measureHydrationOwner>> - > = {} - 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/bin/intent.js b/packages/router-core/bin/intent.js new file mode 100755 index 0000000000..5b08532885 --- /dev/null +++ b/packages/router-core/bin/intent.js @@ -0,0 +1,25 @@ +#!/usr/bin/env node +// Auto-generated by @tanstack/intent setup +// Exposes the intent end-user CLI for consumers of this library. +// Commit this file, then add to your package.json: +// "bin": { "intent": "./bin/intent.js" } +try { + await import('@tanstack/intent/intent-library') +} catch (e) { + const isModuleNotFound = + e?.code === 'ERR_MODULE_NOT_FOUND' || e?.code === 'MODULE_NOT_FOUND' + const missingIntentLibrary = + typeof e?.message === 'string' && e.message.includes('@tanstack/intent') + + if (isModuleNotFound && missingIntentLibrary) { + console.error('@tanstack/intent is not installed.') + console.error('') + console.error('Install it as a dev dependency:') + console.error(' npm add -D @tanstack/intent') + console.error('') + console.error('Or run directly:') + console.error(' npx @tanstack/intent@latest list') + process.exit(1) + } + throw e +} diff --git a/packages/router-core/package.json b/packages/router-core/package.json index ed2b794278..63c008514a 100644 --- a/packages/router-core/package.json +++ b/packages/router-core/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/router-core", - "version": "1.171.39", + "version": "1.168.1", "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": "node ../../node_modules/typescript59/lib/tsc.js", - "test:types:ts60": "tsc6", - "test:types:ts70": "tsc", + "test:types:ts59": "tsc", "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", "test:unit": "vitest", "test:unit:dev": "pnpm run test:unit --watch", @@ -148,26 +148,6 @@ "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, @@ -183,20 +163,19 @@ }, "dependencies": { "@tanstack/history": "workspace:*", - "cookie-es": "^3.0.0", - "seroval": "^1.6.7", - "seroval-plugins": "^1.6.7" + "cookie-es": "^2.0.0", + "seroval": "^1.4.2", + "seroval-plugins": "^1.4.2", + "tiny-invariant": "^1.3.3", + "tiny-warning": "^1.0.3" }, "devDependencies": { - "@tanstack/store": "^0.11.2", - "@types/node": "25.0.9", + "@tanstack/store": "^0.9.2", + "@tanstack/intent": "^0.0.14", "esbuild": "^0.27.4", - "vite": "catalog:", - "@tanstack/vite-config": "catalog:", - "vitest": "catalog:", - "jsdom": "catalog:", - "@arethetypeswrong/cli": "catalog:", - "publint": "catalog:", - "rimraf": "catalog:" + "vite": "*" + }, + "bin": { + "intent": "./bin/intent.js" } } diff --git a/packages/router-core/skills/router-core/SKILL.md b/packages/router-core/skills/router-core/SKILL.md index cadb832037..de11b17d28 100644 --- a/packages/router-core/skills/router-core/SKILL.md +++ b/packages/router-core/skills/router-core/SKILL.md @@ -5,10 +5,9 @@ description: >- 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' +type: core +library: tanstack-router +library_version: '1.166.2' --- # TanStack Router Core @@ -19,8 +18,6 @@ TanStack Router is a type-safe router for React and Solid with built-in SWR cach > **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 | @@ -69,22 +66,6 @@ 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 @@ -155,4 +136,4 @@ The plugin auto-generates this string. If you rename a route file, the plugin up ## Version Note -This skill targets `@tanstack/router-core` v1.171.15. Splat routes use `$` (not `*`); the `*` compat alias will be removed in v2. +This skill targets `@tanstack/router-core` v1.166.2 and `@tanstack/react-router` v1.166.2. APIs are stable. 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 index 4d1a6a3b6e..b11ab95fb3 100644 --- a/packages/router-core/skills/router-core/auth-and-guards/SKILL.md +++ b/packages/router-core/skills/router-core/auth-and-guards/SKILL.md @@ -1,17 +1,17 @@ --- -name: auth-and-guards +name: router-core/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' +type: sub-skill +library: tanstack-router +library_version: '1.166.2' requires: - router-core + - router-core/data-loading sources: - TanStack/router:docs/router/guide/authenticated-routes.md - TanStack/router:docs/router/how-to/setup-authentication.md @@ -21,10 +21,6 @@ sources: # 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`): @@ -375,45 +371,6 @@ export const Route = createFileRoute('/_authenticated')({ ## 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: @@ -439,6 +396,8 @@ export const Route = createFileRoute('/_authenticated/dashboard')({ }) ``` +`beforeLoad` runs before any component rendering and before the loader. It completely prevents the flash. + ### HIGH: Not re-throwing redirects in try/catch `redirect()` works by throwing. If `beforeLoad` has a try/catch, the redirect gets swallowed: @@ -492,8 +451,8 @@ export const Route = createFileRoute('/_authenticated')({ 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 index aac9098121..8d1ba4e7a5 100644 --- a/packages/router-core/skills/router-core/code-splitting/SKILL.md +++ b/packages/router-core/skills/router-core/code-splitting/SKILL.md @@ -1,14 +1,13 @@ --- -name: code-splitting +name: router-core/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' +type: sub-skill +library: tanstack-router +library_version: '1.166.2' requires: - router-core sources: diff --git a/packages/router-core/skills/router-core/data-loading/SKILL.md b/packages/router-core/skills/router-core/data-loading/SKILL.md index 6a4364ff1f..59a71a0cca 100644 --- a/packages/router-core/skills/router-core/data-loading/SKILL.md +++ b/packages/router-core/skills/router-core/data-loading/SKILL.md @@ -1,15 +1,14 @@ --- -name: data-loading +name: router-core/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' +type: sub-skill +library: tanstack-router +library_version: '1.166.2' requires: - router-core sources: @@ -217,29 +216,13 @@ Route-level context via `beforeLoad`: ```tsx export const Route = createFileRoute('/posts')({ - beforeLoad: ({ context }) => ({ - fetchPosts: context.fetchPosts, + beforeLoad: () => ({ + fetchPosts: () => fetch('/api/posts').then((r) => r.json()), }), 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: @@ -293,17 +276,19 @@ function AddPostButton() { const router = useRouter() const handleAdd = async () => { - await createPost({ title: 'New post' }) - await router.invalidate({ sync: true }) + await fetch('/api/posts', { method: 'POST', body: '...' }) + router.invalidate() } return <button onClick={handleAdd}>Add Post</button> } ``` -Use `await router.invalidate({ sync: true })` when the next step requires refreshed loader data. +For synchronous invalidation (wait until loaders finish): -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. +```tsx +await router.invalidate({ sync: true }) +``` ### Error Handling @@ -376,13 +361,16 @@ export const Route = createFileRoute('/posts')({ }, }) -// CORRECT for an SPA — use a client-safe API helper +// CORRECT — loaders run in the browser, use fetch or API calls export const Route = createFileRoute('/posts')({ - loader: () => fetchPosts(), + loader: async () => { + const res = await fetch('/api/posts') + return res.json() + }, }) ``` -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. +Do NOT put database queries, filesystem access, or server-only code in loaders unless you are using TanStack Start server functions. ### MEDIUM: Not understanding staleTime default is 0 diff --git a/packages/router-core/skills/router-core/navigation/SKILL.md b/packages/router-core/skills/router-core/navigation/SKILL.md index ba1f0fd2e6..0e09ddbcec 100644 --- a/packages/router-core/skills/router-core/navigation/SKILL.md +++ b/packages/router-core/skills/router-core/navigation/SKILL.md @@ -1,15 +1,14 @@ --- -name: navigation +name: router-core/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' +type: sub-skill +library: tanstack-router +library_version: '1.166.2' requires: - router-core sources: 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 index 45b231f41e..b4fde048f8 100644 --- 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 @@ -1,14 +1,13 @@ --- -name: not-found-and-errors +name: router-core/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' +type: sub-skill +library: tanstack-router +library_version: '1.166.2' requires: - router-core sources: @@ -169,15 +168,15 @@ export const Route = createFileRoute('/posts/$postId')({ function PostErrorComponent({ error, }: { - error: unknown - info?: { componentStack: string } + error: Error + info: { componentStack: string } reset: () => void }) { const router = useRouter() return ( <div> - <p>Error: {error instanceof Error ? error.message : String(error)}</p> + <p>Error: {error.message}</p> <button onClick={() => { // Invalidate re-runs the loader and resets the error boundary @@ -205,10 +204,7 @@ const router = createRouter({ const router = useRouter() return ( <div> - <p> - Something went wrong:{' '} - {error instanceof Error ? error.message : String(error)} - </p> + <p>Something went wrong: {error.message}</p> <button onClick={() => { router.invalidate() @@ -414,18 +410,12 @@ Masking data lives in `location.state` (browser history). When a masked URL is c ```tsx // WRONG — reset() clears the error boundary but does NOT re-run the loader -function ErrorFallback({ - error, - reset, -}: { - error: unknown - reset: () => void -}) { +function ErrorFallback({ error, reset }: { error: Error; reset: () => void }) { return <button onClick={reset}>Retry</button> } // CORRECT — invalidate re-runs loaders and resets the error boundary -function ErrorFallback({ error }: { error: unknown; reset: () => void }) { +function ErrorFallback({ error }: { error: Error; reset: () => void }) { const router = useRouter() return ( <button diff --git a/packages/router-core/skills/router-core/path-params/SKILL.md b/packages/router-core/skills/router-core/path-params/SKILL.md index b4819f04b5..32964d06cc 100644 --- a/packages/router-core/skills/router-core/path-params/SKILL.md +++ b/packages/router-core/skills/router-core/path-params/SKILL.md @@ -1,14 +1,13 @@ --- -name: path-params +name: router-core/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' +type: sub-skill +library: tanstack-router +library_version: '1.166.2' requires: - router-core sources: diff --git a/packages/router-core/skills/router-core/search-params/SKILL.md b/packages/router-core/skills/router-core/search-params/SKILL.md index 0960297d00..5b509e5a50 100644 --- a/packages/router-core/skills/router-core/search-params/SKILL.md +++ b/packages/router-core/skills/router-core/search-params/SKILL.md @@ -1,14 +1,13 @@ --- -name: search-params +name: router-core/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' +type: sub-skill +library: tanstack-router +library_version: '1.166.2' requires: - router-core sources: 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 index a0c72c7bd2..999bcb2ebf 100644 --- 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 @@ -329,12 +329,7 @@ export const Route = createFileRoute('/products')({ } return { page } }, - errorComponent: ({ error }) => ( - <div> - Bad search params:{' '} - {error instanceof Error ? error.message : String(error)} - </div> - ), + errorComponent: ({ error }) => <div>Bad search params: {error.message}</div>, }) ``` diff --git a/packages/router-core/skills/router-core/ssr/SKILL.md b/packages/router-core/skills/router-core/ssr/SKILL.md index 752fb837a5..1871c0f950 100644 --- a/packages/router-core/skills/router-core/ssr/SKILL.md +++ b/packages/router-core/skills/router-core/ssr/SKILL.md @@ -1,5 +1,5 @@ --- -name: ssr +name: router-core/ssr description: >- Non-streaming and streaming SSR, RouterClient/RouterServer, renderRouterToString/renderRouterToStream, createRequestHandler, @@ -7,10 +7,9 @@ description: >- 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' +type: sub-skill +library: tanstack-router +library_version: '1.166.2' requires: - router-core - router-core/data-loading @@ -392,74 +391,22 @@ component: () => { } ``` -### 3. CRITICAL: Generating Next.js, Remix, or React Router DOM patterns +### 3. CRITICAL: Generating Next.js or Remix SSR 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 +TanStack Router does NOT use `getServerSideProps`, `getStaticProps`, App Router `page.tsx`, or Remix-style server-only `loader` exports. ```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 +// WRONG — Next.js patterns export async function getServerSideProps() { return { props: { data: await fetchData() } } } -// WRONG — Remix +// WRONG — Remix patterns export async function loader({ request }: LoaderFunctionArgs) { return json({ data: await fetchData() }) } -// CORRECT — TanStack Router +// CORRECT — TanStack Router pattern export const Route = createFileRoute('/data')({ loader: async () => { const data = await fetchData() @@ -474,8 +421,6 @@ function DataPage() { } ``` -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: @@ -489,4 +434,4 @@ 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 +- [compositions/router-query](../../../../react-router/skills/compositions/router-query/SKILL.md) — 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 index 15b9d35770..eb258a994f 100644 --- a/packages/router-core/skills/router-core/type-safety/SKILL.md +++ b/packages/router-core/skills/router-core/type-safety/SKILL.md @@ -1,15 +1,14 @@ --- -name: type-safety +name: router-core/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' +type: sub-skill +library: tanstack-router +library_version: '1.166.2' requires: - router-core sources: @@ -230,17 +229,17 @@ With file-based routing the route tree is generated, so this is handled for you. 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 +// SLOWER — TS infers the full ensureQueryData return type into the route tree export const Route = createFileRoute('/posts/$postId')({ loader: ({ context: { queryClient }, params: { postId } }) => - queryClient.query({ ...postQueryOptions(postId), staleTime: 'static' }), + queryClient.ensureQueryData(postQueryOptions(postId)), component: PostComponent, }) -// FASTER — async loader returns no query data, inference stays out of the route tree +// FASTER — void return, 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' }) + loader: async ({ context: { queryClient }, params: { postId } }) => { + await queryClient.ensureQueryData(postQueryOptions(postId)) }, component: PostComponent, }) @@ -314,9 +313,7 @@ export function NavItem(props: NavItemProps): React.ReactNode { <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: +### `ValidateNavigateOptions` — Type-Safe Navigate in Utilities ```tsx import { @@ -335,15 +332,45 @@ export function useDelayedNavigate< export function useDelayedNavigate( options: ValidateNavigateOptions, delayMs: number, -) { +): () => void { const navigate = useNavigate() return () => { setTimeout(() => navigate(options), delayMs) } } + +// Usage — type-safe +const go = useDelayedNavigate( + { to: '/posts/$postId', params: { postId: '1' } }, + 500, +) ``` -`ValidateRedirectOptions` works identically — declare a generic overload accepting `ValidateRedirectOptions<TRouter, TOptions>` and an impl signature accepting `ValidateRedirectOptions`, then call `redirect(options)` in the body. +### `ValidateRedirectOptions` — Type-Safe Redirect in Utilities + +```tsx +import { + redirect, + type RegisteredRouter, + type ValidateRedirectOptions, +} from '@tanstack/react-router' + +export async function fetchOrRedirect< + TRouter extends RegisteredRouter = RegisteredRouter, + TOptions = unknown, +>( + url: string, + redirectOptions: ValidateRedirectOptions<TRouter, TOptions>, +): Promise<unknown> +export async function fetchOrRedirect( + url: string, + redirectOptions: ValidateRedirectOptions, +): Promise<unknown> { + const response = await fetch(url) + if (!response.ok && response.status === 401) throw redirect(redirectOptions) + return response.json() +} +``` ### Render Props for Maximum Performance @@ -450,50 +477,21 @@ declare module '@tanstack/react-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. +### 5. CRITICAL (cross-skill): Generating Next.js or Remix patterns ```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' +// WRONG — these are NOT TanStack Router APIs +export async function getServerSideProps() { ... } +export async function loader({ request }) { ... } // Remix-style +const [searchParams, setSearchParams] = useSearchParams() // React Router -// 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 +// CORRECT — TanStack Router APIs export const Route = createFileRoute('/posts')({ - loader: async () => { ... }, - validateSearch: zodValidator(schema), + loader: async () => { ... }, // TanStack loader + validateSearch: zodValidator(schema), // TanStack search validation component: PostsComponent, }) -const search = Route.useSearch() +const search = Route.useSearch() // TanStack hook ``` -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 41fd4018b5..852d186b67 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 } from './utils' +import type { Constrain, ControlledPromise } from './utils' export type AnyMatchAndValue = { match: any; value: any } @@ -131,32 +131,47 @@ export interface RouteMatch< pathname: string params: TAllParams _strictParams: TAllParams - status: 'pending' | 'success' | 'error' | 'notFound' + status: 'pending' | 'success' | 'error' | 'redirected' | '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 */ - _ctx?: Record<string, unknown> + __routeContext?: 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> - _notFound?: boolean + globalNotFound?: 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 deleted file mode 100644 index 61d59bde2d..0000000000 --- a/packages/router-core/src/await-signal.ts +++ /dev/null @@ -1,61 +0,0 @@ -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/index.ts b/packages/router-core/src/index.ts index 9206ef60dd..ad1389ff23 100644 --- a/packages/router-core/src/index.ts +++ b/packages/router-core/src/index.ts @@ -2,7 +2,6 @@ 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, @@ -68,47 +67,8 @@ export type { } from './fileRoute' export type { ParsedLocation } from './location' -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 type { Manifest, RouterManagedTag } from './manifest' export { isMatch } from './Matches' -export { - _getAssetMatches, - _getRenderedMatches, - _isRouteDeparting, -} from './load-client' -export { composeSsrBodyScripts, getSsrBodyScriptParts } from './ssr/bodyScripts' export type { AnyMatchAndValue, FindValueByIndex, @@ -138,8 +98,6 @@ export { exactPathTest, resolvePath, interpolatePath, - getRouteSegments, - hasMissingPathParams, } from './path' export { encode, decode } from './qss' export { rootRouteId } from './root' @@ -170,8 +128,6 @@ export type { DefaultSearchValidator, ErrorRouteProps, ErrorComponentProps, - DefaultErrorBoundaryTypes, - ErrorBoundaryTypes, NotFoundRouteProps, ResolveParams, ParseParamsFn, @@ -215,7 +171,6 @@ export type { RouteContextFn, ContextOptions, RouteContextOptions, - SsrContextOptions, BeforeLoadContextOptions, RootRouteOptions, RootRouteOptionsExtensions, @@ -252,6 +207,7 @@ export { SearchParamError, PathParamError, getInitialRouterState, + getMatchedRoutes, trailingSlashOptions, } from './router' @@ -280,9 +236,12 @@ export type { ParseLocationFn, InvalidateFn, ControllablePromise, + InjectedHtmlEntry, EmitFn, LoadFn, + GetMatchFn, SubscribeFn, + UpdateMatchFn, CommitLocationFn, GetMatchRoutesFn, MatchRoutesFn, @@ -316,15 +275,14 @@ export type { OptionalStructuralSharing } from './structuralSharing' export { functionalUpdate, - hasKeys, replaceEqualDeep, + isPlainObject, + isPlainArray, deepEqual, createControlledPromise, - isPromise, isModuleNotFoundError, DEFAULT_PROTOCOL_ALLOWLIST, escapeHtml, - getUrlScheme, isDangerousProtocol, buildDevStylesUrl, } from './utils' @@ -431,9 +389,12 @@ export { isNotFound, notFound } from './not-found' export { defaultGetScrollRestorationKey, - getElementScrollRestorationEntry, + restoreScroll, storageKey, + getCssSelector, + scrollRestorationCache, setupScrollRestoration, + handleHashScroll, } from './scroll-restoration' export type { @@ -466,6 +427,7 @@ export type { AnySerializationAdapter, SerializationAdapter, ValidateSerializableInput, + ValidateSerializableInputResult, SerializerExtensions, ValidateSerializable, RegisteredSerializableInput, @@ -474,13 +436,21 @@ export type { Serializable, TSR_SERIALIZABLE, TsrSerializable, - SerializationError, } from './ssr/serializer/transformer' -export { createSerializationAdapter } from './ssr/serializer/transformer' -export { makeSerovalPlugin } from './ssr/serializer/makeSerovalPlugin' +export { + createSerializationAdapter, + makeSerovalPlugin, + makeSsrSerovalPlugin, +} from './ssr/serializer/transformer' -export { RawStream } from './ssr/serializer/RawStream' +export { defaultSerovalPlugins } from './ssr/serializer/seroval-plugins' + +export { + RawStream, + createRawStreamRPCPlugin, + createRawStreamDeserializePlugin, +} from './ssr/serializer/RawStream' export type { OnRawStreamCallback, RawStreamHint, diff --git a/packages/router-core/src/invariant.ts b/packages/router-core/src/invariant.ts deleted file mode 100644 index 926b8793a9..0000000000 --- a/packages/router-core/src/invariant.ts +++ /dev/null @@ -1,3 +0,0 @@ -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 index e12407f409..f2f86b6ec7 100644 --- a/packages/router-core/src/isServer/client.ts +++ b/packages/router-core/src/isServer/client.ts @@ -1,2 +1 @@ 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 index e4f13879ad..3632fabf05 100644 --- a/packages/router-core/src/isServer/development.ts +++ b/packages/router-core/src/isServer/development.ts @@ -1,3 +1,2 @@ // 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 index d13401a9e9..cfa181440a 100644 --- a/packages/router-core/src/isServer/server.ts +++ b/packages/router-core/src/isServer/server.ts @@ -1,2 +1 @@ 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 799ae50811..55d5a79ce8 100644 --- a/packages/router-core/src/link.ts +++ b/packages/router-core/src/link.ts @@ -671,15 +671,13 @@ export interface LinkOptionsProps { /** * The preloading strategy for this link * - `false` - No preloading - * - `'intent'` - Preload the linked route when the user focuses, hovers over, or touches the link + * - `'intent'` - Preload the linked route on hover and cache it for this many milliseconds in hopes that the user will eventually navigate there. * - `'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' /** - * 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. + * 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. */ preloadDelay?: number /** diff --git a/packages/router-core/src/load-client.ts b/packages/router-core/src/load-client.ts deleted file mode 100644 index e84bb8fba5..0000000000 --- a/packages/router-core/src/load-client.ts +++ /dev/null @@ -1,2570 +0,0 @@ -// 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 new file mode 100644 index 0000000000..8407195078 --- /dev/null +++ b/packages/router-core/src/load-matches.ts @@ -0,0 +1,1275 @@ +import invariant from 'tiny-invariant' +import { isServer } from '@tanstack/router-core/isServer' +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 + serialError?: unknown + updateMatch: UpdateMatchFn + matches: Array<AnyRouteMatch> + preload?: boolean + forceStaleReload?: boolean + onReady?: () => Promise<void> + sync?: boolean +} + +const triggerOnReady = (inner: InnerLoadContext): void | Promise<void> => { + if (!inner.rendered) { + inner.rendered = true + return inner.onReady?.() + } +} + +const hasForcePendingActiveMatch = (router: AnyRouter): boolean => { + return router.stores.matchesId.state.some((matchId) => { + return router.stores.activeMatchStoresById.get(matchId)?.state._forcePending + }) +} + +const resolvePreload = (inner: InnerLoadContext, matchId: string): boolean => { + return !!( + inner.preload && !inner.router.stores.activeMatchStoresById.has(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 getNotFoundBoundaryIndex = ( + inner: InnerLoadContext, + err: NotFoundError, +): number | undefined => { + if (!inner.matches.length) { + return undefined + } + + const requestedRouteId = err.routeId + const matchedRootIndex = inner.matches.findIndex( + (m) => m.routeId === inner.router.routeTree.id, + ) + const rootIndex = matchedRootIndex >= 0 ? matchedRootIndex : 0 + + let startIndex = requestedRouteId + ? inner.matches.findIndex((match) => match.routeId === requestedRouteId) + : (inner.firstBadMatchIndex ?? inner.matches.length - 1) + + if (startIndex < 0) { + startIndex = rootIndex + } + + for (let i = startIndex; i >= 0; i--) { + const match = inner.matches[i]! + const route = inner.router.looseRoutesById[match.routeId]! + if (route.options.notFoundComponent) { + return i + } + } + + // If no boundary component is found, preserve explicit routeId targeting behavior, + // otherwise default to root for untargeted notFounds. + return requestedRouteId ? startIndex : rootIndex +} + +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 + + match._nonReactive.error = err + + inner.updateMatch(match.id, (prev) => ({ + ...prev, + status: isRedirect(err) + ? 'redirected' + : prev.status === 'pending' + ? 'success' + : prev.status, + context: buildMatchContext(inner, match.index), + isFetching: false, + error: err, + })) + + if (isNotFound(err) && !err.routeId) { + // Stamp the throwing match's routeId so that the finalization step in + // loadMatches knows where the notFound originated. The actual boundary + // resolution (walking up to the nearest notFoundComponent) is deferred to + // the finalization step, where firstBadMatchIndex is stable and + // headMaxIndex can be capped correctly. + 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 +} + +const shouldSkipLoader = ( + inner: InnerLoadContext, + matchId: string, +): boolean => { + const match = inner.router.getMatch(matchId) + if (!match) { + return true + } + // upon hydration, we skip the loader if the match has been dehydrated on the server + if (!(isServer ?? inner.router.isServer) && match._nonReactive.dehydrated) { + return true + } + + if ((isServer ?? inner.router.isServer) && match.ssr === false) { + return true + } + + return false +} + +const syncMatchContext = ( + inner: InnerLoadContext, + matchId: string, + index: number, +): void => { + const nextContext = buildMatchContext(inner, index) + + inner.updateMatch(matchId, (prev) => { + return { + ...prev, + context: nextContext, + } + }) +} + +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(), + } + }) + + if (!inner.preload && !isRedirect(err) && !isNotFound(err)) { + inner.serialError ??= err + } +} + +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 && + !(isServer ?? 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 + let prevLoadPromise = match._nonReactive.loadPromise + match._nonReactive.loadPromise = createControlledPromise<void>(() => { + prevLoadPromise?.resolve() + prevLoadPromise = undefined + }) + + 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() + + 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) { + inner.router.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, + 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, + routeId: route.id, + ...inner.router.options.additionalContext, + } + + const updateContext = (beforeLoadContext: any) => { + if (beforeLoadContext === undefined) { + inner.router.batch(() => { + pending() + resolve() + }) + return + } + if (isRedirect(beforeLoadContext) || isNotFound(beforeLoadContext)) { + pending() + handleSerialError(inner, index, beforeLoadContext, 'BEFORE_LOAD') + } + + inner.router.batch(() => { + pending() + 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 (isServer ?? 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 = { + ssr: inner.router.options.ssr, + 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, + matchPromises: Array<Promise<AnyRouteMatch>>, + matchId: string, + index: number, + route: AnyRoute, +): LoaderFnContext => { + const parentMatchPromise = 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, + matchPromises: Array<Promise<AnyRouteMatch>>, + 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 (!(isServer ?? inner.router.isServer) || match.ssr === true) { + loadRouteChunk(route) + } + + // Kick off the loader! + const routeLoader = route.options.loader + const loader = + typeof routeLoader === 'function' ? routeLoader : routeLoader?.handler + const loaderResult = loader?.( + getLoaderContext(inner, matchPromises, matchId, index, route), + ) + const loaderResultIsPromise = !!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 (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 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, + context: buildMatchContext(inner, index), + status: 'success', + isFetching: false, + updatedAt: Date.now(), + })) + } catch (e) { + let error = e + + if ((error as any)?.name === 'AbortError') { + if (match.abortController.signal.aborted) { + match._nonReactive.loaderPromise?.resolve() + match._nonReactive.loaderPromise = undefined + return + } + inner.updateMatch(matchId, (prev) => ({ + ...prev, + status: prev.status === 'pending' ? 'success' : prev.status, + isFetching: false, + context: buildMatchContext(inner, index), + })) + return + } + + 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, + ) + } + if (!isRedirect(error) && !isNotFound(error)) { + await loadRouteChunk(route, ['errorComponent']) + } + + inner.updateMatch(matchId, (prev) => ({ + ...prev, + error, + context: buildMatchContext(inner, index), + status: 'error', + isFetching: false, + })) + } + } catch (err) { + const match = inner.router.getMatch(matchId) + // in case of a redirecting match during preload, the match does not exist + if (match) { + match._nonReactive.loaderPromise = undefined + } + handleRedirectAndNotFound(inner, match, err) + } +} + +const loadRouteMatch = async ( + inner: InnerLoadContext, + matchPromises: Array<Promise<AnyRouteMatch>>, + index: number, +): Promise<AnyRouteMatch> => { + async function handleLoader( + preload: boolean, + prevMatch: AnyRouteMatch, + previousRouteMatchId: string | undefined, + match: AnyRouteMatch, + route: AnyRoute, + ) { + const age = Date.now() - prevMatch.updatedAt + + 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, matchPromises, matchId, index, route), + ) + : shouldReloadOption + + // If the route is successful and still fresh, just resolve + const { status, invalid } = match + const staleMatchShouldReload = + age >= staleAge && + (!!inner.forceStaleReload || + match.cause === 'enter' || + (previousRouteMatchId !== undefined && + previousRouteMatchId !== match.id)) + loaderShouldRunAsync = + status === 'success' && + (invalid || (shouldReload ?? staleMatchShouldReload)) + if (preload && route.options.preload === false) { + // Do nothing + } else if ( + loaderShouldRunAsync && + !inner.sync && + shouldReloadInBackground + ) { + loaderIsRunningAsync = true + ;(async () => { + try { + await runLoader(inner, matchPromises, matchId, index, route) + const match = inner.router.getMatch(matchId)! + match._nonReactive.loaderPromise?.resolve() + match._nonReactive.loadPromise?.resolve() + match._nonReactive.loaderPromise = undefined + match._nonReactive.loadPromise = undefined + } catch (err) { + if (isRedirect(err)) { + await inner.router.navigate(err.options) + } + } + })() + } else if (status !== 'success' || loaderShouldRunAsync) { + await runLoader(inner, matchPromises, matchId, index, route) + } else { + syncMatchContext(inner, matchId, index) + } + } + + const { id: matchId, routeId } = inner.matches[index]! + let loaderShouldRunAsync = false + let loaderIsRunningAsync = false + const route = inner.router.looseRoutesById[routeId]! + const routeLoader = route.options.loader + const shouldReloadInBackground = + ((typeof routeLoader === 'function' + ? undefined + : routeLoader?.staleReloadMode) ?? + inner.router.options.defaultStaleReloadMode) !== 'blocking' + + if (shouldSkipLoader(inner, matchId)) { + const match = inner.router.getMatch(matchId) + if (!match) { + return inner.matches[index]! + } + + syncMatchContext(inner, matchId, index) + + if (isServer ?? inner.router.isServer) { + return inner.router.getMatch(matchId)! + } + } else { + const prevMatch = inner.router.getMatch(matchId)! // This is where all of the stale-while-revalidate magic happens + const activeIdAtIndex = inner.router.stores.matchesId.state[index] + const activeAtIndex = + (activeIdAtIndex && + inner.router.stores.activeMatchStoresById.get(activeIdAtIndex)) || + null + const previousRouteMatchId = + activeAtIndex?.routeId === routeId + ? activeIdAtIndex + : inner.router.stores.activeMatchesSnapshot.state.find( + (d) => d.routeId === routeId, + )?.id + const preload = resolvePreload(inner, 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 && + shouldReloadInBackground + ) { + 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) + } + + if (match.status === 'pending') { + await handleLoader( + preload, + prevMatch, + previousRouteMatchId, + match, + route, + ) + } + } else { + const nextPreload = + preload && !inner.router.stores.activeMatchStoresById.has(matchId) + const match = inner.router.getMatch(matchId)! + match._nonReactive.loaderPromise = createControlledPromise<void>() + if (nextPreload !== match.preload) { + inner.updateMatch(matchId, (prev) => ({ + ...prev, + preload: nextPreload, + })) + } + + await handleLoader(preload, prevMatch, previousRouteMatchId, match, route) + } + } + const match = inner.router.getMatch(matchId)! + if (!loaderIsRunningAsync) { + match._nonReactive.loaderPromise?.resolve() + match._nonReactive.loadPromise?.resolve() + match._nonReactive.loadPromise = undefined + } + + clearTimeout(match._nonReactive.pendingTimeout) + match._nonReactive.pendingTimeout = undefined + if (!loaderIsRunningAsync) match._nonReactive.loaderPromise = undefined + match._nonReactive.dehydrated = undefined + + 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 + forceStaleReload?: boolean + onReady?: () => Promise<void> + updateMatch: UpdateMatchFn + sync?: boolean +}): Promise<Array<MakeRouteMatch>> { + const inner: InnerLoadContext = arg + const matchPromises: Array<Promise<AnyRouteMatch>> = [] + + // 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 ( + !(isServer ?? inner.router.isServer) && + hasForcePendingActiveMatch(inner.router) + ) { + triggerOnReady(inner) + } + + let beforeLoadNotFound: NotFoundError | undefined + + // Execute all beforeLoads one by one + for (let i = 0; i < inner.matches.length; i++) { + try { + const beforeLoad = handleBeforeLoad(inner, i) + if (isPromise(beforeLoad)) await beforeLoad + } catch (err) { + if (isRedirect(err)) { + throw err + } + if (isNotFound(err)) { + beforeLoadNotFound = err + } else { + if (!inner.preload) throw err + } + break + } + + if (inner.serialError) { + break + } + } + + // Execute loaders once, with max index adapted for beforeLoad notFound handling. + const baseMaxIndexExclusive = inner.firstBadMatchIndex ?? inner.matches.length + + const boundaryIndex = + beforeLoadNotFound && !inner.preload + ? getNotFoundBoundaryIndex(inner, beforeLoadNotFound) + : undefined + + const maxIndexExclusive = + beforeLoadNotFound && inner.preload + ? 0 + : boundaryIndex !== undefined + ? Math.min(boundaryIndex + 1, baseMaxIndexExclusive) + : baseMaxIndexExclusive + + let firstNotFound: NotFoundError | undefined + let firstUnhandledRejection: unknown + + for (let i = 0; i < maxIndexExclusive; i++) { + matchPromises.push(loadRouteMatch(inner, matchPromises, i)) + } + + try { + await Promise.all(matchPromises) + } catch { + const settled = await Promise.allSettled(matchPromises) + + for (const result of settled) { + if (result.status !== 'rejected') continue + + const reason = result.reason + if (isRedirect(reason)) { + throw reason + } + if (isNotFound(reason)) { + firstNotFound ??= reason + } else { + firstUnhandledRejection ??= reason + } + } + + if (firstUnhandledRejection !== undefined) { + throw firstUnhandledRejection + } + } + + const notFoundToThrow = + firstNotFound ?? + (beforeLoadNotFound && !inner.preload ? beforeLoadNotFound : undefined) + + let headMaxIndex = inner.serialError + ? (inner.firstBadMatchIndex ?? 0) + : inner.matches.length - 1 + + if (!notFoundToThrow && beforeLoadNotFound && inner.preload) { + return inner.matches + } + + if (notFoundToThrow) { + // Determine once which matched route will actually render the + // notFoundComponent, then pass this precomputed index through the remaining + // finalization steps. + // This can differ from the throwing route when routeId targets an ancestor + // boundary (or when bubbling resolves to a parent/root boundary). + const renderedBoundaryIndex = getNotFoundBoundaryIndex( + inner, + notFoundToThrow, + ) + + invariant( + renderedBoundaryIndex !== undefined, + 'Could not find match for notFound boundary', + ) + const boundaryMatch = inner.matches[renderedBoundaryIndex]! + + const boundaryRoute = inner.router.looseRoutesById[boundaryMatch.routeId]! + const defaultNotFoundComponent = (inner.router.options as any) + ?.defaultNotFoundComponent + + // Ensure a notFoundComponent exists on the boundary route + if (!boundaryRoute.options.notFoundComponent && defaultNotFoundComponent) { + boundaryRoute.options.notFoundComponent = defaultNotFoundComponent + } + + notFoundToThrow.routeId = boundaryMatch.routeId + + const boundaryIsRoot = boundaryMatch.routeId === inner.router.routeTree.id + + inner.updateMatch(boundaryMatch.id, (prev) => ({ + ...prev, + ...(boundaryIsRoot + ? // For root boundary, use globalNotFound so the root component's + // shell still renders and <Outlet> handles the not-found display, + // instead of replacing the entire root shell via status='notFound'. + { status: 'success' as const, globalNotFound: true, error: undefined } + : // For non-root boundaries, set status:'notFound' so MatchInner + // renders the notFoundComponent directly. + { status: 'notFound' as const, error: notFoundToThrow }), + isFetching: false, + })) + + headMaxIndex = renderedBoundaryIndex + + // Ensure the rendering boundary route chunk (and its lazy components, including + // lazy notFoundComponent) is loaded before we continue to head execution/render. + await loadRouteChunk(boundaryRoute, ['notFoundComponent']) + } else if (!inner.preload) { + // Clear stale root global-not-found state on normal navigations that do not + // throw notFound. This must live here (instead of only in runLoader success) + // because the root loader may be skipped when data is still fresh. + const rootMatch = inner.matches[0]! + // `rootMatch` is the next match for this navigation. If it is not global + // not-found, then any currently stored root global-not-found is stale. + if (!rootMatch.globalNotFound) { + // `currentRootMatch` is the current store state (from the previous + // navigation/load). Update only when a stale flag is actually present. + const currentRootMatch = inner.router.getMatch(rootMatch.id) + if (currentRootMatch?.globalNotFound) { + inner.updateMatch(rootMatch.id, (prev) => ({ + ...prev, + globalNotFound: false, + error: undefined, + })) + } + } + } + + // When a serial error occurred (e.g. beforeLoad threw a regular Error), + // the erroring route's lazy chunk wasn't loaded because loaders were skipped. + // We need to load it so the code-split errorComponent is available for rendering. + if (inner.serialError && inner.firstBadMatchIndex !== undefined) { + const errorRoute = + inner.router.looseRoutesById[ + inner.matches[inner.firstBadMatchIndex]!.routeId + ]! + await loadRouteChunk(errorRoute, ['errorComponent']) + } + + // serially execute heads once after loaders/notFound handling, ensuring + // all head functions get a chance even if one throws. + for (let i = 0; i <= headMaxIndex; i++) { + const match = inner.matches[i]! + const { id: matchId, routeId } = match + const route = inner.router.looseRoutesById[routeId]! + try { + const headResult = executeHead(inner, matchId, route) + if (headResult) { + const head = await headResult + inner.updateMatch(matchId, (prev) => ({ + ...prev, + ...head, + })) + } + } catch (err) { + console.error(`Error executing head for route ${routeId}:`, err) + } + } + + const readyPromise = triggerOnReady(inner) + if (isPromise(readyPromise)) { + await readyPromise + } + + if (notFoundToThrow) { + throw notFoundToThrow + } + + if (inner.serialError && !inner.preload && !inner.onReady) { + throw inner.serialError + } + + return inner.matches +} + +export type RouteComponentType = + | 'component' + | 'errorComponent' + | 'pendingComponent' + | 'notFoundComponent' + +function preloadRouteComponents( + route: AnyRoute, + componentTypesToLoad: Array<RouteComponentType>, +): Promise<void> | undefined { + const preloads = componentTypesToLoad + .map((type) => (route.options[type] as any)?.preload?.()) + .filter(Boolean) + + if (preloads.length === 0) return undefined + + return Promise.all(preloads) as any as Promise<void> +} + +export function loadRouteChunk( + route: AnyRoute, + componentTypesToLoad: Array<RouteComponentType> = componentTypes, +) { + 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 + } + } + + const runAfterLazy = () => + route._componentsLoaded + ? undefined + : componentTypesToLoad === componentTypes + ? (() => { + if (route._componentsPromise === undefined) { + const componentsPromise = preloadRouteComponents( + route, + componentTypes, + ) + + if (componentsPromise) { + route._componentsPromise = componentsPromise.then(() => { + route._componentsLoaded = true + route._componentsPromise = undefined // gc promise, we won't need it anymore + }) + } else { + route._componentsLoaded = true + } + } + + return route._componentsPromise + })() + : preloadRouteComponents(route, componentTypesToLoad) + + return route._lazyPromise + ? route._lazyPromise.then(runAfterLazy) + : runAfterLazy() +} + +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: Array<RouteComponentType> = [ + 'component', + 'errorComponent', + 'pendingComponent', + 'notFoundComponent', +] as const diff --git a/packages/router-core/src/load-server.ts b/packages/router-core/src/load-server.ts deleted file mode 100644 index 325f8d63f7..0000000000 --- a/packages/router-core/src/load-server.ts +++ /dev/null @@ -1,964 +0,0 @@ -// 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/lru-cache.ts b/packages/router-core/src/lru-cache.ts new file mode 100644 index 0000000000..ee3ec7d7a0 --- /dev/null +++ b/packages/router-core/src/lru-cache.ts @@ -0,0 +1,74 @@ +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 b43f485236..e789e00af4 100644 --- a/packages/router-core/src/manifest.ts +++ b/packages/router-core/src/manifest.ts @@ -1,215 +1,32 @@ -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 + routes: Record< + string, + { + filePath?: string + preloads?: Array<string> + assets?: Array<RouterManagedTag> + } + > } export type RouterManagedTag = - | 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 | { - href: string - crossOrigin?: AssetCrossOrigin - [DEV_STYLES_ATTR]?: true + tag: 'title' + attrs?: Record<string, any> + children: 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 } - -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 fd63889df2..213f559f94 100644 --- a/packages/router-core/src/new-process-route-tree.ts +++ b/packages/router-core/src/new-process-route-tree.ts @@ -1,9 +1,7 @@ -import { invariant } from './invariant' -import { trimPathRight } from './path' -import { createSieveCache } from './sieve-cache' +import invariant from 'tiny-invariant' +import { createLRUCache } from './lru-cache' import { last } from './utils' -import type { SieveCache } from './sieve-cache' -import type { InterpolationSegment, RouteInterpolation } from './path' +import type { LRUCache } from './lru-cache' export const SEGMENT_TYPE_PATHNAME = 0 export const SEGMENT_TYPE_PARAM = 1 @@ -29,291 +27,431 @@ type ExtendedSegmentKind = | typeof SEGMENT_TYPE_INDEX | typeof SEGMENT_TYPE_PATHLESS -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) +function getOpenAndCloseBraces( + part: string, +): [openBrace: number, closeBrace: number] | null { + const openBrace = part.indexOf('{') + if (openBrace === -1) return null + const closeBrace = part.indexOf('}', openBrace) + if (closeBrace === -1) return null + const afterOpen = openBrace + 1 + if (afterOpen >= part.length) return null + return [openBrace, closeBrace] } -/** Parse one segment for matching and retain the same record for interpolation. */ +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 +} + +/** + * 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. + */ export function parseSegment( /** The full path string containing the segment. */ path: string, /** The starting index of the segment within the path. */ start: number, - /** The next slash, or the length of the path. */ - end: number, -): InterpolationSegment { - const part = path.slice(start, end) - if (part.charCodeAt(0) === 36) { - return part.length === 1 - ? [SEGMENT_TYPE_WILDCARD, '_splat', '', undefined] - : [SEGMENT_TYPE_PARAM, part.slice(1), '', ''] + /** 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 } - 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), - ] + + // $ (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 + 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 + } + + const braces = getOpenAndCloseBraces(part) + if (braces) { + const [openBrace, closeBrace] = braces + const firstChar = part.charCodeAt(openBrace + 1) + + // Check for {-$...} (optional param) + // prefix{-$paramName}suffix + // /^([^{]*)\{-\$([a-zA-Z_$][a-zA-Z0-9_$]*)\}([^}]*)$/ + if (firstChar === 45) { + // '-' + if ( + openBrace + 2 < part.length && + part.charCodeAt(openBrace + 2) === 36 // '$' + ) { + const paramStart = openBrace + 3 + const paramEnd = closeBrace + // Validate param name exists + if (paramStart < paramEnd) { + output[0] = SEGMENT_TYPE_OPTIONAL_PARAM + output[1] = start + openBrace + output[2] = start + paramStart + output[3] = start + paramEnd + output[4] = start + closeBrace + 1 + output[5] = end + return output as ParsedSegment + } + } + } else if (firstChar === 36) { + // '$' + const dollarPos = openBrace + 1 + const afterDollar = openBrace + 2 + // Check for {$} (wildcard) + if (afterDollar === closeBrace) { + // For wildcard, value should be '$' (from dollarPos to afterDollar) + // prefix{$}suffix + // /^([^{]*)\{\$\}([^}]*)$/ + output[0] = SEGMENT_TYPE_WILDCARD + output[1] = start + openBrace + output[2] = start + dollarPos + output[3] = start + afterDollar + output[4] = start + closeBrace + 1 + output[5] = path.length + return output as ParsedSegment + } + // Regular param {$paramName} - value is the param name (after $) + // prefix{$paramName}suffix + // /^([^{]*)\{\$([a-zA-Z_$][a-zA-Z0-9_$]*)\}([^}]*)$/ + output[0] = SEGMENT_TYPE_PARAM + output[1] = start + openBrace + output[2] = start + afterDollar + output[3] = start + closeBrace + output[4] = start + closeBrace + 1 + output[5] = end + return output as ParsedSegment } } - return part + + // 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 } -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>( +/** + * 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>( defaultCaseSensitive: boolean, + data: Uint16Array, route: TRouteLike, start: number, node: AnySegmentNode<TRouteLike>, - 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> { + depth: number, + onRoute?: (route: TRouteLike) => void, +) { + onRoute?.(route) let cursor = start - 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) + { + const path = route.fullPath ?? route.from + const length = path.length + const caseSensitive = route.options?.caseSensitive ?? defaultCaseSensitive + const skipOnParamError = !!( + route.options?.params?.parse && + route.options?.skipRouteOnParseError?.params + ) + 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 = + !skipOnParamError && + node.dynamic?.find( + (s) => + !s.skipOnParamError && + 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 = + !skipOnParamError && + node.optional?.find( + (s) => + !s.skipOnParamError && + 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 + } + + // create pathless node if ( - tail && - typeof tail !== 'string' && - tail[0 /* kind */] === SEGMENT_TYPE_WILDCARD + skipOnParamError && + route.children && + !route.isRoot && + route.id && + route.id.charCodeAt(route.id.lastIndexOf('/') + 1) === 95 /* '_' */ ) { - // 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 + const pathlessNode = createStaticNode<TRouteLike>( + route.fullPath ?? route.from, + ) + pathlessNode.kind = SEGMENT_TYPE_PATHLESS + pathlessNode.parent = node + depth++ + pathlessNode.depth = depth + node.pathless ??= [] + node.pathless.push(pathlessNode) + node = pathlessNode } - } - 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) - } - } + + const isLeaf = (route.path || !route.children) && !route.isRoot + // create index node + if (isLeaf && path.endsWith('/')) { + const indexNode = createStaticNode<TRouteLike>( + route.fullPath ?? route.from, + ) + indexNode.kind = SEGMENT_TYPE_INDEX + indexNode.parent = node + depth++ + indexNode.depth = depth + node.index = indexNode + node = indexNode } - 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! - } + node.parse = route.options?.params?.parse ?? null + node.skipOnParamError = skipOnParamError + node.parsingPriority = route.options?.skipRouteOnParseError?.priority ?? 0 - // 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) { + // make node "matchable" + if (isLeaf && !node.route) { node.route = route + node.fullPath = route.fullPath ?? route.from } } - return [node, cursor, segmentData] + if (route.children) + for (const child of route.children) { + parseSegments( + defaultCaseSensitive, + data, + child as TRouteLike, + cursor, + node, + depth, + onRoute, + ) + } } function sortDynamic( a: { - prefix: string - suffix: string + prefix?: string + suffix?: string caseSensitive: boolean - parse: null | ((params: Record<string, string>) => unknown) - priority: number + skipOnParamError: boolean + parsingPriority: number }, b: { - prefix: string - suffix: string + prefix?: string + suffix?: string caseSensitive: boolean - parse: null | ((params: Record<string, string>) => unknown) - priority: number + skipOnParamError: boolean + parsingPriority: 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.skipOnParamError && !b.skipOnParamError) return -1 + if (!a.skipOnParamError && b.skipOnParamError) return 1 + if ( + a.skipOnParamError && + b.skipOnParamError && + (a.parsingPriority || b.parsingPriority) + ) + return b.parsingPriority - a.parsingPriority 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 @@ -329,34 +467,53 @@ function sortDynamic( if (a.caseSensitive && !b.caseSensitive) return -1 if (!a.caseSensitive && b.caseSensitive) return 1 - // Equal specificity preserves route declaration order through stable sort. + // we don't need a tiebreaker here + // at this point the 2 nodes cannot conflict during matching return 0 } -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, - 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, -): SegmentNode<T> { +function sortTreeNodes(node: SegmentNode<RouteLike>) { + if (node.pathless) { + for (const child of node.pathless) { + sortTreeNodes(child) + } + } + 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, - depth: parent ? parent.depth + 1 : 0, + kind: SEGMENT_TYPE_PATHNAME, + depth: 0, pathless: null, index: null, static: null, @@ -365,10 +522,44 @@ function createSegmentNode<T extends RouteLike>( optional: null, wildcard: null, route: null, - data: undefined, - parent, + fullPath, + parent: null, parse: null, - priority: 0, + skipOnParamError: false, + parsingPriority: 0, + } +} + +/** + * 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>( + kind: + | typeof SEGMENT_TYPE_PARAM + | typeof SEGMENT_TYPE_WILDCARD + | typeof SEGMENT_TYPE_OPTIONAL_PARAM, + fullPath: string, + caseSensitive: boolean, + prefix?: string, + suffix?: string, +): DynamicSegmentNode<T> { + return { + kind, + depth: 0, + pathless: null, + index: null, + static: null, + staticInsensitive: null, + dynamic: null, + optional: null, + wildcard: null, + route: null, + fullPath, + parent: null, + parse: null, + skipOnParamError: false, + parsingPriority: 0, caseSensitive, prefix, suffix, @@ -387,8 +578,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 } @@ -398,9 +589,6 @@ type AnySegmentNode<T extends RouteLike> = type SegmentNode<T extends RouteLike> = { kind: ExtendedSegmentKind - prefix?: string - suffix?: string - caseSensitive?: boolean pathless: Array<StaticSegmentNode<T>> | null @@ -425,34 +613,38 @@ type SegmentNode<T extends RouteLike> = { /** Terminal route (if this path can end here) */ route: T | null - /** Original template data for this candidate or parse gate. */ - data: RouteInterpolation | undefined + /** The full path for this segment node (will only be valid on leaf nodes) */ + fullPath: string - parent: AnySegmentNode<T> | undefined + parent: AnySegmentNode<T> | null depth: number /** route.options.params.parse function, set on the last node of the route */ - parse: null | ((params: Record<string, string>) => unknown) + parse: null | ((params: Record<string, string>) => any) - /** route.options.params.priority ?? 0 */ - priority: number + /** options.skipRouteOnParseError.params ?? false */ + skipOnParamError: boolean + + /** options.skipRouteOnParseError.priority ?? 0 */ + parsingPriority: 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 + skipRouteOnParseError?: { + params?: boolean priority?: number } + caseSensitive?: boolean + params?: { + parse?: (params: Record<string, string>) => any + } } } & // router tree @@ -471,11 +663,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: SieveCache<string, AnySegmentNode<TSingle>> + singleCache: LRUCache<string, AnySegmentNode<TSingle>> /** a cache of route matches from the `segmentTree` */ - matchCache: SieveCache<string, RouteMatch<TTree> | null> + matchCache: LRUCache<string, RouteMatch<TTree> | null> /** a cache of route matches from the `masksTree` */ - flatCache: SieveCache<string, ReturnType<typeof findMatch<TFlat>>> | null + flatCache: LRUCache<string, ReturnType<typeof findMatch<TFlat>>> | null } export function processRouteMasks< @@ -484,36 +676,14 @@ export function processRouteMasks< routeList: Array<TRouteLike>, processedTree: ProcessedTree<any, TRouteLike, any>, ) { - 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) - } - } - } + const segmentTree = createStaticNode<TRouteLike>('/') + const data = new Uint16Array(6) for (const route of routeList) { - visit(route, 1, segmentTree) - } - for (const nodes of dynamicListsToSort) { - nodes.sort(sortDynamic) + parseSegments(false, data, route, 1, segmentTree, 0) } + sortTreeNodes(segmentTree) processedTree.masksTree = segmentTree - processedTree.flatCache = createSieveCache< + processedTree.flatCache = createLRUCache< string, ReturnType<typeof findMatch<TRouteLike>> >(1000) @@ -530,7 +700,7 @@ export function findFlatMatch<T extends Extract<RouteLike, { from: string }>>( ) { path ||= '/' const cached = processedTree.flatCache!.get(path) - if (cached !== undefined) return cached + if (cached) return cached const result = findMatch(path, processedTree.masksTree!) processedTree.flatCache!.set(path, result) return result @@ -553,8 +723,9 @@ 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 = createSegmentNode<{ from: string }>() - parseSegments(caseSensitive, { from }, 1, tree) + tree = createStaticNode<{ from: string }>('/') + const data = new Uint16Array(6) + parseSegments(caseSensitive, data, { from }, 1, tree, 0) processedTree.singleCache.set(key, tree) } return findMatch(path, tree, fuzzy) @@ -563,6 +734,7 @@ export function findSingleMatch( type RouteMatch<T extends Extract<RouteLike, { fullPath: string }>> = { route: T rawParams: Record<string, string> + parsedParams?: Record<string, unknown> branch: ReadonlyArray<T> } @@ -601,6 +773,11 @@ export function findRouteMatch< 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 }, > { @@ -617,71 +794,44 @@ export interface ProcessRouteTreeResult< * Also builds lookup maps for routes by ID and by trimmed full path. */ export function processRouteTree< - TRouteLike extends Extract<RouteLike, { fullPath: string }> & { - id: string - init: (originalIndex: number) => void - }, + TRouteLike extends Extract<RouteLike, { fullPath: string }> & { id: string }, >( /** 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, ): ProcessRouteTreeResult<TRouteLike> { - const segmentTree = createSegmentNode<TRouteLike>() - const dynamicListsToSort: Array<Array<DynamicSegmentNode<TRouteLike>>> = [] + const segmentTree = createStaticNode<TRouteLike>(routeTree.fullPath) + const data = new Uint16Array(6) const routesById = {} as Record<string, TRouteLike> const routesByPath = {} as Record<string, TRouteLike> let index = 0 - function visit( - route: TRouteLike, - start: number, - parentNode: AnySegmentNode<TRouteLike>, - parentInterpolation?: RouteInterpolation, - ) { - route.init(index) + parseSegments(caseSensitive, data, routeTree, 1, segmentTree, 0, (route) => { + initRoute?.(route, index) - 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() - } + invariant( + !(route.id in routesById), + `Duplicate routes found with id: ${String(route.id)}`, + ) routesById[route.id] = route + if (index !== 0 && route.path) { const trimmedFullPath = trimPathRight(route.fullPath) if (!routesByPath[trimmedFullPath] || route.fullPath.endsWith('/')) { routesByPath[trimmedFullPath] = route } } - index++ - 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) - } + index++ + }) + sortTreeNodes(segmentTree) const processedTree: ProcessedTree<TRouteLike, any, any> = { segmentTree, - singleCache: createSieveCache<string, AnySegmentNode<any>>(1000), - matchCache: createSieveCache<string, RouteMatch<TRouteLike> | null>(1000), + singleCache: createLRUCache<string, AnySegmentNode<any>>(1000), + matchCache: createLRUCache<string, RouteMatch<TRouteLike> | null>(1000), flatCache: null, masksTree: null, } @@ -703,6 +853,11 @@ function findMatch<T extends RouteLike>( * This will be the exhaustive list of all params defined in the route's path. */ rawParams: Record<string, string> + /** + * The accumlulated parsed params of each route in the branch that had `skipRouteOnParseError` enabled. + * Will not contain all params defined in the route's path. Those w/ a `params.parse` but no `skipRouteOnParseError` will need to be parsed separately. + */ + parsedParams?: Record<string, unknown> } | null { const parts = path.split('/') const leaf = getNodeMatch(path, parts, segmentTree, fuzzy) @@ -711,6 +866,7 @@ function findMatch<T extends RouteLike>( return { route: leaf.node.route!, rawParams, + parsedParams: leaf.parsedParams, } } @@ -718,7 +874,7 @@ type ParamExtractionState = { part: number node: number path: number - param: number + segment: number } /** @@ -739,7 +895,7 @@ function extractParams<T extends RouteLike>( }, ): [rawParams: Record<string, string>, state: ParamExtractionState] { const list = buildBranch(leaf.node) - const names = leaf.node.data && getParamNames(leaf.node.data) + let nodeParts: Array<string> | null = null const rawParams: Record<string, string> = Object.create(null) /** which segment of the path we're currently processing */ let partIndex = leaf.extract?.part ?? 0 @@ -747,14 +903,19 @@ function extractParams<T extends RouteLike>( 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++) { + /** which fullPath segment we're currently processing */ + let segmentCount = leaf.extract?.segment ?? 0 + for ( + ; + nodeIndex < list.length; + partIndex++, nodeIndex++, pathIndex++, segmentCount++ + ) { 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) { + segmentCount-- partIndex-- pathIndex-- continue @@ -762,34 +923,49 @@ function extractParams<T extends RouteLike>( const part = parts[partIndex] const currentPathIndex = pathIndex if (part) pathIndex += part.length - 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) - ) { + if (node.kind === SEGMENT_TYPE_PARAM) { + nodeParts ??= leaf.node.fullPath.split('/') + const nodePart = nodeParts[segmentCount]! + 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) + rawParams[name] = decodeURIComponent(value) + } else { + const name = nodePart.substring(1) + rawParams[name] = decodeURIComponent(part!) + } + } else if (node.kind === SEGMENT_TYPE_OPTIONAL_PARAM) { + if (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[segmentCount]! + 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( - node.prefix.length, - part!.length - node.suffix.length, - ) - : part! - if (value || node.kind === SEGMENT_TYPE_PARAM) { - rawParams[name] = decodeURIComponent(value) - } + ? part!.substring(preLength, part!.length - sufLength) + : part + if (value) rawParams[name] = decodeURIComponent(value) } else if (node.kind === SEGMENT_TYPE_WILDCARD) { const n = node const value = path.substring( - currentPathIndex + n.prefix.length, - path.length - n.suffix.length, + currentPathIndex + (n.prefix?.length ?? 0), + path.length - (n.suffix?.length ?? 0), ) const splat = decodeURIComponent(value) // TODO: Deprecate * @@ -805,12 +981,12 @@ function extractParams<T extends RouteLike>( part: partIndex, node: nodeIndex, path: pathIndex, - param: paramIndex, + segment: segmentCount, }, ] } -export function buildRouteBranch<T extends RouteLike>(route: T) { +function buildRouteBranch<T extends RouteLike>(route: T) { const list = [route] while (route.parentRoute) { route = route.parentRoute as T @@ -833,6 +1009,8 @@ 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. * @@ -840,7 +1018,6 @@ 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 @@ -848,6 +1025,7 @@ type MatchStackFrame<T extends RouteLike> = { extract?: ParamExtractionState /** intermediary params from param extraction */ rawParams?: Record<string, string> + parsedParams?: Record<string, unknown> } function getNodeMatch<T extends RouteLike>( @@ -861,7 +1039,7 @@ function getNodeMatch<T extends RouteLike>( if (path === '/' && segmentTree.index) return { node: segmentTree.index, skipped: 0 } as Pick< Frame, - 'node' | 'skipped' + 'node' | 'skipped' | 'parsedParams' > const trailingSlash = !last(parts) @@ -882,37 +1060,28 @@ function getNodeMatch<T extends RouteLike>( node: segmentTree, index: 1, skipped: 0, - statics: 0, + depth: 1, + statics: 1, 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()! - const { node, index, skipped, statics, dynamics, optionals } = frame - let { extract, rawParams } = frame + const { node, index, skipped, depth, statics, dynamics, optionals } = frame + let { extract, rawParams, parsedParams } = 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 (node.skipOnParamError) { + const result = validateMatchParams(path, parts, frame) if (!result) continue rawParams = frame.rawParams extract = frame.extract + parsedParams = frame.parsedParams } // In fuzzy mode, track the best partial match we've found so far @@ -927,13 +1096,7 @@ function getNodeMatch<T extends RouteLike>( const isBeyondPath = index === partsLength if (isBeyondPath) { - if ( - node.route && - (!pathIsIndex || - node.kind === SEGMENT_TYPE_INDEX || - node.kind === SEGMENT_TYPE_WILDCARD) && - isFrameMoreSpecific(bestMatch, frame) - ) { + if (node.route && !pathIsIndex && isFrameMoreSpecific(bestMatch, frame)) { bestMatch = frame } // beyond the length of the path parts, only some segment types can match @@ -950,26 +1113,23 @@ function getNodeMatch<T extends RouteLike>( node: node.index, index, skipped, + depth: depth + 1, statics, dynamics, optionals, extract, rawParams, + parsedParams, } let indexValid = true - if (node.index.parse) { - const result = validateParseParams(path, parts, indexFrame) + if (node.index.skipOnParamError) { + const result = validateMatchParams(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) - ) { + if (statics === partsLength && !dynamics && !optionals && !skipped) { return indexFrame } if (isFrameMoreSpecific(bestMatch, indexFrame)) { @@ -980,9 +1140,8 @@ function getNodeMatch<T extends RouteLike>( } // 5. Try wildcard match - if (node.wildcard) { - for (let i = node.wildcard.length - 1; i >= 0; i--) { - const segment = node.wildcard[i]! + if (node.wildcard && isFrameMoreSpecific(wildcardMatch, frame)) { + for (const segment of node.wildcard) { const { prefix, suffix } = segment if (prefix) { if (isBeyondPath) continue @@ -993,48 +1152,51 @@ function getNodeMatch<T extends RouteLike>( } if (suffix) { if (isBeyondPath) 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 - } + const end = parts.slice(index).join('/').slice(-suffix.length) + const casePart = segment.caseSensitive ? end : end.toLowerCase() + if (casePart !== suffix) continue } - // wildcard matches consume the rest of the URL and cannot have children - stack.push({ + // the first wildcard match is the highest priority one + // wildcard matches skip the stack because they cannot have children + const frame = { node: segment, index: partsLength, skipped, + depth, statics, dynamics, optionals, extract, rawParams, - }) + parsedParams, + } + if (segment.skipOnParamError) { + const result = validateMatchParams(path, parts, frame) + if (!result) continue + } + wildcardMatch = frame + break } } // 4. Try optional match if (node.optional) { - // A skipped optional is keyed by the child node's trie depth. - const nextSkipped = skipped | (1 << (node.depth + 1)) + const nextSkipped = skipped | (1 << depth) + const nextDepth = depth + 1 for (let i = node.optional.length - 1; i >= 0; i--) { const segment = node.optional[i]! - // when skipping, the node advances by 1, but the index doesn't + // when skipping, node and depth advance by 1, but index doesn't stack.push({ node: segment, index, skipped: nextSkipped, + depth: nextDepth, statics, dynamics, optionals, extract, rawParams, + parsedParams, }) // enqueue skipping the optional } if (!isBeyondPath) { @@ -1046,23 +1208,19 @@ function getNodeMatch<T extends RouteLike>( ? part! : (lowerPart ??= part!.toLowerCase()) if (prefix && !casePart.startsWith(prefix)) continue - if ( - suffix && - casePart.indexOf(suffix, casePart.length - suffix.length) < - prefix.length - ) { - continue - } + if (suffix && !casePart.endsWith(suffix)) continue } stack.push({ node: segment, index: index + 1, skipped, + depth: nextDepth, statics, dynamics, - optionals: optionals + segmentScore(partsLength, index), + optionals: optionals + 1, extract, rawParams, + parsedParams, }) } } @@ -1078,23 +1236,19 @@ function getNodeMatch<T extends RouteLike>( ? part : (lowerPart ??= part.toLowerCase()) if (prefix && !casePart.startsWith(prefix)) continue - if ( - suffix && - casePart.indexOf(suffix, casePart.length - suffix.length) < - prefix.length - ) { - continue - } + if (suffix && !casePart.endsWith(suffix)) continue } stack.push({ node: segment, index: index + 1, skipped, + depth: depth + 1, statics, - dynamics: dynamics + segmentScore(partsLength, index), + dynamics: dynamics + 1, optionals, extract, rawParams, + parsedParams, }) } } @@ -1109,11 +1263,13 @@ function getNodeMatch<T extends RouteLike>( node: match, index: index + 1, skipped, - statics: statics + segmentScore(partsLength, index), + depth: depth + 1, + statics: statics + 1, dynamics, optionals, extract, rawParams, + parsedParams, }) } } @@ -1126,35 +1282,48 @@ function getNodeMatch<T extends RouteLike>( node: match, index: index + 1, skipped, - statics: statics + segmentScore(partsLength, index), + depth: depth + 1, + statics: statics + 1, dynamics, optionals, extract, rawParams, + parsedParams, }) } } // 0. Try pathless match if (node.pathless) { + const nextDepth = depth + 1 for (let i = node.pathless.length - 1; i >= 0; i--) { const segment = node.pathless[i]! stack.push({ node: segment, index, skipped, + depth: nextDepth, statics, dynamics, optionals, extract, rawParams, + parsedParams, }) } } } + 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++) { @@ -1169,46 +1338,25 @@ function getNodeMatch<T extends RouteLike>( 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>( +function validateMatchParams<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) + const [rawParams, state] = extractParams(path, parts, frame) + frame.rawParams = rawParams + frame.extract = state + const parsed = frame.node.parse!(rawParams) + frame.parsedParams = Object.assign( + Object.create(null), + frame.parsedParams, + parsed, + ) + return true } 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( @@ -1229,6 +1377,6 @@ function isFrameMoreSpecific( (prev.node.kind === SEGMENT_TYPE_INDEX) || ((next.node.kind === SEGMENT_TYPE_INDEX) === (prev.node.kind === SEGMENT_TYPE_INDEX) && - next.node.depth > prev.node.depth))))))) + next.depth > prev.depth))))))) ) } diff --git a/packages/router-core/src/not-found.ts b/packages/router-core/src/not-found.ts index ddf8f0a259..0681b82054 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 === true + return !!obj?.isNotFound } diff --git a/packages/router-core/src/path.ts b/packages/router-core/src/path.ts index 1b6288dc36..70709e6045 100644 --- a/packages/router-core/src/path.ts +++ b/packages/router-core/src/path.ts @@ -1,12 +1,13 @@ +import { isServer } from '@tanstack/router-core/isServer' 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 { SieveCache } from './sieve-cache' -import type { DynamicPathSegment } from './new-process-route-tree' -import type { AnyRoute } from './route' +import type { LRUCache } from './lru-cache' /** Join path segments, cleaning duplicate slashes between parts. */ export function joinPaths(paths: Array<string | undefined>) { @@ -27,13 +28,13 @@ export function cleanPath(path: string) { /** Trim leading slashes (except preserving root '/'). */ export function trimPathLeft(path: string) { - return path === '/' ? path : path.replace(/^\/+/, '') + return path === '/' ? path : path.replace(/^\/{1,}/, '') } /** Trim trailing slashes (except preserving root '/'). */ export function trimPathRight(path: string) { const len = path.length - return len > 1 && path[len - 1] === '/' ? path.replace(/\/+$/, '') : path + return len > 1 && path[len - 1] === '/' ? path.replace(/\/{1,}$/, '') : path } /** Trim both leading and trailing slashes. */ @@ -94,38 +95,30 @@ 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: string, - to: string, - trailingSlash: 'always' | 'never' | 'preserve' = 'never', - cache?: SieveCache<string, string>, -) { - if (to.includes('//')) { - to = cleanPath(to) - } +export function resolvePath({ + base, + to, + trailingSlash = 'never', + cache, +}: ResolvePathOptions) { + const isAbsolute = to.startsWith('/') + const isBase = !isAbsolute && 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 = isBase ? base : base + '\0' + to + key = isAbsolute ? to : isBase ? base : base + '\0' + to const cached = cache.get(key) if (cached) return cached } @@ -133,10 +126,9 @@ 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() @@ -156,11 +148,7 @@ export function resolvePath( // ignore inter-slashes } } else if (value === '..') { - if (baseSegments.length > 1) { - baseSegments.pop() - } else { - baseSegments = [''] - } + baseSegments.pop() } else if (value === '.') { // ignore } else { @@ -179,15 +167,40 @@ export function resolvePath( } } - const joined = baseSegments.join('/') - const result = (isBase ? cleanPath(joined) : joined) || '/' + 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 || '/' if (key && cache) cache.set(key, result) return result } /** * Create a pre-compiled decode config from allowed characters. - * Created once for the router's fixed encoding configuration. + * This should be called once at router initialization. */ export function compileDecodeCharMap( pathParamsAllowedCharacters: ReadonlyArray<string>, @@ -195,112 +208,229 @@ export function compileDecodeCharMap( 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', - ) + // Escape special regex characters and join with | + const pattern = Array.from(charMap.keys()) + .map((key) => key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')) + .join('|') + const regex = new RegExp(pattern, 'g') return (encoded: string) => encoded.replace(regex, (match) => charMap.get(match) ?? match) } -export type InterpolationSegment = string | DynamicPathSegment - -export type RouteInterpolation = Array<InterpolationSegment> & { - names?: Array<string> +interface InterpolatePathOptions { + path?: string + params: Record<string, unknown> + /** + * A function that decodes a path parameter value. + * Obtained from `compileDecodeCharMap(pathParamsAllowedCharacters)`. + */ + decoder?: (encoded: string) => string + /** + * @internal + * For testing only, in development mode we use the router.isServer value + */ + server?: boolean } -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) - }) +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 } function encodeParam( key: string, - value: unknown, - decoder: ((encoded: string) => string) | undefined, -): string { - if (typeof value !== 'string') { - return '' + (value ?? undefined) - } + params: InterpolatePathOptions['params'], + decoder: InterpolatePathOptions['decoder'], +): any { + const value = params[key] + if (typeof value !== 'string') return value - const splat = key === '_splat' - // Early return if the splat contains only URL-safe characters. - if (splat && (!value || /^[a-zA-Z0-9\-._~!/]*$/.test(value))) { + if (key === '_splat') { + // Early return if value only contains URL-safe characters (performance optimization) + if (/^[a-zA-Z0-9\-._~!/]*$/.test(value)) return value + // the splat/catch-all routes shouldn't have the '/' encoded out + // Use encodeURIComponent for each segment to properly encode spaces, + // plus signs, and other special characters that encodeURI leaves unencoded return value + .split('/') + .map((segment) => encodePathParam(segment, decoder)) + .join('/') + } else { + return encodePathParam(value, decoder) } - 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 } -/** 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 = '' - for (const part of segments) { - if (typeof part === 'string') { - joined += part - continue - } - 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 * - if (splat) { - usedParams['*'] = paramValue +/** + * 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, + decoder, + // `server` is marked @internal and stripped from .d.ts by `stripInternal`. + // We avoid destructuring it in the function signature so the emitted + // declaration doesn't reference a property that no longer exists. + ...rest +}: InterpolatePathOptions): InterPolatePathResult { + // Tracking if any params are missing in the `params` object + // when interpolating the path + let isMissingParams = false + const usedParams: Record<string, unknown> = Object.create(null) + + if (!path || path === '/') + return { interpolatedPath: '/', usedParams, isMissingParams } + if (!path.includes('$')) + return { interpolatedPath: path, usedParams, isMissingParams } + + if (isServer ?? rest.server) { + // Fast path for common templates like `/posts/$id` or `/files/$`. + // Braced segments (`{...}`) are more complex (prefix/suffix/optional) and are + // handled by the general parser below. + if (path.indexOf('{') === -1) { + const length = path.length + let cursor = 0 + let joined = '' + + while (cursor < length) { + // Skip slashes between segments. '/' code is 47 + while (cursor < length && path.charCodeAt(cursor) === 47) cursor++ + if (cursor >= length) break + + const start = cursor + let end = path.indexOf('/', cursor) + if (end === -1) end = length + cursor = end + + const part = path.substring(start, end) + if (!part) continue + + // `$id` or `$` (splat). '$' code is 36 + if (part.charCodeAt(0) === 36) { + if (part.length === 1) { + const splat = params._splat + usedParams._splat = splat + // TODO: Deprecate * + usedParams['*'] = splat + + if (!splat) { + isMissingParams = true + continue + } + + const value = encodeParam('_splat', params, decoder) + joined += '/' + value + } else { + const key = part.substring(1) + if (!isMissingParams && !(key in params)) { + isMissingParams = true + } + usedParams[key] = params[key] + + const value = encodeParam(key, params, decoder) ?? 'undefined' + joined += '/' + value + } + } else { + joined += '/' + part + } } + + if (path.endsWith('/')) joined += '/' + + const interpolatedPath = joined || '/' + return { usedParams, interpolatedPath, isMissingParams } } - if (splat && isMissingSplat(paramValue)) { - // A missing wildcard keeps its affixes, but omits a bare segment. - if (prefix === '/' && !suffix) { + } + + const length = path.length + let cursor = 0 + let segment + 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) + continue + } + + if (kind === SEGMENT_TYPE_WILDCARD) { + const splat = params._splat + usedParams._splat = splat + // 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 + } continue } - paramValue = '' + + const value = encodeParam('_splat', params, decoder) + joined += '/' + prefix + value + suffix + continue } - joined += prefix + encodeParam(key, paramValue, decoder) + (suffix || '') + 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, decoder) ?? '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, decoder) ?? '' + joined += '/' + prefix + value + suffix + continue + } } - return joined + trailingSlash || '/' + if (path.endsWith('/')) joined += '/' + + const interpolatedPath = joined || '/' + + return { usedParams, interpolatedPath, isMissingParams } +} + +function encodePathParam( + value: string, + decoder?: InterpolatePathOptions['decoder'], +) { + const encoded = encodeURIComponent(value) + return decoder?.(encoded) ?? encoded } diff --git a/packages/router-core/src/qss.ts b/packages/router-core/src/qss.ts index 2a4125fdad..a52fd958a1 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 { - let result: URLSearchParams | undefined + const result = new URLSearchParams() for (const key in obj) { const val = obj[key] if (val !== undefined) { - ;(result ||= new URLSearchParams()).set(key, stringify(val)) + result.set(key, stringify(val)) } } - return result ? result.toString() : '' + return result.toString() } /** diff --git a/packages/router-core/src/redirect.ts b/packages/router-core/src/redirect.ts index dc6551d174..b10fac6d7a 100644 --- a/packages/router-core/src/redirect.ts +++ b/packages/router-core/src/redirect.ts @@ -1,5 +1,6 @@ import type { NavigateOptions } from './link' import type { AnyRouter, RegisteredRouter } from './router' +import type { ParsedLocation } from './location' export type AnyRedirect = Redirect<any, any, any, any, any> @@ -13,7 +14,14 @@ export type Redirect< TMaskFrom extends string = TFrom, TMaskTo extends string = '.', > = Response & { - options: NavigateOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> + options: NavigateOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> & { + /** + * @internal + * A **trusted** built location that can be used to redirect to. + */ + _builtLocation?: ParsedLocation + } + redirectHandled?: boolean } export type RedirectOptions< @@ -43,6 +51,11 @@ export type RedirectOptions< * @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RedirectType#headers-property) */ headers?: HeadersInit + /** + * @internal + * A **trusted** built location that can be used to redirect to. + */ + _builtLocation?: ParsedLocation } & NavigateOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> export type ResolvedRedirect< @@ -87,11 +100,11 @@ export interface RedirectFnRoute<in out TDefaultFrom extends string = string> { * * Use from route `loader`/`beforeLoad` or server functions to trigger a * navigation. If `throw: true` is set, the redirect is thrown instead of - * returned. External `href` values are classified as full-document - * navigations when the router resolves the redirect. + * returned. When an absolute `href` is supplied and `reloadDocument` is not + * set, a full-document navigation is inferred. * * @param opts Options for the redirect. Common fields: - * - `href`: absolute URL for external redirects. + * - `href`: absolute URL for external redirects; infers `reloadDocument`. * - `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`, @@ -110,6 +123,17 @@ export function redirect< ): Redirect<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> { opts.statusCode = opts.statusCode || opts.code || 307 + if ( + !opts._builtLocation && + !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) @@ -130,11 +154,13 @@ 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, @@ -142,6 +168,7 @@ 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 901880104e..0da50c5b62 100644 --- a/packages/router-core/src/rewrite.ts +++ b/packages/router-core/src/rewrite.ts @@ -1,6 +1,7 @@ -import { cleanPath, trimPath } from './path' +import { joinPaths, 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 { @@ -20,21 +21,26 @@ export function composeRewrites(rewrites: Array<LocationRewrite>) { } /** Create a rewrite pair that strips/adds a basepath on input/output. */ -export function rewriteBasepath( - basepath: string, - caseSensitive?: boolean, - rewrite?: LocationRewrite, -) { - const trimmedBasepath = trimPath(basepath) +/** 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) const normalizedBasepath = `/${trimmedBasepath}` - const checkBasepath = caseSensitive + const normalizedBasepathWithSlash = `${normalizedBasepath}/` + const checkBasepath = opts.caseSensitive ? normalizedBasepath : normalizedBasepath.toLowerCase() - const checkBasepathWithSlash = `${checkBasepath}/` + const checkBasepathWithSlash = opts.caseSensitive + ? normalizedBasepathWithSlash + : normalizedBasepathWithSlash.toLowerCase() - const basepathRewrite = { + return { input: ({ url }) => { - const pathname = caseSensitive ? url.pathname : url.pathname.toLowerCase() + const pathname = opts.caseSensitive + ? url.pathname + : url.pathname.toLowerCase() // Handle exact basepath match (e.g., /my-app -> /) if (pathname === checkBasepath) { @@ -46,24 +52,13 @@ export function rewriteBasepath( return url }, output: ({ url }) => { - // `url.pathname` always starts with "/", so only slashes already inside - // it can repeat; cleanPath keeps the joinPaths normalization. - url.pathname = cleanPath(`/${trimmedBasepath}${url.pathname}`) + url.pathname = joinPaths(['/', 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, @@ -80,6 +75,7 @@ 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 089369b454..ef80228c8b 100644 --- a/packages/router-core/src/route.ts +++ b/packages/router-core/src/route.ts @@ -1,10 +1,9 @@ -import { invariant } from './invariant' -import { cleanPath, trimPathLeft, trimPathRight } from './path' +import invariant from 'tiny-invariant' +import { joinPaths, 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' @@ -56,7 +55,7 @@ export type AnyContext = {} export interface RouteContext {} -export type PreloadableObj = { preload?: () => Promise<void> | undefined } +export type PreloadableObj = { preload?: () => Promise<void> } export type RoutePathOptions<TCustomId, TPath> = | { @@ -75,17 +74,9 @@ 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> = ( @@ -182,13 +173,9 @@ export type ResolveParams< export type ParseParamsFn<in out TPath extends string, in out TParams> = ( rawParams: Expand<ResolveParams<TPath>>, -) => TParams | false - -type ValidateParsedParams<TPath extends string, TParams> = [TParams] extends [ - ResolveParams<TPath, any>, -] - ? unknown - : never +) => TParams extends ResolveParams<TPath, any> + ? TParams + : ResolveParams<TPath, any> export type StringifyParamsFn<in out TPath extends string, in out TParams> = ( params: TParams, @@ -196,22 +183,14 @@ 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> & ValidateParsedParams<TPath, TParams> - /** - * When multiple route candidates use `params.parse` during matching, - * higher priorities are tried first. - * - * @default 0 - */ - priority?: number + parse?: ParseParamsFn<TPath, TParams> stringify?: StringifyParamsFn<TPath, TParams> } /** @deprecated Use params.parse instead */ - parseParams?: ParseParamsFn<TPath, TParams> & - ValidateParsedParams<TPath, TParams> + parseParams?: ParseParamsFn<TPath, TParams> /** @deprecated Use params.stringify instead @@ -701,6 +680,10 @@ export interface Route< THandlers > isRoot: TParentRoute extends AnyRoute ? true : false + /** @internal */ + _componentsPromise?: Promise<void> + /** @internal */ + _componentsLoaded?: boolean lazyFn?: () => Promise< LazyRoute< Route< @@ -726,14 +709,12 @@ export interface Route< > > /** @internal */ - _lazy?: Promise<void> | true + _lazyPromise?: Promise<void> /** @internal */ - _branch?: ReadonlyArray<AnyRoute> - /** @internal */ - _interpolation?: RouteInterpolation + _lazyLoaded?: boolean rank: number to: TrimPathRight<TFullPath> - init: (originalIndex: number) => void + init: (opts: { originalIndex: number }) => void update: ( options: UpdatableRouteOptions< TParentRoute, @@ -1267,6 +1248,37 @@ export interface UpdatableRouteOptions< in out TBeforeLoadFn, > extends UpdatableStaticRouteOption, UpdatableRouteOptionsExtensions { + /** + * Options to control route matching behavior with runtime code. + * + * @experimental 🚧 this feature is subject to change + * + * @link https://tanstack.com/router/latest/docs/framework/react/api/router/RouteOptionsType + */ + skipRouteOnParseError?: { + /** + * If `true`, skip this route during matching if `params.parse` fails. + * + * Without this option, a `/$param` route could match *any* value for `param`, + * and only later during the route lifecycle would `params.parse` run and potentially + * show the `errorComponent` if validation failed. + * + * With this option enabled, the route will only match if `params.parse` succeeds. + * If it fails, the router will continue trying to match other routes, potentially + * finding a different route that works, or ultimately showing the `notFoundComponent`. + * + * @default false + */ + params?: boolean + /** + * In cases where multiple routes would need to run `params.parse` during matching + * to determine which route to pick, this priority number can be used as a tie-breaker + * for which route to try first. Higher number = higher priority. + * + * @default 0 + */ + priority?: number + } /** * If true, this route will be matched as case-sensitive * @@ -1288,7 +1300,9 @@ export interface UpdatableRouteOptions< preloadGcTime?: number search?: { middlewares?: Array< - SearchMiddleware<ResolveFullSearchSchema<TParentRoute, TSearchValidator>> + SearchMiddleware< + ResolveFullSearchSchemaInput<TParentRoute, TSearchValidator> + > > } /** @@ -1303,7 +1317,7 @@ export interface UpdatableRouteOptions< postSearchFilters?: Array< SearchFilter<ResolveFullSearchSchema<TParentRoute, TSearchValidator>> > - onCatch?: (error: ErrorBoundaryTypes['error']) => void + onCatch?: (error: Error) => void onError?: (err: any) => void // These functions are called as route matches are loaded, stick around and leave the active // matches @@ -1606,14 +1620,7 @@ export type ErrorRouteProps = { reset: () => void } -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']> = { +export type ErrorComponentProps<TError = Error> = { error: TError info?: { componentStack: string } reset: () => void @@ -1717,11 +1724,10 @@ export class BaseRoute< > > /** @internal */ - _lazy?: Promise<void> | true + _lazyPromise?: Promise<void> /** @internal */ - _branch?: ReadonlyArray<AnyRoute> - /** @internal */ - _interpolation?: RouteInterpolation + _componentsPromise?: Promise<void> + constructor( options?: RouteOptions< TRegister, @@ -1771,10 +1777,8 @@ export class BaseRoute< THandlers > - init = (originalIndex: number): void => { - this.originalIndex = originalIndex - // Rebuilding a tree can change the ancestors of an existing route. - this._branch = undefined + init = (opts: { originalIndex: number }): void => { + this.originalIndex = opts.originalIndex const options = this.options as | (RouteOptions< @@ -1804,13 +1808,10 @@ export class BaseRoute< if (isRoot) { this._path = rootRouteId as TPath } else if (!this.parentRoute) { - 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() + invariant( + false, + `Child Route instances must pass a 'getParentRoute: () => ParentRoute' option that returns a Route instance.`, + ) } let path: undefined | string = isRoot ? rootRouteId : options?.path @@ -1823,24 +1824,23 @@ export class BaseRoute< const customId = options?.id || path // Strip the parentId prefix from the first level of children - const id = isRoot + let id = isRoot ? rootRouteId - : cleanPath( - (this.parentRoute.id === rootRouteId ? '' : this.parentRoute.id) + - '/' + - (customId ?? ''), - ) + : joinPaths([ + this.parentRoute.id === rootRouteId ? '' : this.parentRoute.id, + customId, + ]) if (path === rootRouteId) { path = '/' } + if (id !== rootRouteId) { + id = joinPaths(['/', id]) + } + const fullPath = - id === rootRouteId - ? '/' - : path === undefined - ? this.parentRoute.fullPath - : cleanPath(this.parentRoute.fullPath + '/' + path) + id === rootRouteId ? '/' : joinPaths([this.parentRoute.fullPath, path]) this._path = path as TPath this._id = id as TId diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index ecf443168d..965fefda33 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -1,63 +1,48 @@ -import { - createBrowserHistory, - normalizeProtocolRelative, - parseHref, -} from '@tanstack/history' -import { isServer, loadServerRoute } from '@tanstack/router-core/isServer' +import { createBrowserHistory, parseHref } from '@tanstack/history' +import { isServer } from '@tanstack/router-core/isServer' import { DEFAULT_PROTOCOL_ALLOWLIST, - createNull, + createControlledPromise, 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 { createSieveCache } from './sieve-cache' +import { createLRUCache } from './lru-cache' import { isNotFound } from './not-found' import { setupScrollRestoration } from './scroll-restoration' import { defaultParseSearch, defaultStringifySearch } from './searchParams' import { rootRouteId } from './root' -import { isRedirect } from './redirect' -import { - loadClientRoute, - loadRouteChunk, - preloadClientRoute, - refreshClientRoute, - replaceRouteChunk, -} from './load-client' +import { isRedirect, redirect } from './redirect' +import { loadMatches, loadRouteChunk, routeNeedsPreload } from './load-matches' import { + composeRewrites, executeRewriteInput, executeRewriteOutput, rewriteBasepath, } from './rewrite' import { createRouterStores } from './stores' -import type { SieveCache } from './sieve-cache' -import type { RouteInterpolation } from './path' +import type { LRUCache } from './lru-cache' import type { ProcessRouteTreeResult, ProcessedTree, @@ -65,13 +50,6 @@ import type { 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, @@ -81,6 +59,7 @@ import type { import type { Awaitable, Constrain, + ControlledPromise, NoInfer, NonNullableUpdater, PickAsRequired, @@ -93,9 +72,10 @@ import type { AnyRouteWithContext, LoaderStaleReloadMode, MakeRemountDepsOptionsUnion, + RouteContextOptions, + RouteLike, RouteMask, SearchMiddleware, - SearchMiddlewareMeta, } from './route' import type { FullSearchSchema, @@ -115,37 +95,23 @@ import type { CommitLocationOptions, NavigateFn, } from './RouterProvider' -import type { Manifest, ManifestRouteAssets } from './manifest' +import type { Manifest, RouterManagedTag } 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 { - 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 @@ -232,8 +198,7 @@ export interface RouterOptions< */ defaultPreload?: false | 'intent' | 'viewport' | 'render' /** - * The delay in milliseconds before intent focus/hover and viewport preloading. - * Touch intent preloads immediately. + * The delay in milliseconds that a route must be hovered over or touched before it is preloaded. * * @default 50 * @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultpreloaddelay-property) @@ -290,9 +255,9 @@ export interface RouterOptions< */ defaultPreloadStaleTime?: number /** - * The default `preloadGcTime` a route should use if none is provided. + * The default `defaultPreloadGcTime` a route should use if no preloadGcTime is provided. * - * @default 300_000 `(5 minutes)` + * @default 1_800_000 `(30 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) */ @@ -324,7 +289,7 @@ export interface RouterOptions< /** * The default `gcTime` a route should use if no gcTime is provided. * - * @default 300_000 `(5 minutes)` + * @default 1_800_000 `(30 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) */ @@ -373,8 +338,9 @@ 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?: () => Awaitable< - Constrain<TDehydrated, ValidateSerializableInput<Register, TDehydrated>> + dehydrate?: () => Constrain< + TDehydrated, + ValidateSerializableInput<Register, TDehydrated> > /** * A function that will be called when the router is hydrated. @@ -466,12 +432,11 @@ 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) */ - readonly pathParamsAllowedCharacters?: ReadonlyArray< + pathParamsAllowedCharacters?: Array< ';' | ':' | '@' | '&' | '=' | '+' | '$' | ',' > @@ -534,11 +499,6 @@ 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 @@ -577,10 +537,14 @@ export interface RouterState< in out TRouteMatch = MakeRouteMatchUnion, > { status: 'pending' | 'idle' + loadedAt: number isLoading: boolean + isTransitioning: boolean matches: Array<TRouteMatch> location: ParsedLocation<FullSearchSchema<TRouteTree>> resolvedLocation?: ParsedLocation<FullSearchSchema<TRouteTree>> + statusCode: number + redirect?: AnyRedirect } export interface BuildNextOptions { @@ -648,21 +612,9 @@ export type SubscribeFn = <TType extends keyof RouterEvents>( ) => () => void export interface MatchRoutesOpts { + preload?: boolean throwOnError?: boolean - /** @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 - ) + dest?: BuildNextOptions } export type InferRouterContext<TRouteTree extends AnyRoute> = @@ -700,7 +652,6 @@ 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, @@ -712,14 +663,19 @@ export type PreloadRouteFn< TRouteTree, TTrailingSlashOption, TDefaultStructuralSharingOption, - TRouterHistory, - TDehydrated + TRouterHistory >, TFrom, TTo, TMaskFrom, TMaskTo - >, + > & { + /** + * @internal + * A **trusted** built location that can be used to redirect to. + */ + _builtLocation?: ParsedLocation + }, ) => Promise<Array<AnyRouteMatch> | undefined> export type MatchRouteFn< @@ -752,15 +708,12 @@ export type UpdateFn< TRouterHistory extends RouterHistory, TDehydrated extends Record<string, any>, > = ( - newOptions: Omit< - RouterConstructorOptions< - TRouteTree, - TTrailingSlashOption, - TDefaultStructuralSharingOption, - TRouterHistory, - TDehydrated - >, - 'pathParamsAllowedCharacters' + newOptions: RouterConstructorOptions< + TRouteTree, + TTrailingSlashOption, + TDefaultStructuralSharingOption, + TRouterHistory, + TDehydrated >, ) => void @@ -775,22 +728,19 @@ export type ParseLocationFn<TRouteTree extends AnyRoute> = ( previousLocation?: ParsedLocation<FullSearchSchema<TRouteTree>>, ) => ParsedLocation<FullSearchSchema<TRouteTree>> -export type GetMatchRoutesFn = (pathname: string) => [ - matchedRoutes: ReadonlyArray<AnyRoute>, +export type GetMatchRoutesFn = (pathname: string) => { + matchedRoutes: ReadonlyArray<AnyRoute> /** exhaustive params, still in their string form */ - rawParams: Record<string, string>, - foundRoute: AnyRoute | undefined, -] + routeParams: Record<string, string> + /** partial params, parsed from routeParams during matching */ + parsedParams: Record<string, unknown> | undefined + foundRoute: AnyRoute | undefined + parseError?: unknown +} export type EmitFn = (routerEvent: RouterEvent) => 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 LoadFn = (opts?: { sync?: boolean }) => Promise<void> export type CommitLocationFn = ({ viewTransition, @@ -798,10 +748,7 @@ export type CommitLocationFn = ({ ...next }: ParsedLocation & CommitLocationOptions) => Promise<void> -export type StartTransitionFn = ( - fn: () => void, - expected: Array<AnyRouteMatch>, -) => Promise<boolean> +export type StartTransitionFn = (fn: () => void) => void export interface MatchRoutesFn { ( @@ -820,6 +767,13 @@ 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 @@ -828,63 +782,31 @@ 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 { - /** @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. */ + /** + * Injects HTML synchronously into the stream. + * Emits an onInjectedHtml event that listeners can handle. + * If no subscriber is listening, the HTML is buffered and can be retrieved via takeBufferedHtml(). + */ + injectHtml: (html: string) => void + /** + * Injects a script tag synchronously into the stream. + */ + injectScript: (script: string) => void + isDehydrated: () => boolean + isSerializationFinished: () => boolean onRenderFinished: (listener: () => void) => void - /** Framework-only. */ setRenderFinished: () => void - /** Framework-only. */ cleanup: () => void + onSerializationFinished: (listener: () => void) => void + dehydrate: () => Promise<void> + takeBufferedScripts: () => RouterManagedTag | undefined /** - * 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. + * Takes any buffered HTML that was injected. + * Returns the buffered HTML string (which may include multiple script tags) or undefined if empty. */ - 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> + takeBufferedHtml: () => string | undefined + liftScriptBarrier: () => void } export type AnyRouterWithContext<TContext> = RouterCore< @@ -951,100 +873,14 @@ 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, - } + const fromLocation = resolvedLocation + const toLocation = 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 } } -/** - * 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', @@ -1074,57 +910,12 @@ declare global { var __TSR_CACHE__: | { routeTree: AnyRoute - caseSensitive: boolean | undefined - processRouteTreeResult: RouteTreeCaches<AnyRoute> + processRouteTreeResult: ProcessRouteTreeResult<AnyRoute> + resolvePathCache: LRUCache<string, string> } | 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. * @@ -1145,19 +936,13 @@ export class RouterCore< tempLocationKey: string | undefined = `${Math.round( Math.random() * 10000000, )}` - _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 } + resetNextScroll = true + shouldViewTransition?: boolean | ViewTransitionOptions = undefined + isViewTransitionTypesSupported?: boolean = undefined subscribers = new Set<RouterListener<RouterEvent>>() - /** Accepted off-screen loader generations keyed by match ID. */ - _cache = new Map<string, AnyRouteMatch>() - /** Accepted semantic lane, excluding temporary pending presentation. */ - _committed: Array<AnyRouteMatch> = [] + viewTransitionPromise?: ControlledPromise<true> + isScrollRestoring = false + isScrollRestorationSetup = false // Must build in constructor stores!: RouterStores<TRouteTree> @@ -1176,26 +961,17 @@ export class RouterCore< > history!: TRouterHistory rewrite?: LocationRewrite - origin!: string + origin?: string latestLocation!: ParsedLocation<FullSearchSchema<TRouteTree>> - _pendingLocation?: ParsedLocation<FullSearchSchema<TRouteTree>> + pendingBuiltLocation?: 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 + resolvePathCache!: LRUCache<string, string> isServer!: boolean - readonly pathParamsDecoder?: (encoded: string) => string + pathParamsDecoder?: (encoded: string) => string protocolAllowlist!: Set<string> /** @@ -1212,11 +988,6 @@ export class RouterCore< getStoreConfig: GetStoreConfig, ) { this.getStoreConfig = getStoreConfig - if (options.pathParamsAllowedCharacters?.length) { - this.pathParamsDecoder = compileDecodeCharMap( - options.pathParamsAllowedCharacters, - ) - } this.update({ defaultPreloadDelay: 50, @@ -1232,19 +1003,24 @@ export class RouterCore< options.protocolAllowlist ?? DEFAULT_PROTOCOL_ALLOWLIST, }) - if (!(isServer ?? typeof document === 'undefined')) { + if (typeof document !== 'undefined') { self.__TSR_ROUTER__ = this } } - startTransition: StartTransitionFn = async (fn) => { - fn() - return false - } + // This is a default implementation that can optionally be overridden + // by the router provider once rendered. We provide this so that the + // router can be used in a non-react environment if necessary + startTransition: StartTransitionFn = (fn) => fn() + isShell() { return !!this.options.isShell } + isPrerendering() { + return !!this.options.isPrerendering + } + update: UpdateFn< TRouteTree, TTrailingSlashOption, @@ -1261,21 +1037,24 @@ export class RouterCore< } 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 ?? 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.isServer = this.options.isServer ?? typeof document === 'undefined' this.protocolAllowlist = new Set(this.options.protocolAllowlist) + if (this.options.pathParamsAllowedCharacters) + this.pathParamsDecoder = compileDecodeCharMap( + this.options.pathParamsAllowedCharacters, + ) + if ( !this.history || (this.options.history && this.options.history !== this.history) @@ -1289,7 +1068,7 @@ export class RouterCore< } } - this.origin = this.options.origin! + this.origin = this.options.origin if (!this.origin) { if ( !(isServer ?? this.isServer) && @@ -1303,83 +1082,107 @@ 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 || - ((isServer ?? this.isServer) && - prevOptions?.caseSensitive !== this.options.caseSensitive) - ) { + if (this.options.routeTree !== this.routeTree) { this.routeTree = this.options.routeTree as TRouteTree - let processRouteTreeResult: RouteTreeCaches<TRouteTree> + let processRouteTreeResult: ProcessRouteTreeResult<TRouteTree> if ( - process.env.NODE_ENV !== 'development' && (isServer ?? this.isServer) && + process.env.NODE_ENV !== 'development' && globalThis.__TSR_CACHE__ && - globalThis.__TSR_CACHE__.routeTree === this.routeTree && - globalThis.__TSR_CACHE__.caseSensitive === this.options.caseSensitive + globalThis.__TSR_CACHE__.routeTree === this.routeTree ) { const cached = globalThis.__TSR_CACHE__ + this.resolvePathCache = cached.resolvePathCache processRouteTreeResult = cached.processRouteTreeResult as any } else { + this.resolvePathCache = createLRUCache(1000) processRouteTreeResult = this.buildRouteTree() // only cache if nothing else is cached yet if ( - process.env.NODE_ENV !== 'development' && (isServer ?? this.isServer) && + process.env.NODE_ENV !== 'development' && globalThis.__TSR_CACHE__ === undefined ) { globalThis.__TSR_CACHE__ = { routeTree: this.routeTree, - caseSensitive: this.options.caseSensitive, processRouteTreeResult: processRouteTreeResult as any, + resolvePathCache: this.resolvePathCache, } } } 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 (!this.stores && this.latestLocation) { + const config = this.getStoreConfig(this) + this.batch = config.batch + this.stores = createRouterStores( + getInitialRouterState(this.latestLocation), + config, + ) - if (!(isServer ?? this.isServer)) { - setupScrollRestoration(this) - } + 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) + } + + 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> = [] + const trimmed = trimPath(nextBasepath) + if (trimmed && trimmed !== '/') { + 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.stores) { + this.stores.location.setState(() => this.latestLocation) + } + + if ( + typeof window !== 'undefined' && + 'CSS' in window && + typeof window.CSS?.supports === 'function' + ) { + this.isViewTransitionTypesSupported = window.CSS.supports( + 'selector(:active-view-transition-type(a)', + ) } } get state(): RouterState<TRouteTree> { - return this.stores.__store.get() + return this.stores.__store.state } updateLatestLocation = () => { @@ -1389,33 +1192,38 @@ export class RouterCore< ) } - buildRouteTree = (): RouteTreeCaches<TRouteTree> => { - const result = processRouteTree(this.routeTree, this.options.caseSensitive) + buildRouteTree = () => { + const result = processRouteTree( + this.routeTree, + this.options.caseSensitive, + (route, i) => { + route.init({ + originalIndex: i, + }) + }, + ) if (this.options.routeMasks) { processRouteMasks(this.options.routeMasks, result.processedTree) } - return { - ...result, - resolvePathCache: createSieveCache(1000), - } + return result } - setRoutes(caches: RouteTreeCaches<TRouteTree>) { - Object.assign(this, caches) - this.lightweightCache = new WeakMap() - if (!(isServer ?? this.isServer)) { - this.staticLocations = new WeakMap() - } + setRoutes({ + routesById, + routesByPath, + processedTree, + }: ProcessRouteTreeResult<TRouteTree>) { + this.routesById = routesById as RoutesById<TRouteTree> + this.routesByPath = routesByPath as RoutesByPath<TRouteTree> + this.processedTree = processedTree const notFoundRoute = this.options.notFoundRoute if (notFoundRoute) { - 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) - } + notFoundRoute.init({ + originalIndex: 99999999999, + }) this.routesById[notFoundRoute.id] = notFoundRoute } } @@ -1440,15 +1248,11 @@ export class RouterCore< } emit: EmitFn = (routerEvent) => { - for (const listener of this.subscribers) { + this.subscribers.forEach((listener) => { if (listener.eventType === routerEvent.type) { - try { - listener.fn(routerEvent) - } catch (e) { - console.error(e) - } + listener.fn(routerEvent) } - } + }) } /** @@ -1459,10 +1263,13 @@ export class RouterCore< locationToParse, previousLocation, ) => { - const parse = ( - { pathname, search, hash, href }: HistoryLocation, - state: HistoryLocation['state'], - ): ParsedLocation<FullSearchSchema<TRouteTree>> => { + const parse = ({ + pathname, + search, + hash, + href, + state, + }: HistoryLocation): 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 @@ -1472,22 +1279,24 @@ export class RouterCore< return { href: pathname + searchStr + hash, - publicHref: pathname + searchStr + hash, - pathname: decodePath(pathname), + publicHref: href, + pathname: decodePath(pathname).path, external: false, searchStr, search: nullReplaceEqualDeep( previousLocation?.search, parsedSearch, ) as any, - hash: decodePath(hash.slice(1)), + hash: decodePath(hash.slice(1)).path, 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)) + // 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 parsedSearch = this.options.parseSearch(url.search) const searchStr = this.options.stringifySearch(parsedSearch) @@ -1495,43 +1304,58 @@ 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: url.href.replace(url.origin, ''), + href: fullPath, publicHref: href, - // 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), + pathname: decodePath(url.pathname).path, + external: !!this.rewrite && url.origin !== this.origin, searchStr, search: nullReplaceEqualDeep( previousLocation?.search, parsedSearch, ) as any, - hash: decodePath(url.hash.slice(1)), + hash: decodePath(url.hash.slice(1)).path, state: replaceEqualDeep(previousLocation?.state, state), } } - const location = parse(locationToParse, locationToParse.state) + const location = parse(locationToParse) const { __tempLocation, __tempKey } = location.state if (__tempLocation && (!__tempKey || __tempKey === this.tempLocationKey)) { - // 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 + // 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, + } } return location } + /** 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, @@ -1550,21 +1374,30 @@ export class RouterCore< return this.matchRoutesInternal(pathnameOrNext, locationSearchOrOpts) } + private getParentContext(parentMatch?: AnyRouteMatch) { + const parentMatchId = parentMatch?.id + + const parentContext = !parentMatchId + ? ((this.options.context as any) ?? undefined) + : (parentMatch.context ?? this.options.context ?? undefined) + + return parentContext + } + private matchRoutesInternal( next: ParsedLocation, opts?: MatchRoutesOpts, ): Array<AnyRouteMatch> { - const [initialMatchedRoutes, rawParams, foundRoute] = this.getMatchedRoutes( - next.pathname, - ) - let matchedRoutes = initialMatchedRoutes + const matchedRoutesResult = this.getMatchedRoutes(next.pathname) + const { foundRoute, routeParams, parsedParams } = matchedRoutesResult + let { matchedRoutes } = matchedRoutesResult 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 !== '/' && rawParams['**'] + ? foundRoute.path !== '/' && routeParams['**'] : // Or if we didn't find a route and we have left over path trimPathRight(next.pathname) ) { @@ -1577,22 +1410,20 @@ export class RouterCore< } } - const _notFoundRouteId = isGlobalNotFound + const globalNotFoundRouteId = isGlobalNotFound ? findGlobalNotFoundRouteId(this.options.notFoundMode, matchedRoutes) : undefined 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 + // Snapshot of active match state keyed by routeId, used to stabilise + // params/search across navigations. + const previousActiveMatchesByRouteId = new Map<string, AnyRouteMatch>() + for (const store of this.stores.activeMatchStoresById.values()) { + if (store.routeId) { + previousActiveMatchesByRouteId.set(store.routeId, store.state) + } } - 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 @@ -1622,6 +1453,7 @@ export class RouterCore< ...strictSearch, } strictMatchSearch = { ...parentStrictSearch, ...strictSearch } + searchError = undefined } catch (err: any) { let searchParamError = err if (!(err instanceof SearchParamError)) { @@ -1639,40 +1471,32 @@ export class RouterCore< 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 - 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 loaderDeps = + route.options.loaderDeps?.({ + search: preMatchSearch, + }) ?? '' - // 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 loaderDepsHash = loaderDeps ? JSON.stringify(loaderDeps) : '' + + const { interpolatedPath, usedParams } = interpolatePath({ + path: route.fullPath, + params: routeParams, + decoder: this.pathParamsDecoder, + server: this.isServer, + }) + + // 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 const matchId = // route.id for disambiguation route.id + @@ -1681,22 +1505,17 @@ export class RouterCore< // explicit deps loaderDepsHash - 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 existingMatch = this.getMatch(matchId) - // Carry parsed ancestors forward without mutating the raw route params. - strictParams = - existingMatch?._strictParams ?? Object.assign(usedParams, strictParams) + const previousMatch = previousActiveMatchesByRouteId.get(route.id) - let paramsError: unknown + const strictParams = existingMatch?._strictParams ?? usedParams + + let paramsError: unknown = undefined if (!existingMatch) { try { - extractStrictParams(route, strictParams) + extractStrictParams(route, usedParams, parsedParams!, strictParams) } catch (err: any) { if (isNotFound(err) || isRedirect(err)) { paramsError = err @@ -1712,6 +1531,8 @@ export class RouterCore< } } + Object.assign(routeParams, strictParams) + const cause = previousMatch ? 'stay' : 'enter' let match: AnyRouteMatch @@ -1720,21 +1541,28 @@ export class RouterCore< match = { ...existingMatch, cause, + params: previousMatch?.params ?? routeParams, + _strictParams: strictParams, search: previousMatch ? nullReplaceEqualDeep(previousMatch.search, preMatchSearch) : nullReplaceEqualDeep(existingMatch.search, preMatchSearch), _strictSearch: strictMatchSearch, - searchError, } } else { - const status = routeNeedsLoad(route) ? 'pending' : 'success' + const status = + route.options.loader || + route.options.beforeLoad || + route.lazyFn || + routeNeedsPreload(route) + ? 'pending' + : 'success' match = { id: matchId, ssr: (isServer ?? this.isServer) ? undefined : route.options.ssr, index, routeId: route.id, - params: previousMatch?.params ?? strictParams, + params: previousMatch?.params ?? routeParams, _strictParams: strictParams, pathname: interpolatedPath, updatedAt: Date.now(), @@ -1742,42 +1570,96 @@ export class RouterCore< ? nullReplaceEqualDeep(previousMatch.search, preMatchSearch) : preMatchSearch, _strictSearch: strictMatchSearch, - searchError, + searchError: undefined, status, isFetching: false, error: undefined, paramsError, + __routeContext: undefined, + _nonReactive: { + loadPromise: createControlledPromise(), + }, + __beforeLoadContext: undefined, context: {}, - abortController: opts?._controller ?? new AbortController(), + abortController: new AbortController(), + fetchCount: 0, 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 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 + if (!opts?.preload) { + // If we have a global not found, mark the right match as global not found + match.globalNotFound = globalNotFoundRouteId === route.id + } + + // update the searchError if there is one + match.searchError = searchError + + const parentContext = this.getParentContext(parentMatch) + + match.context = { + ...parentContext, + ...match.__routeContext, + ...match.__beforeLoadContext, } - match._notFound = _notFound matches[index] = match } 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 = {} + const route = this.looseRoutesById[match.routeId]! + const existingMatch = this.getMatch(match.id) + + // Update the match's params + const previousMatch = previousActiveMatchesByRouteId.get(match.routeId) + match.params = previousMatch + ? nullReplaceEqualDeep(previousMatch.params, routeParams) + : routeParams + + if (!existingMatch) { + const parentMatch = matches[index - 1] + const parentContext = this.getParentContext(parentMatch) + + // Update the match's context + + if (route.options.context) { + const contextFnContext: RouteContextOptions<any, 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, + routeId: route.id, + } + // Get the route context + match.__routeContext = + route.options.context(contextFnContext) ?? undefined + } + + match.context = { + ...parentContext, + ...match.__routeContext, + ...match.__beforeLoadContext, + } } } @@ -1785,41 +1667,27 @@ export class RouterCore< } getMatchedRoutes: GetMatchRoutesFn = (pathname) => { - 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, - ] + return getMatchedRoutes({ + pathname, + routesById: this.routesById, + processedTree: this.processedTree, + }) } /** * Lightweight route matching for buildLocation. * Only computes fullPath, accumulated search, and params - skipping expensive - * operations like AbortController, loaderDeps, and full match objects. + * operations like AbortController, ControlledPromise, 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 */] - } - - const [matchedRoutes, rawParams] = this.getMatchedRoutes(location.pathname) + private matchRoutesLightweight(location: ParsedLocation): { + matchedRoutes: ReadonlyArray<AnyRoute> + fullPath: string + search: Record<string, unknown> + params: Record<string, unknown> + } { + const { matchedRoutes, routeParams, parsedParams } = this.getMatchedRoutes( + location.pathname, + ) const lastRoute = last(matchedRoutes)! // I don't know if we should run the full search middleware chain, or just validateSearch @@ -1845,6 +1713,10 @@ export class RouterCore< } // Determine params: reuse from state if possible, otherwise parse + const lastStateMatchId = last(this.stores.matchesId.state) + const lastStateMatch = + lastStateMatchId && + this.stores.activeMatchStoresById.get(lastStateMatchId)?.state const canReuseParams = lastStateMatch && lastStateMatch.routeId === lastRoute.id && @@ -1855,11 +1727,18 @@ export class RouterCore< params = lastStateMatch.params } else { // Parse params through the route chain - // getMatchedRoutes already copied the cached raw params. - const strictParams: Record<string, unknown> = rawParams + const strictParams: Record<string, unknown> = Object.assign( + Object.create(null), + routeParams, + ) for (const route of matchedRoutes) { try { - extractStrictParams(route, strictParams) + extractStrictParams( + route, + routeParams, + parsedParams ?? {}, + strictParams, + ) } catch { // Ignore errors, we're not actually routing } @@ -1867,87 +1746,81 @@ export class RouterCore< params = strictParams } - const result: LightweightRouteMatchResult = [ + return { matchedRoutes, - lastRoute.fullPath, - accumulatedSearch, + fullPath: lastRoute.fullPath, + search: accumulatedSearch, params, - ] - this.lightweightCache.set(location, [lastStateMatchId, result]) - return result + } + } + + cancelMatch = (id: string) => { + const match = this.getMatch(id) + + if (!match) return + + match.abortController.abort() + clearTimeout(match._nonReactive.pendingTimeout) + match._nonReactive.pendingTimeout = undefined + } + + cancelMatches = () => { + this.stores.pendingMatchesId.state.forEach((matchId) => { + this.cancelMatch(matchId) + }) + + this.stores.matchesId.state.forEach((matchId) => { + if (this.stores.pendingMatchStoresById.has(matchId)) { + return + } + + const match = this.stores.activeMatchStoresById.get(matchId)?.state + if (!match) { + return + } + + if (match.status === 'pending' || match.isFetching === 'loader') { + this.cancelMatch(matchId) + } + }) } /** * Build the next ParsedLocation from navigation options without committing. * Resolves `to`/`from`, params/search/hash/state, applies search validation - * 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. + * and middlewares, and returns a stable, stringified location object. * * @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 => { - 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. + // We allow the caller to override the current location const currentLocation = - opts._fromLocation || this._pendingLocation || this.latestLocation + dest._fromLocation || this.pendingBuiltLocation || this.latestLocation - // 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())) + // Use lightweight matching - only computes what buildLocation needs + // (fullPath, search, params) without creating full match objects + const lightweightResult = this.matchRoutesLightweight(currentLocation) // check that from path exists in the current route tree // do this check only on navigations during test or development if ( - process.env.NODE_ENV !== 'production' && dest.from && + process.env.NODE_ENV !== 'production' && dest._isNavigate ) { - const [allFromMatches] = this.getMatchedRoutes(dest.from) - const [matchedRoutes, fullPath] = currentMatch() + const allFromMatches = this.getMatchedRoutes(dest.from).matchedRoutes - const matchedFrom = findLast(matchedRoutes, (d) => { + const matchedFrom = findLast(lightweightResult.matchedRoutes, (d) => { return comparePaths(d.fullPath, dest.from!) }) const matchedCurrent = findLast(allFromMatches, (d) => { - return comparePaths(d.fullPath, fullPath) + return comparePaths(d.fullPath, lightweightResult.fullPath) }) // for from to be invalid it shouldn't just be unmatched to currentLocation @@ -1957,157 +1830,118 @@ export class RouterCore< } } - 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, + const defaultedFromPath = + dest.unsafeRelative === 'path' + ? currentLocation.pathname + : (dest.from ?? lightweightResult.fullPath) + + // ensure this includes the basePath if set + const fromPath = this.resolvePathWithBase(defaultedFromPath, '.') + + // From search should always use the current location + const fromSearch = lightweightResult.search + // Same with params. It can't hurt to provide as many as possible + const fromParams = Object.assign( + Object.create(null), + lightweightResult.params, ) - const destRoute = this.routesByPath[ - trimPathRight(nextTo) as keyof typeof this.routesByPath - ] as AnyRoute | undefined + // Resolve the next to + // ensure this includes the basePath if set + const nextTo = dest.to + ? this.resolvePathWithBase(fromPath, `${dest.to}`) + : this.resolvePathWithBase(fromPath, '.') - 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 params + const nextParams = + dest.params === false || dest.params === null + ? Object.create(null) + : (dest.params ?? true) === true + ? fromParams + : Object.assign( + fromParams, + functionalUpdate(dest.params as any, fromParams), + ) - if ( - this.options.notFoundRoute && - (!foundRoute || (foundRoute.path !== '/' && rawParams['**'])) - ) { - destRoutes = [...destRoutes, this.options.notFoundRoute] - } + // Use lightweight getMatchedRoutes instead of matchRoutesInternal + // This avoids creating full match objects (AbortController, ControlledPromise, etc.) + // which are expensive and not needed for buildLocation + const destMatchResult = this.getMatchedRoutes(nextTo) + let destRoutes = destMatchResult.matchedRoutes + + // Compute globalNotFoundRouteId using the same logic as matchRoutesInternal + const isGlobalNotFound = + !destMatchResult.foundRoute || + (destMatchResult.foundRoute.path !== '/' && + destMatchResult.routeParams['**']) + + if (isGlobalNotFound && this.options.notFoundRoute) { + 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. + // 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) { + 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 - ? // Keep path params uninterpolated for matchRoute/template matching. + ? // Use the original template path for interpolation + // This preserves the original parameter syntax including optional parameters nextTo - : normalizeProtocolRelative( - decodePath( - interpolation - ? interpolatePath( - nextTo, - interpolation, - nextParams, - this.pathParamsDecoder, - ) - : nextTo, - ), - ) - - 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.`, - ) - } - } catch { - // Ignore roundtrip validation errors. The generated location will be - // handled by the normal navigation flow. - } - } + : decodePath( + interpolatePath({ + path: nextTo, + params: nextParams, + decoder: this.pathParamsDecoder, + server: this.isServer, + }).interpolatedPath, + ).path // Resolve the next search - const middlewares = getSearchMiddlewares( - destRoutes, - 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 - } + 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 } - }) - search = validatedSearch - } - return search + } + }) + nextSearch = validatedSearch } - // 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 + + nextSearch = applySearchMiddleware({ + search: nextSearch, + dest, + destRoutes, + _includeValidateSearch: opts._includeValidateSearch, + }) + + // Replace the equal deep + nextSearch = nullReplaceEqualDeep(fromSearch, nextSearch) // Stringify the next search const searchStr = this.options.stringifySearch(nextSearch) @@ -2115,23 +1949,24 @@ export class RouterCore< // Resolve the next hash const hash = dest.hash === true - ? current().hash - : typeof dest.hash === 'function' - ? dest.hash(current().hash) - : dest.hash || undefined + ? currentLocation.hash + : dest.hash + ? functionalUpdate(dest.hash, currentLocation.hash) + : undefined // Resolve the next hash string const hashStr = hash ? `#${hash}` : '' - // 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 + // 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) // Create the full path of the location const fullPath = `${nextPathname}${searchStr}${hashStr}` @@ -2144,18 +1979,16 @@ export class RouterCore< 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) + href = url.href.replace(url.origin, '') // If rewrite changed the origin, publicHref needs full URL // Otherwise just use the path components - if (isExternalUrl(rewrittenUrl, origin)) { + if (rewrittenUrl.origin !== this.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)) + publicHref = + rewrittenUrl.pathname + rewrittenUrl.search + rewrittenUrl.hash } } else { // Fast path: no rewrite, skip URL construction entirely @@ -2179,45 +2012,67 @@ export class RouterCore< } } - const next = build(opts) + const buildWithMatches = ( + dest: BuildNextOptions = {}, + maskedDest?: BuildNextOptions, + ) => { + const next = build(dest) + + let maskedNext = maskedDest ? build(maskedDest) : undefined + + if (!maskedNext) { + const params = Object.create(null) + + if (this.options.routeMasks) { + const match = findFlatMatch<RouteMask<TRouteTree>>( + next.pathname, + this.processedTree, + ) + if (match) { + Object.assign(params, match.rawParams) // 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 + ? Object.create(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 + } if (opts.mask) { - next.maskedLocation = build({ + return buildWithMatches(opts, { 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, - }) - } } - // 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 + return buildWithMatches(opts) } - _commitPromise: (Promise<void> & { resolve: () => void }) | undefined + commitLocationPromise: undefined | ControlledPromise<void> /** * Commit a previously built location to history (push/replace), optionally @@ -2228,39 +2083,37 @@ export class RouterCore< ignoreBlocker, ...next }) => { - if (isServer ?? this.isServer) { - return - } - - const nextLocation = next.maskedLocation ?? next - if (nextLocation.external && !(isServer ?? this.isServer)) { - return documentNavigation(this, nextLocation.publicHref, { - replace: next.replace, - ignoreBlocker, + 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 } - let historyAction: HistoryAction | undefined - const isSameLocation = - trimPathRight(this.latestLocation.href) === trimPathRight(next.href) && - deepEqual( - _getUserHistoryState(next.state), - _getUserHistoryState(this.latestLocation.state), - ) + const isSameUrl = + trimPathRight(this.latestLocation.href) === trimPathRight(next.href) - const previousCommitPromise = this._commitPromise - let resolve!: () => void - const commitPromise = new Promise<void>((done) => { - resolve = done - }) as Promise<void> & { resolve: () => void } - commitPromise.resolve = () => { - resolve() + let previousCommitPromise = this.commitLocationPromise + this.commitLocationPromise = createControlledPromise<void>(() => { previousCommitPromise?.resolve() - } - this._commitPromise = commitPromise + previousCommitPromise = undefined + }) // Don't commit to history if nothing changed - if (isSameLocation) { + if (isSameUrl && isSameState()) { this.load() } else { let { @@ -2300,32 +2153,25 @@ export class RouterCore< } } - nextHistory.state = { - ...nextHistory.state, - __hashScrollIntoViewOptions: - hashScrollIntoView ?? this.options.defaultHashScrollIntoView ?? true, - } + nextHistory.state.__hashScrollIntoViewOptions = + hashScrollIntoView ?? this.options.defaultHashScrollIntoView ?? true this.shouldViewTransition = viewTransition - historyAction = next.replace ? 'REPLACE' : 'PUSH' - - this.history[historyAction === 'REPLACE' ? 'replace' : 'push']( + this.history[next.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._scroll.n = next.resetScroll ?? true + this.resetNextScroll = next.resetScroll ?? true - return this._commitPromise + if (!this.history.subscribers.size) { + this.load() + } + + return this.commitLocationPromise } /** Convenience helper: build a location from options, then commit it. */ @@ -2335,10 +2181,26 @@ export class RouterCore< hashScrollIntoView, viewTransition, ignoreBlocker, + href, ...rest - }: BuildNextOptions & CommitLocationOptions = {}): Promise<void> => { - if (isServer ?? this.isServer) { - return Promise.resolve() + }: BuildNextOptions & CommitLocationOptions = {}) => { + if (href) { + const currentIndex = this.history.location.state.__TSR_index + + const parsed = parseHref(href, { + __TSR_index: replace ? currentIndex : currentIndex + 1, + }) + + // If the href contains the basepath, we need to strip it before setting `to` + // because `buildLocation` will add the basepath back when creating the final URL. + // Without this, hrefs like '/app/about' would become '/app/app/about'. + const hrefUrl = new URL(parsed.pathname, this.origin) + const rewrittenUrl = executeRewriteInput(this.rewrite, hrefUrl) + + rest.to = rewrittenUrl.pathname + rest.search = this.options.parseSearch(parsed.search) + // remove the leading `#` from the hash + rest.hash = parsed.hash.slice(1) } const location = this.buildLocation({ @@ -2346,7 +2208,7 @@ export class RouterCore< _includeValidateSearch: true, }) - this._pendingLocation = location as ParsedLocation< + this.pendingBuiltLocation = location as ParsedLocation< FullSearchSchema<TRouteTree> > @@ -2361,9 +2223,9 @@ export class RouterCore< // Clear pending location after commit starts // We do this on next microtask to allow synchronous navigate calls to chain - queueMicrotask(() => { - if (this._pendingLocation === location) { - this._pendingLocation = undefined + Promise.resolve().then(() => { + if (this.pendingBuiltLocation === location) { + this.pendingBuiltLocation = undefined } }) @@ -2384,30 +2246,71 @@ export class RouterCore< publicHref, ...rest }) => { - if (isServer ?? this.isServer) { - return + let hrefIsUrl = false + + if (href) { + try { + new URL(`${href}`) + hrefIsUrl = true + } catch {} } - const hrefScheme = href ? getUrlScheme(href) : undefined + if (hrefIsUrl && !reloadDocument) { + reloadDocument = true + } - if (hrefScheme || reloadDocument) { + if (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) - const publicLocation = location.maskedLocation ?? location // Use publicHref which contains the path (origin-stripped is fine for reload) - href ??= publicLocation.publicHref - publicHref ??= publicLocation.publicHref + href = href ?? location.publicHref + publicHref = publicHref ?? location.publicHref } // 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 + const reloadHref = !hrefIsUrl && publicHref ? publicHref : href - return documentNavigation(this, reloadHref, rest) + // Block dangerous protocols like javascript:, blob:, data: + // These could execute arbitrary code if passed to window.location + if (isDangerousProtocol(reloadHref, this.protocolAllowlist)) { + if (process.env.NODE_ENV !== 'production') { + console.warn( + `Blocked navigation to dangerous protocol: ${reloadHref}`, + ) + } + return Promise.resolve() + } + + // 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() + } + } + } + } + + if (rest.replace) { + window.location.replace(reloadHref) + } else { + window.location.href = reloadHref + } + return Promise.resolve() } return this.buildAndCommitLocation({ @@ -2418,17 +2321,254 @@ export class RouterCore< }) } - load: LoadFn = async (opts): Promise<void> => { + latestLoadPromise: undefined | Promise<void> + + beforeLoad = () => { + // Cancel any pending matches + this.cancelMatches() + this.updateLatestLocation() + if (isServer ?? this.isServer) { - return loadServerRoute(this, opts) + // 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, + }) + + // Check if location changed - origin check is unnecessary since buildLocation + // always uses this.origin when constructing URLs + if (this.latestLocation.publicHref !== nextLocation.publicHref) { + const href = this.getParsedLocationHref(nextLocation) + if (nextLocation.external) { + throw redirect({ href }) + } else { + throw redirect({ href, _builtLocation: nextLocation }) + } + } } - this.updateLatestLocation() - if (opts?.action) { - this._scroll.h = - opts.action.type === 'PUSH' || opts.action.type === 'REPLACE' + // Match the routes + const pendingMatches = this.matchRoutes(this.latestLocation) + + const nextCachedMatches = this.stores.cachedMatchesSnapshot.state.filter( + (d) => !pendingMatches.some((e) => e.id === d.id), + ) + + // Ingest the new matches + this.batch(() => { + this.stores.status.setState(() => 'pending') + this.stores.statusCode.setState(() => 200) + this.stores.isLoading.setState(() => true) + this.stores.location.setState(() => this.latestLocation) + this.stores.setPendingMatches(pendingMatches) + // If a cached match moved to pending matches, remove it from cached matches + this.stores.setCachedMatches(nextCachedMatches) + }) + } + + load: LoadFn = async (opts?: { sync?: boolean }): Promise<void> => { + let redirect: AnyRedirect | undefined + let notFound: NotFoundError | undefined + let loadPromise: Promise<void> + const previousLocation = + this.stores.resolvedLocation.state ?? this.stores.location.state + + // eslint-disable-next-line prefer-const + loadPromise = new Promise<void>((resolve) => { + this.startTransition(async () => { + try { + this.beforeLoad() + const next = this.latestLocation + const prevLocation = this.stores.resolvedLocation.state + const locationChangeInfo = getLocationChangeInfo(next, prevLocation) + + if (!this.stores.redirect.state) { + this.emit({ + type: 'onBeforeNavigate', + ...locationChangeInfo, + }) + } + + this.emit({ + type: 'onBeforeLoad', + ...locationChangeInfo, + }) + + await loadMatches({ + router: this, + sync: opts?.sync, + forceStaleReload: previousLocation.href === next.href, + matches: this.stores.pendingMatchesSnapshot.state, + 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 + // + // exitingMatches uses match.id (routeId + params + loaderDeps) so + // navigating /foo?page=1 → /foo?page=2 correctly caches the page=1 entry. + let exitingMatches: Array<AnyRouteMatch> | null = null + + // Lifecycle-hook identity uses routeId only so that navigating between + // different params/deps of the same route fires onStay (not onLeave+onEnter). + let hookExitingMatches: Array<AnyRouteMatch> | null = null + let hookEnteringMatches: Array<AnyRouteMatch> | null = null + let hookStayingMatches: Array<AnyRouteMatch> | null = null + + this.batch(() => { + const pendingMatches = + this.stores.pendingMatchesSnapshot.state + const mountPending = pendingMatches.length + const currentMatches = + this.stores.activeMatchesSnapshot.state + + exitingMatches = mountPending + ? currentMatches.filter( + (match) => + !this.stores.pendingMatchStoresById.has(match.id), + ) + : null + + // Lifecycle-hook identity: routeId only (route presence in tree) + // Build routeId sets from pools to avoid derived stores. + const pendingRouteIds = new Set<string>() + for (const s of this.stores.pendingMatchStoresById.values()) { + if (s.routeId) pendingRouteIds.add(s.routeId) + } + const activeRouteIds = new Set<string>() + for (const s of this.stores.activeMatchStoresById.values()) { + if (s.routeId) activeRouteIds.add(s.routeId) + } + + hookExitingMatches = mountPending + ? currentMatches.filter( + (match) => !pendingRouteIds.has(match.routeId), + ) + : null + hookEnteringMatches = mountPending + ? pendingMatches.filter( + (match) => !activeRouteIds.has(match.routeId), + ) + : null + hookStayingMatches = mountPending + ? pendingMatches.filter((match) => + activeRouteIds.has(match.routeId), + ) + : currentMatches + + this.stores.isLoading.setState(() => false) + this.stores.loadedAt.setState(() => Date.now()) + /** + * 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. + */ + if (mountPending) { + this.stores.setActiveMatches(pendingMatches) + this.stores.setPendingMatches([]) + this.stores.setCachedMatches([ + ...this.stores.cachedMatchesSnapshot.state, + ...exitingMatches!.filter( + (d) => + d.status !== 'error' && + d.status !== 'notFound' && + d.status !== 'redirected', + ), + ]) + this.clearExpiredCache() + } + }) + + // + for (const [matches, hook] of [ + [hookExitingMatches, 'onLeave'], + [hookEnteringMatches, 'onEnter'], + [hookStayingMatches, 'onStay'], + ] as const) { + if (!matches) continue + for (const match of matches as Array<AnyRouteMatch>) { + this.looseRoutesById[match.routeId]!.options[hook]?.( + match, + ) + } + } + }) + }) + }, + }) + } catch (err) { + if (isRedirect(err)) { + redirect = err + if (!(isServer ?? this.isServer)) { + this.navigate({ + ...redirect.options, + replace: true, + ignoreBlocker: true, + }) + } + } else if (isNotFound(err)) { + notFound = err + } + + const nextStatusCode = redirect + ? redirect.status + : notFound + ? 404 + : this.stores.activeMatchesSnapshot.state.some( + (d) => d.status === 'error', + ) + ? 500 + : 200 + + this.batch(() => { + this.stores.statusCode.setState(() => nextStatusCode) + this.stores.redirect.setState(() => 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.stores.activeMatchesSnapshot.state.some((d) => d.status === 'error') + ) { + newStatusCode = 500 + } + if (newStatusCode !== undefined) { + this.stores.statusCode.setState(() => newStatusCode) } - await loadClientRoute(this, opts) } startViewTransition = (fn: () => Promise<void>) => { @@ -2443,8 +2583,9 @@ export class RouterCore< // Attempt to start a view transition (or just apply the changes if we can't) if ( shouldViewTransition && - !(isServer ?? typeof document === 'undefined') && - typeof (document as any).startViewTransition === 'function' + typeof document !== 'undefined' && + 'startViewTransition' in document && + typeof document.startViewTransition === 'function' ) { // lib.dom.ts doesn't support viewTransition types variant yet. // TODO: Fix this when dom types are updated @@ -2452,10 +2593,10 @@ export class RouterCore< if ( typeof shouldViewTransition === 'object' && - window.CSS?.supports?.('selector(:active-view-transition-type(a))') + this.isViewTransitionTypesSupported ) { const next = this.latestLocation - const prevLocation = this.stores.resolvedLocation.get() + const prevLocation = this.stores.resolvedLocation.state const resolvedViewTransitionTypes = typeof shouldViewTransition.types === 'function' @@ -2465,7 +2606,8 @@ export class RouterCore< : shouldViewTransition.types if (resolvedViewTransitionTypes === false) { - return fn() + fn() + return } startViewTransitionParams = { @@ -2476,21 +2618,58 @@ export class RouterCore< startViewTransitionParams = fn } - return (document as any).startViewTransition(startViewTransitionParams) - .updateCallbackDone + document.startViewTransition(startViewTransitionParams) + } else { + fn() } - return fn() + } + + updateMatch: UpdateMatchFn = (id, updater) => { + this.startTransition(() => { + const pendingMatch = this.stores.pendingMatchStoresById.get(id) + if (pendingMatch) { + pendingMatch.setState(updater) + return + } + + const activeMatch = this.stores.activeMatchStoresById.get(id) + if (activeMatch) { + activeMatch.setState(updater) + return + } + + const cachedMatch = this.stores.cachedMatchStoresById.get(id) + if (cachedMatch) { + const next = updater(cachedMatch.state) + if (next.status === 'redirected') { + const deleted = this.stores.cachedMatchStoresById.delete(id) + if (deleted) { + this.stores.cachedMatchesId.setState((prev) => + prev.filter((matchId) => matchId !== id), + ) + } + } else { + cachedMatch.setState(() => next) + } + } + }) + } + + getMatch: GetMatchFn = (matchId: string): AnyRouteMatch | undefined => { + return ( + this.stores.cachedMatchStoresById.get(matchId)?.state ?? + this.stores.pendingMatchStoresById.get(matchId)?.state ?? + this.stores.activeMatchStoresById.get(matchId)?.state + ) } /** - * Invalidate selected match generations and optionally force current matches - * back into a pending state. + * Invalidate the current matches and optionally force them back into a pending state. * - * - 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. + * - 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). */ invalidate: InvalidateFn< RouterCore< @@ -2501,177 +2680,195 @@ 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 (invalidIds.has(d.id)) { - const route = this.routesById[d.routeId] as AnyRoute - const next = { + if (opts?.filter?.(d as MakeRouteMatchUnion<this>) ?? true) { + return { ...d, invalid: true, - ...((opts?.forcePending || - d.status === 'error' || - d.status === 'notFound') && - routeNeedsLoad(route) + ...(opts?.forcePending || + d.status === 'error' || + d.status === 'notFound' ? ({ 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._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.batch(() => { + this.stores.setActiveMatches( + this.stores.activeMatchesSnapshot.state.map(invalidate), + ) + this.stores.setCachedMatches( + this.stores.cachedMatchesSnapshot.state.map(invalidate), + ) + this.stores.setPendingMatches( + this.stores.pendingMatchesSnapshot.state.map(invalidate), + ) + }) this.shouldViewTransition = false return this.load({ sync: opts?.sync }) } - resolveRedirect = (redirect: AnyRedirect): AnyRedirect => { - const options = redirect.options - let href = redirect.headers.get('Location') || options.href + getParsedLocationHref = (location: ParsedLocation) => { + // For redirects and external use, we need publicHref (with rewrite output applied) + // href is the internal path after rewrite input, publicHref is user-facing + return location.publicHref || '/' + } - if (!href) { - const location = this.buildLocation(options) - href = (location.maskedLocation ?? location).publicHref || '/' + resolveRedirect = (redirect: AnyRedirect): AnyRedirect => { + const locationHeader = redirect.headers.get('Location') + + if (!redirect.options.href || redirect.options._builtLocation) { + const location = + redirect.options._builtLocation ?? this.buildLocation(redirect.options) + const href = this.getParsedLocationHref(location) + redirect.options.href = href + redirect.headers.set('Location', href) + } else if (locationHeader) { + try { + const url = new URL(locationHeader) + if (this.origin && url.origin === this.origin) { + const href = url.pathname + url.search + url.hash + redirect.options.href = href + redirect.headers.set('Location', href) + } + } catch { + // ignore invalid URLs + } } - 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)) + redirect.options.href && + !redirect.options._builtLocation && + // Check for dangerous protocols before processing the redirect + isDangerousProtocol(redirect.options.href, this.protocolAllowlist) ) { 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 in href "${redirect.options.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 (!redirect.headers.get('Location')) { + redirect.headers.set('Location', redirect.options.href) } - 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 - 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) - } - } - 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() + if (filter !== undefined) { + this.stores.setCachedMatches( + this.stores.cachedMatchesSnapshot.state.filter( + (m) => !filter(m as MakeRouteMatchUnion<this>), + ), + ) + } else { + this.stores.setCachedMatches([]) } } - loadRouteChunk: ( - route: AnyRoute, - componentType?: 'errorComponent' | 'notFoundComponent' | false, - ) => Promise<void> | undefined = loadRouteChunk + clearExpiredCache = () => { + const now = Date.now() + // 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 + } + + // 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 = now - d.updatedAt >= gcTime + return gcEligible + } + this.clearCache({ filter }) + } + + loadRouteChunk = loadRouteChunk preloadRoute: PreloadRouteFn< TRouteTree, TTrailingSlashOption, TDefaultStructuralSharingOption, - TRouterHistory, - TDehydrated - > = (opts) => preloadClientRoute(this, opts) + TRouterHistory + > = async (opts) => { + const next = opts._builtLocation ?? this.buildLocation(opts as any) + + let matches = this.matchRoutes(next, { + throwOnError: true, + preload: true, + dest: opts, + }) + + const activeMatchIds = new Set([ + ...this.stores.matchesId.state, + ...this.stores.pendingMatchesId.state, + ]) + + const loadedMatchIds = new Set([ + ...activeMatchIds, + ...this.stores.cachedMatchesId.state, + ]) + + // If the matches are already loaded, we need to add them to the cached matches. + const matchesToCache = matches.filter( + (match) => !loadedMatchIds.has(match.id), + ) + if (matchesToCache.length) { + const cachedMatches = this.stores.cachedMatchesSnapshot.state + this.stores.setCachedMatches([...cachedMatches, ...matchesToCache]) + } + + 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 + } + } matchRoute: MatchRouteFn< TRouteTree, @@ -2682,28 +2879,23 @@ export class RouterCore< const matchLocation = { ...location, to: location.to - ? resolvePath( - location.from || '', - location.to as string, - this.options.trailingSlash, - this.resolvePathCache, - ) + ? this.resolvePathWithBase(location.from || '', location.to as string) : undefined, params: location.params || {}, leaveParams: true, } const next = this.buildLocation(matchLocation as any) - const isPending = this.stores.status.get() === 'pending' - if (opts?.pending && !isPending) { + if (opts?.pending && this.stores.status.state !== 'pending') { return false } - const pending = opts?.pending ?? !isPending + const pending = + opts?.pending === undefined ? !this.stores.isLoading.state : opts.pending const baseLocation = pending ? this.latestLocation - : this.stores.resolvedLocation.get() || this.stores.location.get() + : this.stores.resolvedLocation.state || this.stores.location.state const match = findSingleMatch( next.pathname, @@ -2718,13 +2910,13 @@ export class RouterCore< } if (location.params) { - if (!deepEqual(match.rawParams, location.params, true)) { + if (!deepEqual(match.rawParams, location.params, { partial: true })) { return false } } if (opts?.includeSearch ?? true) { - return deepEqual(baseLocation.search, next.search, true) + return deepEqual(baseLocation.search, next.search, { partial: true }) ? match.rawParams : false } @@ -2738,65 +2930,10 @@ export class RouterCore< serverSsr?: ServerSsr - 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) + hasNotFoundMatch = () => { + return this.stores.activeMatchesSnapshot.state.some( + (d) => d.status === 'notFound' || d.globalNotFound, + ) } } @@ -2833,11 +2970,14 @@ export function getInitialRouterState( location: ParsedLocation, ): RouterState<any> { return { + loadedAt: 0, isLoading: false, + isTransitioning: false, status: 'idle', resolvedLocation: undefined, location, matches: [], + statusCode: 200, } } @@ -2869,155 +3009,166 @@ function validateSearch(validateSearch: AnyValidator, input: unknown): unknown { return {} } -function resolveNextParams( - spec: unknown, - base: Record<string, unknown>, -): Record<string, unknown> { - if (spec === undefined || spec === true) { - return base +/** + * 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> = Object.create(null) + const trimmedPath = trimPathRight(pathname) + + let foundRoute: TRouteLike | undefined = undefined + let parsedParams: Record<string, unknown> | undefined = undefined + const match = findRouteMatch<TRouteLike>(trimmedPath, processedTree, true) + if (match) { + foundRoute = match.route + Object.assign(routeParams, match.rawParams) // Copy params, because they're cached + parsedParams = Object.assign(Object.create(null), match.parsedParams) } - 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) + + const matchedRoutes = match?.branch || [routesById[rootRouteId]!] + + return { matchedRoutes, routeParams, foundRoute, parsedParams } } -// 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 */]), - ) - ) +/** + * TODO: once caches are persisted across requests on the server, + * we can cache the built middleware chain using `last(destRoutes)` as the key + */ +function applySearchMiddleware({ + search, + dest, + destRoutes, + _includeValidateSearch, +}: { + search: any + dest: { search?: unknown } + destRoutes: ReadonlyArray<AnyRoute> + _includeValidateSearch: boolean | undefined +}) { + const middleware = buildMiddlewareChain(destRoutes) + return middleware(search, dest, _includeValidateSearch ?? false) } -const EMPTY_RECORD: Record<string, never> = Object.freeze({}) +function buildMiddlewareChain(destRoutes: ReadonlyArray<AnyRoute>) { + const context = { + dest: null as unknown as BuildNextOptions, + _includeValidateSearch: false, + middlewares: [] as Array<SearchMiddleware<any>>, + } -// 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>> - - 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) + for (const route of destRoutes) { + if ('search' in route.options) { + if (route.options.search?.middlewares) { + context.middlewares.push(...route.options.search.middlewares) } } // TODO remove preSearchFilters and postSearchFilters in v2 - else if (routeOptions.preSearchFilters || routeOptions.postSearchFilters) { + else if ( + route.options.preSearchFilters || + route.options.postSearchFilters + ) { const legacyMiddleware: SearchMiddleware<any> = ({ search, next }) => { - const nextSearch = routeOptions.preSearchFilters - ? routeOptions.preSearchFilters.reduce( - (prev, next) => next(prev), - search, - ) - : search + let nextSearch = search + + if ( + 'preSearchFilters' in route.options && + route.options.preSearchFilters + ) { + nextSearch = route.options.preSearchFilters.reduce( + (prev, next) => next(prev), + search, + ) + } const result = next(nextSearch) - return routeOptions.postSearchFilters - ? routeOptions.postSearchFilters.reduce( - (prev, next) => next(prev), - result, - ) - : result - } - middlewares.push(legacyMiddleware) - } - - 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 { ...result, ...validated } - } catch { - // ignore errors here because they are already handled in matchRoutes + if ( + 'postSearchFilters' in route.options && + route.options.postSearchFilters + ) { + return route.options.postSearchFilters.reduce( + (prev, next) => next(prev), + result, + ) } + return result } + context.middlewares.push(legacyMiddleware) + } - middlewares.push(validate) + if (route.options.validateSearch) { + const validate: SearchMiddleware<any> = ({ search, next }) => { + const result = next(search) + if (!context._includeValidateSearch) return result + try { + const validatedSearch = { + ...result, + ...(validateSearch(route.options.validateSearch, result) ?? + undefined), + } + return validatedSearch + } catch { + // ignore errors here because they are already handled in matchRoutes + return result + } + } + + context.middlewares.push(validate) } } - return middlewares -} + // the chain ends here since `next` is not called + const final: SearchMiddleware<any> = ({ search }) => { + const dest = context.dest + if (!dest.search) { + return {} + } + if (dest.search === true) { + return search + } + return functionalUpdate(dest.search, search) + } + + context.middlewares.push(final) -function applySearchMiddleware( - middlewares: Array<SearchMiddleware<any>>, - search: any, - dest: BuildNextOptions, -) { const applyNext = ( index: number, currentSearch: any, - meta?: SearchMiddlewareMeta, + middlewares: Array<SearchMiddleware<any>>, ): any => { // no more middlewares left, return the current search 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 + return currentSearch } - 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) + const middleware = middlewares[index]! + + const next = (newSearch: any): any => { + return applyNext(index + 1, newSearch, middlewares) } - return (middlewares[index]! as any)({ search: currentSearch, next, meta }) + return middleware({ search: currentSearch, next }) } - return applyNext(0, search) + return function middleware( + search: any, + dest: BuildNextOptions, + _includeValidateSearch: boolean, + ) { + context.dest = dest + context._includeValidateSearch = _includeValidateSearch + return applyNext(0, search, context.middlewares) + } } function findGlobalNotFoundRouteId( @@ -3025,16 +3176,11 @@ function findGlobalNotFoundRouteId( 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) { + if (route.children) { return route.id } - fallback ||= route.children && route.id - } - if (fallback) { - return fallback } } return rootRouteId @@ -3042,13 +3188,22 @@ function findGlobalNotFoundRouteId( function extractStrictParams( route: AnyRoute, + referenceParams: Record<string, unknown>, + parsedParams: Record<string, unknown>, accumulatedParams: Record<string, unknown>, ) { const parseParams = route.options.params?.parse ?? route.options.parseParams if (parseParams) { - Object.assign( - accumulatedParams, - parseParams(accumulatedParams as Record<string, string>), - ) + if (route.options.skipRouteOnParseError) { + // Use pre-parsed params from route matching for skipRouteOnParseError routes + for (const key in referenceParams) { + if (key in parsedParams) { + accumulatedParams[key] = parsedParams[key] + } + } + } else { + const result = parseParams(accumulatedParams as Record<string, string>) + Object.assign(accumulatedParams, result) + } } } diff --git a/packages/router-core/src/scroll-restoration-inline.ts b/packages/router-core/src/scroll-restoration-inline.ts deleted file mode 100644 index 76ab0027b3..0000000000 --- a/packages/router-core/src/scroll-restoration-inline.ts +++ /dev/null @@ -1,53 +0,0 @@ -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 deleted file mode 100644 index 7552ebcce3..0000000000 --- a/packages/router-core/src/scroll-restoration-script/client.ts +++ /dev/null @@ -1,5 +0,0 @@ -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 deleted file mode 100644 index 5c5ce5e734..0000000000 --- a/packages/router-core/src/scroll-restoration-script/server.ts +++ /dev/null @@ -1,43 +0,0 @@ -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 972da92da1..4f5cce0648 100644 --- a/packages/router-core/src/scroll-restoration.ts +++ b/packages/router-core/src/scroll-restoration.ts @@ -1,13 +1,20 @@ import { isServer } from '@tanstack/router-core/isServer' +import { functionalUpdate } from './utils' 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 } -type ScrollRestorationByElement = Record<string, ScrollRestorationEntry> +export type ScrollRestorationByElement = Record<string, ScrollRestorationEntry> -type ScrollRestorationByKey = Record<string, ScrollRestorationByElement> +export 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'] @@ -15,31 +22,66 @@ export type ScrollRestorationOptions = { function getSafeSessionStorage() { try { - // Accessing sessionStorage itself can throw SecurityError in locked-down - // contexts, e.g. sandboxed/opaque origins or blocked storage policies. - return sessionStorage + if ( + typeof window !== 'undefined' && + typeof window.sessionStorage === 'object' + ) { + return window.sessionStorage + } } catch { - return + // silent } + return undefined } -// SessionStorage key used to store scroll positions across navigations. +/** 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. */ export const storageKey = 'tsr-scroll-restoration-v1_3' -const safeSessionStorage = getSafeSessionStorage() -function createScrollRestorationCache() { - try { - return JSON.parse( - safeSessionStorage?.getItem(storageKey) || '{}', - ) as ScrollRestorationByKey - } catch { - // ignore invalid session storage payloads - return {} +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) + } } } -const scrollRestorationCache = /* @__PURE__ */ createScrollRestorationCache() -const scrollRestorationIdAttribute = 'data-scroll-restoration-id' +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 + try { + safeSessionStorage.setItem(storageKey, JSON.stringify(state)) + } catch { + console.warn( + '[ts-router] Could not persist scroll restoration state to sessionStorage.', + ) + } + }, + } +} + +/** In-memory handle to the persisted scroll restoration cache. */ +export const scrollRestorationCache = createScrollRestorationCache() /** * The default `getKey` function for `useScrollRestoration`. @@ -47,332 +89,315 @@ const scrollRestorationIdAttribute = 'data-scroll-restoration-id' * * 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 } -function getScrollRestorationSelector(element: Element): string { - const attrId = element.getAttribute(scrollRestorationIdAttribute) - if (attrId) { - return `[${scrollRestorationIdAttribute}="${attrId}"]` - } - - let selector = '' - let el: any = element +/** Best-effort nth-child CSS selector for a given element. */ +export function getCssSelector(el: any): string { + const path = [] let parent: HTMLElement - while ((parent = el.parentNode)) { - let index = 1 - let sibling = el - while ((sibling = sibling.previousElementSibling)) { - index++ - } - - const part = `${el.localName}:nth-child(${index})` - selector = selector ? `${part} > ${selector}` : part + path.push( + `${el.tagName}:nth-child(${Array.prototype.indexOf.call(parent.children, el) + 1})`, + ) el = parent } - - return selector -} - -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] - - if (!entries) { - return - } - - if (options.id) { - return entries[`[${scrollRestorationIdAttribute}="${options.id}"]`] - } - - const element = options.getElement?.() - if (!element) { - return - } - - return entries[ - element === window - ? windowScrollTarget - : getScrollRestorationSelector(element as Element) - ] + return `${path.reverse().join(' > ')}`.toLowerCase() } let ignoreScroll = false -const windowScrollTarget = 'window' -function getElement(selector: string | (() => Element | null | undefined)) { +// 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 { - 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) { + byKey = JSON.parse(sessionStorage.getItem(storageKey) || '{}') + } catch (error) { + console.error(error) return } + const resolvedKey = key || window.history.state?.__TSR_key + const elementEntries = byKey[resolvedKey] + + // + ignoreScroll = true + + // + 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 + ) { + for (const elementSelector in elementEntries) { + const entry = elementEntries[elementSelector]! + if (elementSelector === 'window') { + window.scrollTo({ + top: entry.scrollY, + left: entry.scrollX, + behavior, + }) + } else if (elementSelector) { + const element = document.querySelector(elementSelector) + if (element) { + element.scrollLeft = entry.scrollX + element.scrollTop = entry.scrollY + } + } + } + + 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) + } + } + + 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 && !(isServer ?? router.isServer)) { + return + } + const shouldScrollRestoration = + force ?? router.options.scrollRestoration ?? false + + if (shouldScrollRestoration) { + router.isScrollRestoring = true + } + + if ( + (isServer ?? router.isServer) || + router.isScrollRestorationSetup || + !scrollRestorationCache + ) { + return + } + + router.isScrollRestorationSetup = true + + // + ignoreScroll = false + 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) + window.history.scrollRestoration = 'manual' - 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, - } - } - } - } + // // Create a MutationObserver to monitor DOM changes + // const mutationObserver = new MutationObserver(() => { + // ;ignoreScroll = true + // requestAnimationFrame(() => { + // ;ignoreScroll = false - if (shouldSetupScrollRestoration && !scroll.s) { - scroll.s = true - 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.stores.location.state), + // router.options.scrollRestorationBehavior, + // ) + // }) + // }) - history.scrollRestoration = 'manual' + // 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 + // }) + // } - 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' + // const unobserveDom = () => { + // mutationObserver.disconnect() + // } - // 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.', - ) - } - } - }) + // observeDom() - 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' - } - }) - } + const onScroll = (event: Event) => { + // unobserveDom() - 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 - - if ( - typeof router.options.scrollRestoration === 'function' && - !router.options.scrollRestoration({ location: router.latestLocation }) - ) { + if (ignoreScroll || !router.isScrollRestoring) { return } - const cacheKey = getKey(event.toLocation) - const fromCacheKey = event.fromLocation && getKey(event.fromLocation) + let elementSelector = '' - if (scroll.e && fromCacheKey && fromCacheKey !== cacheKey) { - const fromElementEntries = scrollRestorationCache[fromCacheKey] + if (event.target === document || event.target === window) { + elementSelector = 'window' + } else { + const attrId = (event.target as Element).getAttribute( + 'data-scroll-restoration-id', + ) - 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]! - } + if (attrId) { + elementSelector = `[data-scroll-restoration-id="${attrId}"]` + } else { + elementSelector = getCssSelector(event.target) } } - ignoreScroll = true + const restoreKey = getKey(router.stores.location.state) - try { - const hash = event.toLocation.hash - const hashScrollIntoViewOptions = - event.toLocation.state.__hashScrollIntoViewOptions ?? true - let windowRestored = false + scrollRestorationCache.set((state) => { + const keyEntry = (state[restoreKey] ||= {} as ScrollRestorationByElement) - if (shouldResetScroll) { - if (!hash && scrollToTopSelectors) { - scrollToTopElements ??= getScrollToTopElements(scrollToTopSelectors) - } + const elementEntry = (keyEntry[elementSelector] ||= + {} as ScrollRestorationEntry) - 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, - } - - if (!windowRestored) { - scrollTo(scrollOptions) - } - if (scrollToTopElements) { - for (const element of scrollToTopElements) { - element.scrollTo(scrollOptions) - } - } + 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 } } - if (!windowRestored && hash && hashScrollIntoViewOptions) { - document.getElementById(hash)?.scrollIntoView(hashScrollIntoViewOptions) + 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 } - } finally { - ignoreScroll = false + } + + 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 + }) } }) } + +/** + * @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 location = router.stores.location.state + const hashScrollIntoViewOptions = + location.state.__hashScrollIntoViewOptions ?? true + + if (hashScrollIntoViewOptions && location.hash !== '') { + const el = document.getElementById(location.hash) + if (el) { + el.scrollIntoView(hashScrollIntoViewOptions) + } + } + } +} diff --git a/packages/router-core/src/searchMiddleware.ts b/packages/router-core/src/searchMiddleware.ts index a78732d833..1d60cc9587 100644 --- a/packages/router-core/src/searchMiddleware.ts +++ b/packages/router-core/src/searchMiddleware.ts @@ -1,17 +1,8 @@ -import { deepEqual, hasOwn } from './utils' +import { deepEqual } from './utils' import type { NoInfer, PickOptional } from './utils' -import type { - SearchMiddleware, - SearchMiddlewareContext, - SearchMiddlewareMeta, -} from './route' +import type { SearchMiddleware } from './route' import type { IsRequiredParams } from './link' -type SearchMiddlewareNextWithMeta<TSearchSchema> = ( - newSearch: TSearchSchema, - collectMeta: true, -) => { search: TSearchSchema; meta: SearchMiddlewareMeta } - /** * Retain specified search params across navigations. * @@ -26,64 +17,17 @@ export function retainSearchParams<TSearchSchema extends object>( keys: Array<keyof TSearchSchema> | true, ): SearchMiddleware<TSearchSchema> { return ({ search, next }) => { - const { search: resultSearch, meta } = ( - next as unknown as SearchMiddlewareNextWithMeta<TSearchSchema> - )(search, true) - + const result = next(search) if (keys === true) { - 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] - } - } - 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 + return { ...search, ...result } } - - const copy = { ...resultSearch } - const explicit = meta.explicit + const copy = { ...result } // 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)))) - ) { + keys.forEach((key) => { + if (!(key in copy)) { copy[key] = search[key] } - } + }) return copy } } @@ -101,41 +45,31 @@ export function retainSearchParams<TSearchSchema extends object>( export function stripSearchParams< TSearchSchema, TOptionalProps = PickOptional<NoInfer<TSearchSchema>>, - const TValues = Partial<NoInfer<TSearchSchema>> | Array<keyof TOptionalProps>, + const TValues = + | Partial<NoInfer<TOptionalProps>> + | Array<keyof TOptionalProps>, const TInput = IsRequiredParams<TSearchSchema> extends never ? TValues | true : TValues, >(input: NoInfer<TInput>): SearchMiddleware<TSearchSchema> { - return (({ search, next, meta }: SearchMiddlewareContext<TSearchSchema>) => { + return ({ search, next }) => { if (input === true) { - Object.keys(search as object).forEach((key) => { - if (meta) { - ;(meta.removedAny ||= new Set()).add(key) - } - }) return {} } - const nextResult = next(search) - const result = { ...nextResult } as Record<string, unknown> + const result = { ...next(search) } as Record<string, unknown> if (Array.isArray(input)) { input.forEach((key) => { - delete result[key as string] - if (meta) { - ;(meta.removedAny ||= new Set()).add(key as string) - } + delete result[key] }) } 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 19155586e8..740d36441c 100644 --- a/packages/router-core/src/searchParams.ts +++ b/packages/router-core/src/searchParams.ts @@ -1,10 +1,6 @@ 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. */ @@ -24,10 +20,9 @@ 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.slice(1) + searchStr = searchStr.substring(1) } const query: Record<string, unknown> = decode(searchStr) @@ -36,10 +31,6 @@ 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) { @@ -68,19 +59,15 @@ export function stringifySearchWith( stringify: (search: any) => string, parser?: (str: string) => any, ) { - const isJsonParser = parser === JSON.parse + const hasParser = typeof parser === 'function' function stringifyValue(val: any) { - if (val && typeof val === 'object') { + if (typeof val === 'object' && val !== null) { try { return stringify(val) } catch (_err) { // silent } - } else if (parser && typeof val === 'string') { - // Skip JSON.parse when the value cannot begin valid JSON. - if (isJsonParser && !jsonStart.test(val)) { - return val - } + } else if (hasParser && typeof val === 'string') { 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 deleted file mode 100644 index c977c12e6d..0000000000 --- a/packages/router-core/src/sieve-cache.ts +++ /dev/null @@ -1,75 +0,0 @@ -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 deleted file mode 100644 index 12d3bd7b08..0000000000 --- a/packages/router-core/src/ssr/STREAMING.md +++ /dev/null @@ -1,617 +0,0 @@ -# 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 deleted file mode 100644 index b2472ec30b..0000000000 --- a/packages/router-core/src/ssr/bodyScripts.ts +++ /dev/null @@ -1,57 +0,0 @@ -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 dc769e7495..79ed2f1e8a 100644 --- a/packages/router-core/src/ssr/client.ts +++ b/packages/router-core/src/ssr/client.ts @@ -4,11 +4,3 @@ 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/constants.ts b/packages/router-core/src/ssr/constants.ts index 8ce3dcfa0d..59d6c16100 100644 --- a/packages/router-core/src/ssr/constants.ts +++ b/packages/router-core/src/ssr/constants.ts @@ -1,2 +1,3 @@ export const GLOBAL_TSR = '$_TSR' export declare const GLOBAL_SEROVAL: '$R' +export const TSR_SCRIPT_BARRIER_ID = '$tsr-stream-barrier' diff --git a/packages/router-core/src/ssr/createRequestHandler.ts b/packages/router-core/src/ssr/createRequestHandler.ts index 21e48ca242..5f6dd0fd69 100644 --- a/packages/router-core/src/ssr/createRequestHandler.ts +++ b/packages/router-core/src/ssr/createRequestHandler.ts @@ -1,36 +1,19 @@ -import { createServerHistory } from '@tanstack/history' -import { _getRenderedMatches } from '../load-client' -import { waitForReason as waitForRequest } from '../await-signal' +import { createMemoryHistory } from '@tanstack/history' import { mergeHeaders } from './headers' 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 { ServerManifest } from '../manifest' +import type { Manifest } 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, @@ -38,22 +21,17 @@ export function createRequestHandler<TRouter extends AnyRouter>({ }: { createRouter: () => TRouter request: Request - getRouterManifest?: () => ServerManifest | Promise<ServerManifest> + getRouterManifest?: () => Manifest | Promise<Manifest> }): RequestHandler<TRouter> { return async (cb) => { - const signal = request.signal - signal.throwIfAborted() - const manifest = getRouterManifest - ? await waitForRequest(getRouterManifest(), signal) - : undefined - signal.throwIfAborted() const router = createRouter() - let responseOwnsCleanup = false + // Track whether the callback will handle cleanup + let cbWillCleanup = false try { attachRouterServerSsrUtils({ router, - manifest, + manifest: await getRouterManifest?.(), }) // normalizing and sanitizing the pathname here for server, so we always deal with the same format during SSR. @@ -62,7 +40,9 @@ export function createRequestHandler<TRouter extends AnyRouter>({ const href = url.href.replace(url.origin, '') // Create a history for the router - const history = createServerHistory(href) + const history = createMemoryHistory({ + initialEntries: [href], + }) // Update the router with the history and context router.update({ @@ -70,45 +50,27 @@ export function createRequestHandler<TRouter extends AnyRouter>({ origin: router.options.origin ?? origin, }) - await router.load({ - _signal: signal, - _skipLocationUpdate: true, - }) - signal.throwIfAborted() + await router.load() - const result = router._serverResult - if (result?.type === 'redirect') { - return result.redirect - } - - await router.serverSsr?.dehydrate({ signal }) - signal.throwIfAborted() + await router.serverSsr?.dehydrate() const responseHeaders = getRequestHeaders({ router, }) - 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 + // Mark that the callback will handle cleanup + cbWillCleanup = true + return cb({ + request, + router, + responseHeaders, + }) } finally { - if (!responseOwnsCleanup) { + if (!cbWillCleanup) { // Clean up router SSR state if the callback won't handle it // (e.g., if an error occurred before the callback was invoked). - // Transformed streaming response bodies clean up when consumed/cancelled. + // When the callback runs, it handles cleanup (either via transformStreamWithRouter + // for streaming, or directly in renderRouterToString for non-streaming). router.serverSsr?.cleanup() } } @@ -116,9 +78,15 @@ export function createRequestHandler<TRouter extends AnyRouter>({ } function getRequestHeaders(opts: { router: AnyRouter }): Headers { - const matchHeaders: Array<AnyHeaders> = [] - for (const match of _getRenderedMatches(opts.router.stores.matches.get())) { - matchHeaders.push(match.headers) + const matchHeaders = + opts.router.stores.activeMatchesSnapshot.state.map<AnyHeaders>( + (match) => match.headers, + ) + + // Handle Redirects + const redirect = opts.router.stores.redirect.state + if (redirect) { + matchHeaders.push(redirect.headers) } return mergeHeaders( diff --git a/packages/router-core/src/ssr/handlerCallback.ts b/packages/router-core/src/ssr/handlerCallback.ts index 45f3255c5b..e9ae2cd3ba 100644 --- a/packages/router-core/src/ssr/handlerCallback.ts +++ b/packages/router-core/src/ssr/handlerCallback.ts @@ -1,173 +1,11 @@ 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 - }): HandlerCallbackResult | Promise<HandlerCallbackResult> + }): Response | Promise<Response> } export function defineHandlerCallback<TRouter extends AnyRouter>( diff --git a/packages/router-core/src/ssr/htmlBoundaryScanner.ts b/packages/router-core/src/ssr/htmlBoundaryScanner.ts deleted file mode 100644 index 4a46f7c55f..0000000000 --- a/packages/router-core/src/ssr/htmlBoundaryScanner.ts +++ /dev/null @@ -1,138 +0,0 @@ -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 deleted file mode 100644 index 79222e5d73..0000000000 --- a/packages/router-core/src/ssr/hydrationScripts.ts +++ /dev/null @@ -1,689 +0,0 @@ -/* 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/renderSsrHtmlResponse.ts b/packages/router-core/src/ssr/renderSsrHtmlResponse.ts deleted file mode 100644 index 32f7919b1d..0000000000 --- a/packages/router-core/src/ssr/renderSsrHtmlResponse.ts +++ /dev/null @@ -1,29 +0,0 @@ -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 index 26827d6e96..b5cba6d1a5 100644 --- a/packages/router-core/src/ssr/serializer/RawStream.ts +++ b/packages/router-core/src/ssr/serializer/RawStream.ts @@ -1,10 +1,19 @@ -import type { PluginInfo, SerovalNode } from 'seroval' +import { createPlugin, createStream } from 'seroval' +import type { Plugin } from 'seroval' +/** + * Hint for RawStream encoding strategy during SSR serialization. + * - 'binary': Always use base64 encoding (best for binary data like files, images) + * - 'text': Try UTF-8 first, fallback to base64 (best for text-heavy data like RSC payloads) + */ export type RawStreamHint = 'binary' | 'text' +/** + * Options for RawStream configuration. + */ export interface RawStreamOptions { /** - * Encoding hint for JSON and SSR serialization. + * Encoding hint for SSR serialization. * - 'binary' (default): Always use base64 encoding * - 'text': Try UTF-8 first, fallback to base64 for invalid UTF-8 chunks */ @@ -13,8 +22,7 @@ export interface RawStreamOptions { /** * Marker class for ReadableStream<Uint8Array> that should be serialized - * with base64/text encoding (JSON and SSR) or binary framing - * (server-function responses). + * with base64 encoding (SSR) or binary framing (server functions). * * Wrap your binary streams with this to get efficient serialization: * ```ts @@ -24,13 +32,6 @@ export interface RawStreamOptions { * // 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 @@ -43,16 +44,421 @@ export class RawStream { } } +/** + * Callback type for RPC plugin to register raw streams with multiplexer + */ export type OnRawStreamCallback = ( streamId: number, stream: ReadableStream<Uint8Array>, ) => void -export interface RawStreamJSONNode extends PluginInfo { - text: SerovalNode - stream: SerovalNode +// Base64 helpers used in both Node and browser. +// In Node-like runtimes, prefer Buffer for speed and compatibility. +const BufferCtor: any = (globalThis as any).Buffer +const hasNodeBuffer = !!BufferCtor && typeof BufferCtor.from === 'function' + +function uint8ArrayToBase64(bytes: Uint8Array): string { + if (bytes.length === 0) return '' + + if (hasNodeBuffer) { + return BufferCtor.from(bytes).toString('base64') + } + + // Browser fallback: chunked String.fromCharCode + btoa + const CHUNK_SIZE = 0x8000 // 32KB chunks to avoid stack overflow + const chunks: Array<string> = [] + for (let i = 0; i < bytes.length; i += CHUNK_SIZE) { + const chunk = bytes.subarray(i, i + CHUNK_SIZE) + chunks.push(String.fromCharCode.apply(null, chunk as any)) + } + return btoa(chunks.join('')) } -export interface RawStreamRPCNode extends PluginInfo { - streamId: SerovalNode +function base64ToUint8Array(base64: string): Uint8Array { + if (base64.length === 0) return new Uint8Array(0) + + if (hasNodeBuffer) { + const buf = BufferCtor.from(base64, 'base64') + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) + } + + const binary = atob(base64) + const bytes = new Uint8Array(binary.length) + for (let i = 0; i < binary.length; i++) { + bytes[i] = binary.charCodeAt(i) + } + return bytes +} + +// Factory sentinels - use null-proto objects to avoid prototype surprises +const RAW_STREAM_FACTORY_BINARY: Record<string, never> = Object.create(null) +const RAW_STREAM_FACTORY_TEXT: Record<string, never> = Object.create(null) + +// Factory constructor for binary mode - converts seroval stream to ReadableStream<Uint8Array> +// All chunks are base64 encoded strings +const RAW_STREAM_FACTORY_CONSTRUCTOR_BINARY = ( + stream: ReturnType<typeof createStream>, +) => + new ReadableStream<Uint8Array>({ + start(controller) { + stream.on({ + next(base64: string) { + try { + controller.enqueue(base64ToUint8Array(base64)) + } catch { + // Stream may be closed + } + }, + throw(error: unknown) { + controller.error(error) + }, + return() { + try { + controller.close() + } catch { + // Stream may already be closed + } + }, + }) + }, + }) + +// Factory constructor for text mode - converts seroval stream to ReadableStream<Uint8Array> +// Chunks are either strings (UTF-8) or { $b64: string } (base64 fallback) +// Use module-level TextEncoder to avoid per-factory allocation +const textEncoderForFactory = new TextEncoder() +const RAW_STREAM_FACTORY_CONSTRUCTOR_TEXT = ( + stream: ReturnType<typeof createStream>, +) => { + return new ReadableStream<Uint8Array>({ + start(controller) { + stream.on({ + next(value: string | { $b64: string }) { + try { + if (typeof value === 'string') { + controller.enqueue(textEncoderForFactory.encode(value)) + } else { + controller.enqueue(base64ToUint8Array(value.$b64)) + } + } catch { + // Stream may be closed + } + }, + throw(error: unknown) { + controller.error(error) + }, + return() { + try { + controller.close() + } catch { + // Stream may already be closed + } + }, + }) + }, + }) +} + +// Minified factory function for binary mode - all chunks are base64 strings +// This must be self-contained since it's injected into the HTML +const FACTORY_BINARY = `(s=>new ReadableStream({start(c){s.on({next(b){try{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)}catch(_){}},throw(e){c.error(e)},return(){try{c.close()}catch(_){}}})}}))` + +// Minified factory function for text mode - chunks are string or {$b64: string} +// Uses cached TextEncoder for performance +const FACTORY_TEXT = `(s=>{const e=new TextEncoder();return new ReadableStream({start(c){s.on({next(v){try{if(typeof v==='string'){c.enqueue(e.encode(v))}else{const d=atob(v.$b64),a=new Uint8Array(d.length);for(let i=0;i<d.length;i++)a[i]=d.charCodeAt(i);c.enqueue(a)}}catch(_){}},throw(x){c.error(x)},return(){try{c.close()}catch(_){}}})}})})` + +// Convert ReadableStream<Uint8Array> to seroval stream with base64-encoded chunks (binary mode) +function toBinaryStream(readable: ReadableStream<Uint8Array>) { + const stream = createStream() + const reader = readable.getReader() + + // Use iterative loop instead of recursive async to avoid stack accumulation + ;(async () => { + try { + while (true) { + const { done, value } = await reader.read() + if (done) { + stream.return(undefined) + break + } + stream.next(uint8ArrayToBase64(value)) + } + } catch (error) { + stream.throw(error) + } finally { + reader.releaseLock() + } + })() + + return stream +} + +// Convert ReadableStream<Uint8Array> to seroval stream with UTF-8 first, base64 fallback (text mode) +function toTextStream(readable: ReadableStream<Uint8Array>) { + const stream = createStream() + const reader = readable.getReader() + const decoder = new TextDecoder('utf-8', { fatal: true }) + + // Use iterative loop instead of recursive async to avoid stack accumulation + ;(async () => { + try { + while (true) { + const { done, value } = await reader.read() + if (done) { + // Flush any remaining bytes in the decoder + try { + const remaining = decoder.decode() + if (remaining.length > 0) { + stream.next(remaining) + } + } catch { + // Ignore decode errors on flush + } + stream.return(undefined) + break + } + + try { + // Try UTF-8 decode first + const text = decoder.decode(value, { stream: true }) + if (text.length > 0) { + stream.next(text) + } + } catch { + // UTF-8 decode failed, fallback to base64 + stream.next({ $b64: uint8ArrayToBase64(value) }) + } + } + } catch (error) { + stream.throw(error) + } finally { + reader.releaseLock() + } + })() + + return stream +} + +// Factory plugin for binary mode +const RawStreamFactoryBinaryPlugin = createPlugin< + Record<string, never>, + undefined +>({ + tag: 'tss/RawStreamFactory', + test(value) { + return value === RAW_STREAM_FACTORY_BINARY + }, + parse: { + sync() { + return undefined + }, + async() { + return Promise.resolve(undefined) + }, + stream() { + return undefined + }, + }, + serialize() { + return FACTORY_BINARY + }, + deserialize() { + return RAW_STREAM_FACTORY_BINARY + }, +}) + +// Factory plugin for text mode +const RawStreamFactoryTextPlugin = createPlugin< + Record<string, never>, + undefined +>({ + tag: 'tss/RawStreamFactoryText', + test(value) { + return value === RAW_STREAM_FACTORY_TEXT + }, + parse: { + sync() { + return undefined + }, + async() { + return Promise.resolve(undefined) + }, + stream() { + return undefined + }, + }, + serialize() { + return FACTORY_TEXT + }, + deserialize() { + return RAW_STREAM_FACTORY_TEXT + }, +}) + +/** + * SSR Plugin - uses base64 or UTF-8+base64 encoding for chunks, delegates to seroval's stream mechanism. + * Used during SSR when serializing to JavaScript code for HTML injection. + * + * Supports two modes based on RawStream hint: + * - 'binary': Always base64 encode (default) + * - 'text': Try UTF-8 first, fallback to base64 for invalid UTF-8 + */ +export const RawStreamSSRPlugin: Plugin<any, any> = createPlugin({ + tag: 'tss/RawStream', + extends: [RawStreamFactoryBinaryPlugin, RawStreamFactoryTextPlugin], + + test(value: unknown) { + return value instanceof RawStream + }, + + parse: { + sync(value: RawStream, ctx) { + // Sync parse not really supported for streams, return empty stream + const factory = + value.hint === 'text' + ? RAW_STREAM_FACTORY_TEXT + : RAW_STREAM_FACTORY_BINARY + return { + hint: value.hint, + factory: ctx.parse(factory), + stream: ctx.parse(createStream()), + } + }, + async async(value: RawStream, ctx) { + const factory = + value.hint === 'text' + ? RAW_STREAM_FACTORY_TEXT + : RAW_STREAM_FACTORY_BINARY + const encodedStream = + value.hint === 'text' + ? toTextStream(value.stream) + : toBinaryStream(value.stream) + return { + hint: value.hint, + factory: await ctx.parse(factory), + stream: await ctx.parse(encodedStream), + } + }, + stream(value: RawStream, ctx) { + const factory = + value.hint === 'text' + ? RAW_STREAM_FACTORY_TEXT + : RAW_STREAM_FACTORY_BINARY + const encodedStream = + value.hint === 'text' + ? toTextStream(value.stream) + : toBinaryStream(value.stream) + return { + hint: value.hint, + factory: ctx.parse(factory), + stream: ctx.parse(encodedStream), + } + }, + }, + + serialize(node: { hint: RawStreamHint; factory: any; stream: any }, ctx) { + return ( + '(' + + ctx.serialize(node.factory) + + ')(' + + ctx.serialize(node.stream) + + ')' + ) + }, + + deserialize( + node: { hint: RawStreamHint; factory: any; stream: any }, + ctx, + ): any { + const stream: ReturnType<typeof createStream> = ctx.deserialize(node.stream) + return node.hint === 'text' + ? RAW_STREAM_FACTORY_CONSTRUCTOR_TEXT(stream) + : RAW_STREAM_FACTORY_CONSTRUCTOR_BINARY(stream) + }, +}) as Plugin<any, any> + +/** + * Node type for RPC plugin serialization + */ +interface RawStreamRPCNode { + streamId: number +} + +/** + * Creates an RPC plugin instance that registers raw streams with a multiplexer. + * Used for server function responses where we want binary framing. + * Note: RPC always uses binary framing regardless of hint. + * + * @param onRawStream Callback invoked when a RawStream is encountered during serialization + */ +export function createRawStreamRPCPlugin( + onRawStream: OnRawStreamCallback, +): Plugin<any, any> { + // Own stream counter - sequential IDs starting at 1, independent of seroval internals + let nextStreamId = 1 + + return createPlugin({ + tag: 'tss/RawStream', + + test(value: unknown) { + return value instanceof RawStream + }, + + parse: { + async(value: RawStream) { + const streamId = nextStreamId++ + onRawStream(streamId, value.stream) + return Promise.resolve({ streamId }) + }, + stream(value: RawStream) { + const streamId = nextStreamId++ + onRawStream(streamId, value.stream) + return { streamId } + }, + }, + + serialize(): never { + // RPC uses toCrossJSONStream which produces JSON nodes, not JS code. + // This method is only called by crossSerialize* which we don't use. + throw new Error( + 'RawStreamRPCPlugin.serialize should not be called. RPC uses JSON serialization, not JS code generation.', + ) + }, + + deserialize(): never { + // Client uses createRawStreamDeserializePlugin instead + throw new Error( + 'RawStreamRPCPlugin.deserialize should not be called. Use createRawStreamDeserializePlugin on client.', + ) + }, + }) as Plugin<any, any> +} + +/** + * Creates a deserialize-only plugin for client-side stream reconstruction. + * Used in serverFnFetcher to wire up streams from frame decoder. + * + * @param getOrCreateStream Function to get/create a stream by ID from frame decoder + */ +export function createRawStreamDeserializePlugin( + getOrCreateStream: (id: number) => ReadableStream<Uint8Array>, +): Plugin<any, any> { + return createPlugin({ + tag: 'tss/RawStream', + + test: () => false, // Client never serializes RawStream + + parse: {}, // Client only deserializes, never parses + + serialize(): never { + // Client never serializes RawStream back to server + throw new Error( + 'RawStreamDeserializePlugin.serialize should not be called. Client only deserializes.', + ) + }, + + deserialize(node: RawStreamRPCNode) { + return getOrCreateStream(node.streamId) + }, + }) as Plugin<any, any> } diff --git a/packages/router-core/src/ssr/serializer/RawStreamJSONPlugin.ts b/packages/router-core/src/ssr/serializer/RawStreamJSONPlugin.ts deleted file mode 100644 index cafe363bab..0000000000 --- a/packages/router-core/src/ssr/serializer/RawStreamJSONPlugin.ts +++ /dev/null @@ -1,64 +0,0 @@ -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 deleted file mode 100644 index 7080cae17c..0000000000 --- a/packages/router-core/src/ssr/serializer/RawStreamRPCPlugin.ts +++ /dev/null @@ -1,47 +0,0 @@ -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 deleted file mode 100644 index 0f0a641a54..0000000000 --- a/packages/router-core/src/ssr/serializer/RawStreamSSRPlugin.ts +++ /dev/null @@ -1,97 +0,0 @@ -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 e6b12983a5..f3cc6290c8 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 { PluginInfo, SerovalNode } from 'seroval' +import type { SerovalNode } from 'seroval' -export interface ErrorNode extends PluginInfo { +export interface ErrorNode { message: SerovalNode } diff --git a/packages/router-core/src/ssr/serializer/makeSerovalPlugin.ts b/packages/router-core/src/ssr/serializer/makeSerovalPlugin.ts deleted file mode 100644 index 6d15a9773b..0000000000 --- a/packages/router-core/src/ssr/serializer/makeSerovalPlugin.ts +++ /dev/null @@ -1,31 +0,0 @@ -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 deleted file mode 100644 index 794561cb00..0000000000 --- a/packages/router-core/src/ssr/serializer/makeSsrSerovalPlugin.ts +++ /dev/null @@ -1,40 +0,0 @@ -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 deleted file mode 100644 index e88958f95d..0000000000 --- a/packages/router-core/src/ssr/serializer/rawStreamCodec.ts +++ /dev/null @@ -1,163 +0,0 @@ -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 deleted file mode 100644 index 3b2913d27b..0000000000 --- a/packages/router-core/src/ssr/serializer/seroval-plugins.ssr.ts +++ /dev/null @@ -1,11 +0,0 @@ -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 4595f5c0ad..de10d3bdc0 100644 --- a/packages/router-core/src/ssr/serializer/seroval-plugins.ts +++ b/packages/router-core/src/ssr/serializer/seroval-plugins.ts @@ -1,37 +1,12 @@ import { ReadableStreamPlugin } from 'seroval-plugins/web' import { ShallowErrorPlugin } from './ShallowErrorPlugin' -import { - RawStreamJSONDeserializePlugin, - RawStreamJSONPlugin, - createRawStreamJSONPlugin, -} from './RawStreamJSONPlugin' +import { RawStreamSSRPlugin } from './RawStream' import type { Plugin } from 'seroval' -/** - * 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, +export const defaultSerovalPlugins = [ + ShallowErrorPlugin as Plugin<Error, any>, + // RawStreamSSRPlugin must come before ReadableStreamPlugin to match first + RawStreamSSRPlugin, + // ReadableStreamNode is not exported by seroval + ReadableStreamPlugin as Plugin<ReadableStream, any>, ] diff --git a/packages/router-core/src/ssr/serializer/transformer.ts b/packages/router-core/src/ssr/serializer/transformer.ts index 6fe99f2c43..85f55dd434 100644 --- a/packages/router-core/src/ssr/serializer/transformer.ts +++ b/packages/router-core/src/ssr/serializer/transformer.ts @@ -1,4 +1,6 @@ -import type { PluginInfo, SerovalNode } from 'seroval' +import { createPlugin } from 'seroval' +import { GLOBAL_TSR } from '../constants' +import type { Plugin, SerovalNode } from 'seroval' import type { RegisteredConfigType, RegisteredSsr, @@ -12,7 +14,6 @@ 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 @@ -24,7 +25,6 @@ export interface DefaultSerializable { Uint8Array: Uint8Array RawStream: RawStream TsrSerializable: TsrSerializable - void: void } export interface SerializableExtensions extends DefaultSerializable {} @@ -48,22 +48,6 @@ 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, @@ -76,13 +60,6 @@ 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 @@ -95,14 +72,13 @@ export interface CreateSerializationAdapterOptions< fromSerializable: (value: TOutput) => TInput } -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> +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' : T extends Promise<any> ? ValidateSerializablePromise<T, TSerializable> : T extends ReadableStream<any> @@ -113,9 +89,9 @@ export type ValidateSerializable<T, TSerializable> = T extends TSerializable ? ValidateSerializableMap<T, TSerializable> : T extends AsyncGenerator<any, any> ? ValidateSerializableAsyncGenerator<T, TSerializable> - : T extends object - ? ValidateSerializableMapped<T, TSerializable> - : SerializationError<'Type may not be serializable'> + : { + [K in keyof T]: ValidateSerializable<T[K], TSerializable> + } export type ValidateSerializableAsyncGenerator<T, TSerializable> = T extends AsyncGenerator<infer T, infer TReturn, infer TNext> @@ -149,26 +125,16 @@ export type ValidateSerializableMap<T, TSerializable> = > : never -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 type RegisteredReadableStream = + unknown extends SerializerExtensions['ReadableStream'] + ? never + : SerializerExtensions['ReadableStream'] -export type ValidateSerializableMapped<T, TSerializable> = { - [K in keyof T]: ValidateSerializable<T[K], TSerializable> +export interface DefaultSerializerExtensions { + ReadableStream: unknown } -const SERIALIZATION_ERROR = Symbol.for('TSR_SERIALIZATION_ERROR') - -export interface SerializationError<in out TMessage extends string> { - [SERIALIZATION_ERROR]: TMessage -} +export interface SerializerExtensions extends DefaultSerializerExtensions {} export interface SerializationAdapter< TInput, @@ -195,8 +161,59 @@ export interface SerializationAdapterTypes< export type AnySerializationAdapter = SerializationAdapter<any, any, any> -export interface AdapterNode extends PluginInfo { - v: SerovalNode +/** 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 type ValidateSerializableInput<TRegister, T> = ValidateSerializable< @@ -217,6 +234,20 @@ 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 @@ -251,13 +282,31 @@ export type ValidateSerializableLifecycleResultSSR< ? any : ValidateSerializableInput<TRegister, LooseReturnType<TFn>> -export type RegisteredReadableStream = - unknown extends SerializerExtensions['ReadableStream'] - ? never - : SerializerExtensions['ReadableStream'] +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 interface DefaultSerializerExtensions { - ReadableStream: unknown -} +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 SerializerExtensions extends DefaultSerializerExtensions {} +type ArrayModeResult< + TMode extends 'input' | 'result', + TValue, + TSerializable, +> = TMode extends 'input' + ? ValidateSerializable<TValue, TSerializable> + : ValidateSerializableResult<TValue, TSerializable> diff --git a/packages/router-core/src/ssr/server.ts b/packages/router-core/src/ssr/server.ts index 84c34976c9..89b6059e6d 100644 --- a/packages/router-core/src/ssr/server.ts +++ b/packages/router-core/src/ssr/server.ts @@ -1,33 +1,14 @@ -export { createRequestHandler, waitForRequest } from './createRequestHandler' +export { createRequestHandler } from './createRequestHandler' export type { RequestHandler } from './createRequestHandler' -export { - bindSsrResponseToRequest, - createSsrStreamResponse, - defineHandlerCallback, - disposeSsrResponse, - getSsrStatus, - isSsrResponse, - normalizeSsrResponse, - replaceSsrResponse, - stripSsrResponseBody, -} from './handlerCallback' -export type { - HandlerCallback, - HandlerCallbackResult, - SsrResponse, -} from './handlerCallback' +export { defineHandlerCallback } from './handlerCallback' +export type { HandlerCallback } from './handlerCallback' export { transformPipeableStreamWithRouter, - transformHtmlStringWithRouter, + transformStreamWithRouter, transformReadableStreamWithRouter, } from './transformStreamWithRouter' -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 6b0921c8db..49c4627ad2 100644 --- a/packages/router-core/src/ssr/ssr-client.ts +++ b/packages/router-core/src/ssr/ssr-client.ts @@ -1 +1,293 @@ -export { hydrate } from '../load-client' +import invariant from 'tiny-invariant' +import { isNotFound } from '../not-found' +import { createControlledPromise } from '../utils' +import { hydrateSsrMatchId } from './ssr-match-id' +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 + // Only hydrate global-not-found when a defined value is present in the + // dehydrated payload. If omitted, preserve the value computed from the + // current client location (important for SPA fallback HTML served at unknown + // URLs, where dehydrated matches may come from `/` but client matching marks + // root as globalNotFound). + if (deyhydratedMatch.g !== undefined) { + match.globalNotFound = deyhydratedMatch.g + } +} + +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 dehydratedRouter = window.$_TSR.router + dehydratedRouter.matches.forEach((dehydratedMatch) => { + dehydratedMatch.i = hydrateSsrMatchId(dehydratedMatch.i) + }) + if (dehydratedRouter.lastMatchId) { + dehydratedRouter.lastMatchId = hydrateSsrMatchId( + dehydratedRouter.lastMatchId, + ) + } + const { manifest, dehydratedData, lastMatchId } = dehydratedRouter + + 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.stores.location.state) + + // kick off loading the route chunks + const routeChunkPromise = Promise.all( + matches.map((match) => + router.loadRouteChunk(router.looseRoutesById[match.routeId]!), + ), + ) + + 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 = dehydratedRouter.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.stores.setActiveMatches(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 + const activeMatches = router.stores.activeMatchesSnapshot.state + const location = router.stores.location.state + await Promise.all( + activeMatches.map(async (match) => { + try { + const route = router.looseRoutesById[match.routeId]! + + const parentMatch = activeMatches[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, any> = + { + deps: match.loaderDeps, + params: match.params, + context: parentContext ?? {}, + location, + navigate: (opts: any) => + router.navigate({ + ...opts, + _fromLocation: location, + }), + buildLocation: router.buildLocation, + cause: match.cause, + abortController: match.abortController, + preload: false, + matches, + routeId: route.id, + } + match.__routeContext = + route.options.context(contextFnContext) ?? undefined + } + + match.context = { + ...parentContext, + ...match.__routeContext, + ...match.__beforeLoadContext, + } + + const assetContext = { + ssr: router.options.ssr, + matches: activeMatches, + 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(() => { + router.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.stores.status.state === 'pending') { + router.batch(() => { + router.stores.status.setState(() => 'idle') + router.stores.resolvedLocation.setState( + () => router.stores.location.state, + ) + }) + } + // hide the pending component once the load is finished + router.updateMatch(match.id, (prev) => ({ + ...prev, + _displayPending: undefined, + displayPendingPromise: undefined, + })) + }) + }) + } + return routeChunkPromise +} diff --git a/packages/router-core/src/ssr/ssr-match-id.ts b/packages/router-core/src/ssr/ssr-match-id.ts index 1c725374ec..498c3a0c7e 100644 --- a/packages/router-core/src/ssr/ssr-match-id.ts +++ b/packages/router-core/src/ssr/ssr-match-id.ts @@ -1,9 +1,7 @@ -// 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('/', '#') + return id.replaceAll('/', '\0') +} + +export function hydrateSsrMatchId(id: string): string { + return id.replaceAll('\0', '/').replaceAll('\uFFFD', '/') } diff --git a/packages/router-core/src/ssr/ssr-server.ts b/packages/router-core/src/ssr/ssr-server.ts index e7c9cc2fa6..0d262ade8a 100644 --- a/packages/router-core/src/ssr/ssr-server.ts +++ b/packages/router-core/src/ssr/ssr-server.ts @@ -1,34 +1,39 @@ -import { crossSerializeStream } from 'seroval' -import { invariant } from '../invariant' -import { - createInlineCssPlaceholderAsset, - createInlineCssStyleAsset, - getStylesheetHref, -} from '../manifest' +import { crossSerializeStream, getCrossReferenceHeader } from 'seroval' +import invariant from 'tiny-invariant' 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 { createLRUCache } from '../lru-cache' +import minifiedTsrBootStrapScript from './tsrScript?script-string' +import { GLOBAL_TSR, TSR_SCRIPT_BARRIER_ID } from './constants' 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 { defaultSerovalPlugins } from './serializer/seroval-plugins' +import { makeSsrSerovalPlugin } from './serializer/transformer' +import type { LRUCache } from '../lru-cache' import type { DehydratedMatch, DehydratedRouter } from './types' -import type { AnyRouter, ServerSsr } from '../router' +import type { AnySerializationAdapter } from './serializer/transformer' +import type { AnyRouter } from '../router' import type { AnyRouteMatch } from '../Matches' -import type { - Manifest, - ManifestRoute, - ManifestRouteAssets, - ServerManifest, -} from '../manifest' +import type { Manifest, RouterManagedTag } from '../manifest' -type DehydrationPhase = 'idle' | 'started' | 'disabled' +declare module '../router' { + interface ServerSsr { + setRenderFinished: () => void + cleanup: () => void + } + interface RouterEvents { + onInjectedHtml: { + type: 'onInjectedHtml' + } + onSerializationFinished: { + type: 'onSerializationFinished' + } + } +} + +const SCOPE_ID = 'tsr' + +const TSR_PREFIX = GLOBAL_TSR + '.router=' +const P_PREFIX = GLOBAL_TSR + '.p(()=>' +const P_SUFFIX = ')' export function dehydrateMatch(match: AnyRouteMatch): DehydratedMatch { const dehydratedMatch: DehydratedMatch = { @@ -49,600 +54,320 @@ export function dehydrateMatch(match: AnyRouteMatch): DehydratedMatch { dehydratedMatch[shorthand] = match[key] } } - if (match._notFound) { + if (match.globalNotFound) { dehydratedMatch.g = true } return dehydratedMatch } -function disposeSerializationSafely(dispose?: () => void) { - try { - dispose?.() - } catch (err) { - console.error('Error disposing SSR serialization:', err) - } -} +const INITIAL_SCRIPTS = [ + getCrossReferenceHeader(SCOPE_ID), + minifiedTsrBootStrapScript, +] -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) +class ScriptBuffer { + private router: AnyRouter | undefined + private _queue: Array<string> + private _scriptBarrierLifted = false + private _cleanedUp = false + private _pendingMicrotask = false + + constructor(router: AnyRouter) { + this.router = router + // Copy INITIAL_SCRIPTS to avoid mutating the shared array + this._queue = INITIAL_SCRIPTS.slice() + } + + enqueue(script: string) { + if (this._cleanedUp) return + this._queue.push(script) + // If barrier is lifted, schedule injection (if not already scheduled) + if (this._scriptBarrierLifted && !this._pendingMicrotask) { + this._pendingMicrotask = true + queueMicrotask(() => { + this._pendingMicrotask = false + this.injectBufferedScripts() + }) } } + + liftBarrier() { + if (this._scriptBarrierLifted || this._cleanedUp) return + this._scriptBarrierLifted = true + if (this._queue.length > 0 && !this._pendingMicrotask) { + this._pendingMicrotask = true + queueMicrotask(() => { + this._pendingMicrotask = false + this.injectBufferedScripts() + }) + } + } + + /** + * Flushes any pending scripts synchronously. + * Call this before emitting onSerializationFinished to ensure all scripts are injected. + * + * IMPORTANT: Only injects if the barrier has been lifted. Before the barrier is lifted, + * scripts should remain in the queue so takeBufferedScripts() can retrieve them + */ + flush() { + if (!this._scriptBarrierLifted) return + if (this._cleanedUp) return + this._pendingMicrotask = false + const scriptsToInject = this.takeAll() + if (scriptsToInject && this.router?.serverSsr) { + this.router.serverSsr.injectScript(scriptsToInject) + } + } + + takeAll() { + const bufferedScripts = this._queue + this._queue = [] + if (bufferedScripts.length === 0) { + return undefined + } + // Optimization: if only one script, avoid join + if (bufferedScripts.length === 1) { + return bufferedScripts[0] + ';document.currentScript.remove()' + } + // Append cleanup script and join - avoid push() to not mutate then iterate + return bufferedScripts.join(';') + ';document.currentScript.remove()' + } + + injectBufferedScripts() { + if (this._cleanedUp) return + // Early return if queue is empty (avoids unnecessary takeAll() call) + if (this._queue.length === 0) return + const scriptsToInject = this.takeAll() + if (scriptsToInject && this.router?.serverSsr) { + this.router.serverSsr.injectScript(scriptsToInject) + } + } + + cleanup() { + this._cleanedUp = true + this._queue = [] + this.router = undefined + } } 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> +type ManifestLRU = LRUCache<string, FilteredRoutes> const MANIFEST_CACHE_SIZE = 100 -const manifestCaches = new WeakMap<ServerManifest, ManifestCache>() +const manifestCaches = new WeakMap<Manifest, ManifestLRU>() -function getManifestCache(manifest: ServerManifest): ManifestCache { +function getManifestCache(manifest: Manifest): ManifestLRU { const cache = manifestCaches.get(manifest) - if (cache) { - return cache - } - const newCache = createSieveCache<string, PreparedMatchedManifestRoutes>( - MANIFEST_CACHE_SIZE, - ) + if (cache) return cache + const newCache = createLRUCache<string, FilteredRoutes>(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 - } - - // 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 - } - } - - const preparedRoutes = prepareMatchedManifestRoutes(manifest, matches) - - if (isProd) { - getManifestCache(manifest).set(cacheKey, preparedRoutes) - } - - 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) - } - } - - 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: ServerManifest | undefined - getRequestAssets?: () => ManifestRouteAssets | undefined + manifest: Manifest | 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 = { - get manifest() { - if (!manifest) { - return manifest - } - - const requestAssets = getRequestAssets?.() - const hasAssets = hasRequestAssets(requestAssets) - - 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 composeManifest( - manifest.scriptFormat, - inlineCssAsset, - routes, - hasAssets ? requestAssets : undefined, - ) - }, + manifest, } - let dehydrationPhase: DehydrationPhase = 'idle' - let renderFinished = false + let _dehydrated = false + let _serializationFinished = 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 serializationFinishedListeners: Array<() => void> = [] + const scriptBuffer = new ScriptBuffer(router) + let injectedHtmlBuffer = '' - 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) { + router.serverSsr = { + injectHtml: (html: string) => { + if (!html) return + // Buffer the HTML so it can be retrieved via takeBufferedHtml() + injectedHtmlBuffer += html + // Emit event to notify subscribers that new HTML is available + router.emit({ + type: 'onInjectedHtml', + }) + }, + injectScript: (script: string) => { + if (!script) return + const html = `<script${router.options.ssr?.nonce ? ` nonce='${router.options.ssr.nonce}'` : ''}>${script}</script>` + router.serverSsr!.injectHtml(html) + }, + dehydrate: async () => { + invariant(!_dehydrated, 'router is already dehydrated!') + let matchesToDehydrate = router.stores.activeMatchesSnapshot.state + if (router.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 - // Only currently matched routes are dehydrated. Other route assets are - // loaded through dynamic imports when those routes become active. + // 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) if (manifest) { - const cacheKey = getMatchedRoutesCacheKey(matchesToDehydrate) - const preparedManifest = getPreparedMatchedManifestRoutes( - manifest, - matchesToDehydrate, - cacheKey, - ) + // Prod-only caching; in dev manifests may be replaced/updated (HMR) + const currentRouteIdsList = matchesToDehydrate.map((m) => m.routeId) + const manifestCacheKey = currentRouteIdsList.join('\0') - manifestToDehydrate = composeManifest( - manifest.scriptFormat, - preparedManifest.inlineCssHrefs - ? createInlineCssPlaceholderAsset() - : undefined, - preparedManifest.routes, - opts?.requestAssets, - ) + let filteredRoutes: FilteredRoutes | undefined + + if (isProd) { + filteredRoutes = getManifestCache(manifest).get(manifestCacheKey) + } + + if (!filteredRoutes) { + const currentRouteIds = new Set(currentRouteIdsList) + const nextFilteredRoutes: FilteredRoutes = {} + + for (const routeId in manifest.routes) { + const routeManifest = manifest.routes[routeId]! + if (currentRouteIds.has(routeId)) { + nextFilteredRoutes[routeId] = routeManifest + } else if ( + routeManifest.assets && + routeManifest.assets.length > 0 + ) { + nextFilteredRoutes[routeId] = { + assets: routeManifest.assets, + } + } + } + + if (isProd) { + getManifestCache(manifest).set(manifestCacheKey, nextFilteredRoutes) + } + + filteredRoutes = nextFilteredRoutes + } + + manifestToDehydrate = { + routes: filteredRoutes, + } } const dehydratedRouter: DehydratedRouter = { manifest: manifestToDehydrate, matches, } - 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 lastMatchId = matchesToDehydrate[matchesToDehydrate.length - 1]?.id + if (lastMatchId) { + dehydratedRouter.lastMatchId = dehydrateSsrMatchId(lastMatchId) } - if (dehydratedData !== undefined) { + const dehydratedData = await router.options.dehydrate?.() + if (dehydratedData) { dehydratedRouter.dehydratedData = dehydratedData } - const trackPlugins = { didRun: false } - const serializationAdapters = router.options.serializationAdapters - const plugins = serializationAdapters - ? [ - ...serializationAdapters.map((adapter) => - makeSsrSerovalPlugin(adapter, trackPlugins), - ), - ...ssrSerovalPlugins, - ] - : ssrSerovalPlugins + _dehydrated = true - 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)) + const trackPlugins = { didRun: false } + const serializationAdapters = router.options.serializationAdapters as + | Array<AnySerializationAdapter> + | undefined + const plugins = serializationAdapters + ? serializationAdapters + .map((t) => makeSsrSerovalPlugin(t, trackPlugins)) + .concat(defaultSerovalPlugins) + : defaultSerovalPlugins + + const signalSerializationComplete = () => { + _serializationFinished = true + try { + serializationFinishedListeners.forEach((l) => l()) + router.emit({ type: 'onSerializationFinished' }) + } catch (err) { + console.error('Serialization listener error:', err) + } finally { + serializationFinishedListeners.length = 0 + renderFinishedListeners.length = 0 } } - let synchronousFailure: { error: unknown } | undefined - const dispose = crossSerializeStream(dehydratedRouter, { + crossSerializeStream(dehydratedRouter, { refs: new Map(), plugins, onSerialize: (data, initial) => { - if (serializationCompleteSignaled || cleanupStarted) { - return - } - initialSerialized ||= initial - if ( - !hydrationScripts.pushSerializedSource( - data, - initial, - trackPlugins.didRun, - ) - ) { - // Rejected output stops the producer while deferred work may remain. - completeScriptSerialization(false) + let serialized = initial ? TSR_PREFIX + data : data + if (trackPlugins.didRun) { + serialized = P_PREFIX + serialized + P_SUFFIX } + scriptBuffer.enqueue(serialized) }, - onError: (err: unknown) => { - if (serializationCompleteSignaled || cleanupStarted) { - return - } - console.error('Serialization error:', err) - synchronousFailure = { error: err } - completeScriptSerialization({ error: err }) - }, - scopeId: SSR_SERIALIZATION_SCOPE_ID, + scopeId: SCOPE_ID, onDone: () => { - if (initialSerialized) { - completeScriptSerialization(true) - } + scriptBuffer.enqueue(GLOBAL_TSR + '.e()') + // Flush all pending scripts synchronously before signaling completion + // This ensures all scripts are injected before onSerializationFinished is emitted + scriptBuffer.flush() + signalSerializationComplete() + }, + onError: (err) => { + console.error('Serialization error:', err) + signalSerializationComplete() }, }) - // Seroval can call onDone synchronously before it returns dispose(). - if (cleanupStarted || serializationCompleteSignaled) { - disposeSerializationSafely(dispose) - } else { - disposeSerialization = dispose - } - if (synchronousFailure) { - throw synchronousFailure.error - } }, - onRenderFinished: (listener) => { - if (cleanupStarted) { - return - } - if (renderFinished) { - try { - listener() - } catch (error) { - console.error('Error in render finished listener:', error) - } - return - } - renderFinishedListeners.push(listener) + isDehydrated() { + return _dehydrated }, - 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) + isSerializationFinished() { + return _serializationFinished }, + onRenderFinished: (listener) => renderFinishedListeners.push(listener), + onSerializationFinished: (listener) => + serializationFinishedListeners.push(listener), setRenderFinished: () => { - if (cleanupStarted || renderFinished) { - return + // Wrap in try-catch to ensure scriptBuffer.liftBarrier() is always called + try { + renderFinishedListeners.forEach((l) => l()) + } catch (err) { + console.error('Error in render finished listener:', err) + } finally { + // Clear listeners after calling them to prevent memory leaks + renderFinishedListeners.length = 0 } - renderFinished = true - hydrationScripts.liftBarrier() - notifyAndClearListeners( - renderFinishedListeners, - 'Error in render finished listener:', - undefined, - ) + scriptBuffer.liftBarrier() }, - disableHydration: () => { - if (cleanupStarted || dehydrationPhase === 'disabled') { - return + 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, } - if (dehydrationPhase !== 'idle') { - if (process.env.NODE_ENV !== 'production') { - throw new Error( - 'Invariant failed: cannot disable hydration after dehydrate()!', - ) - } - - invariant() + return serverBufferedScript + }, + liftScriptBarrier() { + scriptBuffer.liftBarrier() + }, + takeBufferedHtml() { + if (!injectedHtmlBuffer) { + return undefined } - // The owner rejects later takes/claims; guard order matters so a - // throwing owner does not leave the phase half-set. - hydrationScripts.disableHydration() - dehydrationPhase = 'disabled' + const buffered = injectedHtmlBuffer + injectedHtmlBuffer = '' + return buffered }, - takeInitialHydrationScriptTags: - hydrationScripts.takeInitialHydrationScriptTags, cleanup() { - // 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, - ) + // Guard against multiple cleanup calls + if (!router.serverSsr) return renderFinishedListeners.length = 0 - router.ssr = undefined + serializationFinishedListeners.length = 0 + injectedHtmlBuffer = '' + scriptBuffer.cleanup() 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) - } - } } /** @@ -673,17 +398,12 @@ export function getOrigin(request: Request) { // 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, + // ensure backslashes are encoded correctly in the URL + if (typeof url === 'string') url = url.replace('\\', '%5C') + + const rawUrl = new URL(url, base) + const { path: decodedPathname, handledProtocolRelativeURL } = decodePath( + rawUrl.pathname, ) const searchParams = new URLSearchParams(rawUrl.search) const normalizedHref = diff --git a/packages/router-core/src/ssr/transformStreamWithRouter.ts b/packages/router-core/src/ssr/transformStreamWithRouter.ts index d253034073..99fe436256 100644 --- a/packages/router-core/src/ssr/transformStreamWithRouter.ts +++ b/packages/router-core/src/ssr/transformStreamWithRouter.ts @@ -1,967 +1,493 @@ +import { ReadableStream } from 'node:stream/web' import { Readable } from 'node:stream' -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 { TSR_SCRIPT_BARRIER_ID } from './constants' import type { AnyRouter } from '../router' -import type { ByteMatcherState } from './htmlBoundaryScanner' -import type { HydrationScriptOutput } from './hydrationScripts' -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 +export function transformReadableStreamWithRouter( + router: AnyRouter, + routerStream: ReadableStream, +) { + return transformStreamWithRouter(router, routerStream) } -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( - transformReadableStreamWithRouter( - router, - Readable.toWeb(routerStream) as AppStream, - opts, - ) as NodeReadableStream<Uint8Array>, + transformStreamWithRouter(router, Readable.toWeb(routerStream)), ) } -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. - } - throw error - } finally { - serverSsr.cleanup() - } - } +// Use string constants for simple indexOf matching +const BODY_END_TAG = '</body>' +const HTML_END_TAG = '</html>' - // 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) -} +// Minimum length of a valid closing tag: </a> = 4 characters +const MIN_CLOSING_TAG_LENGTH = 4 -async function readUtf8Stream(stream: ReadableStream<Uint8Array>) { - const reader = stream.getReader() - const decoder = new TextDecoder() - let text = '' - try { - for (;;) { - const { done, value } = await reader.read() - if (done) { - break - } - text += decoder.decode(value, { stream: true }) - } - return text + decoder.decode() - } finally { - reader.releaseLock() - } -} +// Default timeout values (in milliseconds) +const DEFAULT_SERIALIZATION_TIMEOUT_MS = 60000 +const DEFAULT_LIFETIME_TIMEOUT_MS = 60000 -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, -) { - try { - if (kind === 'complete') { - controller.close() - } else if (kind === 'failure') { - controller.error(reason) - } - } catch { - // The stream already reached a terminal state. - } - - const aborted = kind !== 'complete' - if (aborted) { - try { - onAbort?.(reason) - } catch { - // User cleanup must not block SSR cleanup. - } - } - - const readerDone = aborted - ? cancelReader(reader, reason) - : releaseReader(reader) - serverSsr.cleanup() - return readerDone -} - -function getLifetimeMs(opts?: TransformStreamWithRouterOptions) { - return ( - opts?.lifetimeMs ?? - (opts?.timeoutMs ?? DEFAULT_SERIALIZATION_TIMEOUT_MS) * 2 - ) -} - -// 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 -} - -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) -} +// Module-level encoder (stateless, safe to reuse) +const textEncoder = new TextEncoder() /** - * Create a timer that does not keep the Node.js process alive when this - * last-resort stream backstop is the only remaining work. + * Finds the position just after the last valid HTML closing tag in the string. * - * 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`. + * Valid closing tags match the pattern: </[a-zA-Z][\w:.-]*> + * Examples: </div>, </my-component>, </slot:name.nested> + * + * @returns Position after the last closing tag, or -1 if none found */ -function setUnrefTimeout(callback: () => void, timeoutMs: number) { - const handle = setTimeout(callback, timeoutMs) - const portableHandle = handle as typeof handle & { unref?: () => void } - portableHandle.unref?.() - return handle +function findLastClosingTagEnd(str: string): number { + const len = str.length + if (len < MIN_CLOSING_TAG_LENGTH) return -1 + + let i = len - 1 + + while (i >= MIN_CLOSING_TAG_LENGTH - 1) { + // Look for > (charCode 62) + if (str.charCodeAt(i) === 62) { + // Look backwards for valid tag name characters + 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: [a-zA-Z0-9_:.-] + 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) + // Tag name must start with a letter (a-z or A-Z) + 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 } -/** - * 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, +export function transformStreamWithRouter( + router: AnyRouter, + appStream: ReadableStream, + opts?: { + /** Timeout for serialization to complete after app render finishes (default: 60000ms) */ + timeoutMs?: number + /** Maximum lifetime of the stream transform (default: 60000ms). Safety net for cleanup. */ + lifetimeMs?: number + }, ) { - const signal = opts?.signal + // Check upfront if serialization already finished synchronously + // This is the fast path for routes with no deferred data + const serializationAlreadyFinished = + router.serverSsr?.isSerializationFinished() ?? false + + // Take any HTML that was buffered before we started listening + const initialBufferedHtml = router.serverSsr?.takeBufferedHtml() + + // True passthrough: if serialization already finished and nothing buffered, + // we can avoid any decoding/scanning while still honoring cleanup + setRenderFinished. + if (serializationAlreadyFinished && !initialBufferedHtml) { + let cleanedUp = false + let controller: ReadableStreamDefaultController<Uint8Array> | undefined + let isStreamClosed = false + let lifetimeTimeoutHandle: ReturnType<typeof setTimeout> | undefined + + const cleanup = () => { + if (cleanedUp) return + cleanedUp = true + + if (lifetimeTimeoutHandle !== undefined) { + clearTimeout(lifetimeTimeoutHandle) + lifetimeTimeoutHandle = undefined + } + + router.serverSsr?.cleanup() + } + + const safeClose = () => { + if (isStreamClosed) return + isStreamClosed = true + try { + controller?.close() + } catch { + // ignore + } + } + + const safeError = (error: unknown) => { + if (isStreamClosed) return + isStreamClosed = true + try { + controller?.error(error) + } catch { + // ignore + } + } + + const lifetimeMs = opts?.lifetimeMs ?? DEFAULT_LIFETIME_TIMEOUT_MS + lifetimeTimeoutHandle = setTimeout(() => { + if (!cleanedUp && !isStreamClosed) { + console.warn( + `SSR stream transform exceeded maximum lifetime (${lifetimeMs}ms), forcing cleanup`, + ) + safeError(new Error('Stream lifetime exceeded')) + cleanup() + } + }, lifetimeMs) + + const stream = new ReadableStream<Uint8Array>({ + start(c) { + controller = c + }, + cancel() { + isStreamClosed = true + cleanup() + }, + }) + + ;(async () => { + const reader = appStream.getReader() + try { + while (true) { + const { done, value } = await reader.read() + if (done) break + if (cleanedUp || isStreamClosed) return + controller?.enqueue(value as unknown as Uint8Array) + } + + if (cleanedUp || isStreamClosed) return + + router.serverSsr?.setRenderFinished() + safeClose() + cleanup() + } catch (error) { + if (cleanedUp) return + console.error('Error reading appStream:', error) + router.serverSsr?.setRenderFinished() + safeError(error) + cleanup() + } finally { + reader.releaseLock() + } + })().catch((error) => { + if (cleanedUp) return + console.error('Error in stream transform:', error) + safeError(error) + cleanup() + }) + + return stream + } + + let stopListeningToInjectedHtml: (() => void) | undefined + let stopListeningToSerializationFinished: (() => void) | undefined + let serializationTimeoutHandle: ReturnType<typeof setTimeout> | undefined 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 + let cleanedUp = false + + let controller: ReadableStreamDefaultController<any> + let isStreamClosed = false + + const textDecoder = new TextDecoder() + + // concat'd router HTML; avoids array joins on each flush + let pendingRouterHtml = initialBufferedHtml ?? '' + + // between-chunk text buffer; keep bounded to avoid unbounded memory + let leftover = '' + + // captured closing tags from </body> onward + let pendingClosingTags = '' + + // conservative cap: enough to hold any partial closing tag + a bit + const MAX_LEFTOVER_CHARS = 2048 + + let isAppRendering = true + let streamBarrierLifted = false + let serializationFinished = serializationAlreadyFinished + + function safeEnqueue(chunk: string | Uint8Array) { + if (isStreamClosed) return + if (typeof chunk === 'string') { + controller.enqueue(textEncoder.encode(chunk)) + } else { + controller.enqueue(chunk) + } + } + + function safeClose() { + if (isStreamClosed) return + isStreamClosed = true + try { + controller.close() + } catch { + // ignore + } + } + + function safeError(error: unknown) { + if (isStreamClosed) return + isStreamClosed = true + try { + controller.error(error) + } catch { + // ignore + } + } + + /** + * Cleanup with guards; must be idempotent. + */ + function cleanup() { + if (cleanedUp) return + cleanedUp = true + + try { + stopListeningToInjectedHtml?.() + stopListeningToSerializationFinished?.() + } catch { + // ignore + } + stopListeningToInjectedHtml = undefined + stopListeningToSerializationFinished = undefined + + if (serializationTimeoutHandle !== undefined) { + clearTimeout(serializationTimeoutHandle) + serializationTimeoutHandle = undefined } if (lifetimeTimeoutHandle !== undefined) { clearTimeout(lifetimeTimeoutHandle) lifetimeTimeoutHandle = undefined } + + pendingRouterHtml = '' + leftover = '' + pendingClosingTags = '' + + router.serverSsr?.cleanup() } - 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 - } - 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 - } - } - if (result.done || typeof result.value === 'string') { - acceptAppRead(result) - continue - } - if (result.value.byteLength > 0) { - controller.enqueue(result.value) - return - } - } - } catch (error) { - handlePumpError(error) - } - } - - async function pump() { - const output = hydrationOutput! - while (!terminal) { - const hydrationState = output.state - if (hydrationState === HydrationScriptOutputState.Active) { - controller.enqueue(output.pullChunk()) - return - } - if ( - applicationPhase !== ApplicationPhase.BeforeBoundary && - insertionBoundary && - hydrationState === HydrationScriptOutputState.Ready - ) { - 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 - } - - 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 - } - - await loadNextAppChunk() - } - } - - function handlePumpError(error: unknown) { - if (terminal) { - return - } - console.error('Error processing appStream:', error) - terminate('failure', error) - } - - const stream = new ReadableStream<Uint8Array>({ + const stream = new ReadableStream({ start(c) { controller = c }, - 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) - }, - cancel(reason) { - return terminate('cancel', reason) + cancel() { + isStreamClosed = true + cleanup() }, }) - if (hydrationOutput) { - stopHydrationOutputListener = hydrationOutput.subscribe(() => { - if (hydrationOutput.state === HydrationScriptOutputState.Failed) { - terminate('failure', hydrationOutput.error) - return - } - wakePump() - }) + function flushPendingRouterHtml() { + if (!pendingRouterHtml) return + safeEnqueue(pendingRouterHtml) + pendingRouterHtml = '' } - disarmLifecycle = armStreamLifecycle( - serverSsr, - opts, - () => terminal, - terminate, - ) + + function appendRouterHtml(html: string) { + if (!html) return + pendingRouterHtml += html + } + + /** + * Finish only when app done and serialization complete. + */ + function tryFinish() { + if (isAppRendering || !serializationFinished) return + if (cleanedUp || isStreamClosed) return + + if (serializationTimeoutHandle !== undefined) { + clearTimeout(serializationTimeoutHandle) + serializationTimeoutHandle = undefined + } + + // Flush any remaining bytes in the TextDecoder + const decoderRemainder = textDecoder.decode() + + if (leftover) safeEnqueue(leftover) + if (decoderRemainder) safeEnqueue(decoderRemainder) + flushPendingRouterHtml() + if (pendingClosingTags) safeEnqueue(pendingClosingTags) + + safeClose() + cleanup() + } + + // Safety net: cleanup even if consumer never reads + const lifetimeMs = opts?.lifetimeMs ?? DEFAULT_LIFETIME_TIMEOUT_MS + lifetimeTimeoutHandle = setTimeout(() => { + if (!cleanedUp && !isStreamClosed) { + console.warn( + `SSR stream transform exceeded maximum lifetime (${lifetimeMs}ms), forcing cleanup`, + ) + safeError(new Error('Stream lifetime exceeded')) + cleanup() + } + }, lifetimeMs) + + if (!serializationAlreadyFinished) { + stopListeningToInjectedHtml = router.subscribe('onInjectedHtml', () => { + if (cleanedUp || isStreamClosed) return + const html = router.serverSsr?.takeBufferedHtml() + if (!html) return + + // If we've already captured </body> (pendingClosingTags), we must keep appending + // so injection stays before the stored closing tags. + if (isAppRendering || leftover || pendingClosingTags) { + appendRouterHtml(html) + } else { + safeEnqueue(html) + } + }) + + stopListeningToSerializationFinished = router.subscribe( + 'onSerializationFinished', + () => { + serializationFinished = true + tryFinish() + }, + ) + } + + // Transform the appStream + ;(async () => { + const reader = appStream.getReader() + try { + while (true) { + const { done, value } = await reader.read() + if (done) break + + if (cleanedUp || isStreamClosed) return + + const text = + value instanceof Uint8Array + ? textDecoder.decode(value, { stream: true }) + : String(value) + + // Fast path: most chunks have no pending left-over. + const chunkString = leftover ? leftover + text : text + + if (!streamBarrierLifted) { + if (chunkString.includes(TSR_SCRIPT_BARRIER_ID)) { + streamBarrierLifted = true + router.serverSsr?.liftScriptBarrier() + } + } + + // If we already saw </body>, everything else is part of tail; buffer it. + if (pendingClosingTags) { + pendingClosingTags += chunkString + leftover = '' + continue + } + + const bodyEndIndex = chunkString.indexOf(BODY_END_TAG) + const htmlEndIndex = chunkString.indexOf(HTML_END_TAG) + + if ( + bodyEndIndex !== -1 && + htmlEndIndex !== -1 && + bodyEndIndex < htmlEndIndex + ) { + pendingClosingTags = chunkString.slice(bodyEndIndex) + safeEnqueue(chunkString.slice(0, bodyEndIndex)) + flushPendingRouterHtml() + leftover = '' + continue + } + + const lastClosingTagEnd = findLastClosingTagEnd(chunkString) + + if (lastClosingTagEnd > 0) { + safeEnqueue(chunkString.slice(0, lastClosingTagEnd)) + flushPendingRouterHtml() + + leftover = chunkString.slice(lastClosingTagEnd) + if (leftover.length > MAX_LEFTOVER_CHARS) { + // Ensure bounded memory even if a consumer streams long text sequences + // without any closing tags. This may reduce injection granularity but is correct. + safeEnqueue(leftover.slice(0, leftover.length - MAX_LEFTOVER_CHARS)) + leftover = leftover.slice(-MAX_LEFTOVER_CHARS) + } + } else { + // No closing tag found; keep small tail to handle split closing tags, + // but stream older bytes to prevent unbounded buffering. + const combined = chunkString + if (combined.length > MAX_LEFTOVER_CHARS) { + const flushUpto = combined.length - MAX_LEFTOVER_CHARS + safeEnqueue(combined.slice(0, flushUpto)) + leftover = combined.slice(flushUpto) + } else { + leftover = combined + } + } + } + + if (cleanedUp || isStreamClosed) return + + isAppRendering = false + router.serverSsr?.setRenderFinished() + + if (serializationFinished) { + tryFinish() + } else { + const timeoutMs = opts?.timeoutMs ?? DEFAULT_SERIALIZATION_TIMEOUT_MS + serializationTimeoutHandle = setTimeout(() => { + if (!cleanedUp && !isStreamClosed) { + console.error('Serialization timeout after app render finished') + safeError( + new Error('Serialization timeout after app render finished'), + ) + cleanup() + } + }, timeoutMs) + } + } catch (error) { + if (cleanedUp) return + console.error('Error reading appStream:', error) + isAppRendering = false + router.serverSsr?.setRenderFinished() + safeError(error) + cleanup() + } finally { + reader.releaseLock() + } + })().catch((error) => { + if (cleanedUp) return + console.error('Error in stream transform:', error) + safeError(error) + cleanup() + }) return stream } diff --git a/packages/router-core/src/ssr/types.ts b/packages/router-core/src/ssr/types.ts index 48b8c8d0e9..70395cc9a0 100644 --- a/packages/router-core/src/ssr/types.ts +++ b/packages/router-core/src/ssr/types.ts @@ -3,7 +3,6 @@ import type { MakeRouteMatch } from '../Matches' export interface DehydratedMatch { i: MakeRouteMatch['id'] - /** @internal */ b?: MakeRouteMatch['__beforeLoadContext'] l?: MakeRouteMatch['loaderData'] e?: MakeRouteMatch['error'] @@ -16,6 +15,7 @@ export interface DehydratedMatch { 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 index 8c2beeb2e7..c31bfb4ecb 100644 --- a/packages/router-core/src/stores.ts +++ b/packages/router-core/src/stores.ts @@ -1,19 +1,21 @@ -import { arraysEqual, functionalUpdate } from './utils' +import { createLRUCache } from './lru-cache' +import { arraysEqual } from './utils' import type { AnyRoute } from './route' import type { RouterState } from './router' import type { FullSearchSchema } from './routeInfo' import type { ParsedLocation } from './location' +import type { AnyRedirect } from './redirect' import type { AnyRouteMatch } from './Matches' export interface RouterReadableStore<TValue> { - get: () => TValue + readonly state: TValue } export interface RouterWritableStore< TValue, > extends RouterReadableStore<TValue> { - set: ((updater: (prev: TValue) => TValue) => void) & ((value: TValue) => void) + setState: (updater: (prev: TValue) => TValue) => void } export type RouterBatchFn = (fn: () => void) => void @@ -32,9 +34,12 @@ export type StoreConfig = { createMutableStore: MutableStoreFactory createReadonlyStore: ReadonlyStoreFactory batch: RouterBatchFn + init?: (stores: RouterStores<AnyRoute>) => void } -type MatchStore = RouterWritableStore<AnyRouteMatch | undefined> +type MatchStore = RouterWritableStore<AnyRouteMatch> & { + routeId?: string +} type ReadableStore<TValue> = RouterReadableStore<TValue> /** SSR non-reactive createMutableStore */ @@ -44,11 +49,11 @@ export function createNonReactiveMutableStore<TValue>( let value = initialValue return { - get() { + get state() { return value }, - set(nextOrUpdater: TValue | ((prev: TValue) => TValue)) { - value = functionalUpdate(nextOrUpdater, value) + setState(updater: (prev: TValue) => TValue) { + value = updater(value) }, } } @@ -58,7 +63,7 @@ export function createNonReactiveReadonlyStore<TValue>( read: () => TValue, ): RouterReadableStore<TValue> { return { - get() { + get state() { return read() }, } @@ -66,115 +71,272 @@ export function createNonReactiveReadonlyStore<TValue>( export interface RouterStores<in out TRouteTree extends AnyRoute> { status: RouterWritableStore<RouterState<TRouteTree>['status']> + loadedAt: RouterWritableStore<number> + isLoading: RouterWritableStore<boolean> + isTransitioning: RouterWritableStore<boolean> location: RouterWritableStore<ParsedLocation<FullSearchSchema<TRouteTree>>> resolvedLocation: RouterWritableStore< ParsedLocation<FullSearchSchema<TRouteTree>> | undefined > - ids: RouterWritableStore<Array<string>> - matches: ReadableStore<Array<AnyRouteMatch>> + statusCode: RouterWritableStore<number> + redirect: RouterWritableStore<AnyRedirect | undefined> + matchesId: RouterWritableStore<Array<string>> + pendingMatchesId: RouterWritableStore<Array<string>> + /** @internal */ + cachedMatchesId: RouterWritableStore<Array<string>> + activeMatchesSnapshot: ReadableStore<Array<AnyRouteMatch>> + pendingMatchesSnapshot: ReadableStore<Array<AnyRouteMatch>> + cachedMatchesSnapshot: ReadableStore<Array<AnyRouteMatch>> + firstMatchId: ReadableStore<string | undefined> + hasPendingMatches: ReadableStore<boolean> + matchRouteReactivity: ReadableStore<{ + locationHref: string + resolvedLocationHref: string | undefined + status: RouterState<TRouteTree>['status'] + }> __store: RouterReadableStore<RouterState<TRouteTree>> - byRoute: Map<string, MatchStore> + activeMatchStoresById: Map<string, MatchStore> + pendingMatchStoresById: Map<string, MatchStore> + cachedMatchStoresById: 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. + * Get a computed store that resolves a routeId to its current match state. + * Returns the same cached store instance for repeated calls with the same key. + * The computed depends on matchesId + the individual match store, so + * subscribers are only notified when the resolved match state changes. */ - getMatchStore: ( + getMatchStoreByRouteId: ( routeId: string, ) => RouterReadableStore<AnyRouteMatch | undefined> - setMatches: (nextMatches: Array<AnyRouteMatch>) => void + setActiveMatches: (nextMatches: Array<AnyRouteMatch>) => void + setPendingMatches: (nextMatches: Array<AnyRouteMatch>) => void + setCachedMatches: (nextMatches: Array<AnyRouteMatch>) => void } export function createRouterStores<TRouteTree extends AnyRoute>( - initialLocation: RouterState<TRouteTree>['location'], + initialState: RouterState<TRouteTree>, config: StoreConfig, ): RouterStores<TRouteTree> { - const { createMutableStore, createReadonlyStore, batch } = config + const { createMutableStore, createReadonlyStore, batch, init } = config // non reactive utilities - const byRoute = new Map<string, MatchStore>() + const activeMatchStoresById = new Map<string, MatchStore>() + const pendingMatchStoresById = new Map<string, MatchStore>() + const cachedMatchStoresById = 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>>([]) + const status = createMutableStore(initialState.status) + const loadedAt = createMutableStore(initialState.loadedAt) + const isLoading = createMutableStore(initialState.isLoading) + const isTransitioning = createMutableStore(initialState.isTransitioning) + const location = createMutableStore(initialState.location) + const resolvedLocation = createMutableStore(initialState.resolvedLocation) + const statusCode = createMutableStore(initialState.statusCode) + const redirect = createMutableStore(initialState.redirect) + const matchesId = createMutableStore<Array<string>>([]) + const pendingMatchesId = createMutableStore<Array<string>>([]) + const cachedMatchesId = createMutableStore<Array<string>>([]) // 1st order derived stores - const matches = createReadonlyStore(() => - ids.get().map((id) => byRoute.get(id)!.get()!), + const activeMatchesSnapshot = createReadonlyStore(() => + readPoolMatches(activeMatchStoresById, matchesId.state), ) + const pendingMatchesSnapshot = createReadonlyStore(() => + readPoolMatches(pendingMatchStoresById, pendingMatchesId.state), + ) + const cachedMatchesSnapshot = createReadonlyStore(() => + readPoolMatches(cachedMatchStoresById, cachedMatchesId.state), + ) + const firstMatchId = createReadonlyStore(() => matchesId.state[0]) + const hasPendingMatches = createReadonlyStore(() => + matchesId.state.some((matchId) => { + const store = activeMatchStoresById.get(matchId) + return store?.state.status === 'pending' + }), + ) + const matchRouteReactivity = createReadonlyStore(() => ({ + locationHref: location.state.href, + resolvedLocationHref: resolvedLocation.state?.href, + status: status.state, + })) // compatibility "big" state store const __store = createReadonlyStore(() => ({ - status: status.get(), - isLoading: status.get() === 'pending', - matches: matches.get(), - location: location.get(), - resolvedLocation: resolvedLocation.get(), + status: status.state, + loadedAt: loadedAt.state, + isLoading: isLoading.state, + isTransitioning: isTransitioning.state, + matches: activeMatchesSnapshot.state, + location: location.state, + resolvedLocation: resolvedLocation.state, + statusCode: statusCode.state, + redirect: redirect.state, })) - function getMatchStore(routeId: string): MatchStore { - let matchStore = byRoute.get(routeId) - if (!matchStore) { - matchStore = createMutableStore<AnyRouteMatch | undefined>(undefined) - byRoute.set(routeId, matchStore) + // Per-routeId computed store cache. + // Each entry resolves routeId → match state through the signal graph, + // giving consumers a single store to subscribe to instead of the + // two-level byRouteId → matchStore pattern. + // + // 64 max size is arbitrary, this is only for active matches anyway so + // it should be plenty. And we already have a 32 limit due to route + // matching bitmask anyway. + const matchStoreByRouteIdCache = createLRUCache< + string, + RouterReadableStore<AnyRouteMatch | undefined> + >(64) + + function getMatchStoreByRouteId( + routeId: string, + ): RouterReadableStore<AnyRouteMatch | undefined> { + let cached = matchStoreByRouteIdCache.get(routeId) + if (!cached) { + cached = createReadonlyStore(() => { + // Reading matchesId.state tracks it as a dependency. + // When matchesId changes (navigation), this computed re-evaluates. + const ids = matchesId.state + for (const id of ids) { + const matchStore = activeMatchStoresById.get(id) + if (matchStore && matchStore.routeId === routeId) { + // Reading matchStore.state tracks it as a dependency. + // When the match store's state changes, this re-evaluates. + return matchStore.state + } + } + return undefined + }) + matchStoreByRouteIdCache.set(routeId, cached) } - return matchStore + return cached } const store = { // atoms status, + loadedAt, + isLoading, + isTransitioning, location, resolvedLocation, - ids, + statusCode, + redirect, + matchesId, + pendingMatchesId, + cachedMatchesId, // derived - matches, + activeMatchesSnapshot, + pendingMatchesSnapshot, + cachedMatchesSnapshot, + firstMatchId, + hasPendingMatches, + matchRouteReactivity, // non-reactive state - byRoute, + activeMatchStoresById, + pendingMatchStoresById, + cachedMatchStoresById, // compatibility "big" state __store, - // stable per-route presentation atoms - getMatchStore, + // per-key computed stores + getMatchStoreByRouteId, // methods - setMatches, + setActiveMatches, + setPendingMatches, + setCachedMatches, } + // initialize the active matches + setActiveMatches(initialState.matches as Array<AnyRouteMatch>) + init?.(store) + // 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) + function setActiveMatches(nextMatches: Array<AnyRouteMatch>) { + reconcileMatchPool( + nextMatches, + activeMatchStoresById, + matchesId, + createMutableStore, + batch, + ) + } - 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) - } + function setPendingMatches(nextMatches: Array<AnyRouteMatch>) { + reconcileMatchPool( + nextMatches, + pendingMatchStoresById, + pendingMatchesId, + createMutableStore, + batch, + ) + } - 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) - } - } - }) + function setCachedMatches(nextMatches: Array<AnyRouteMatch>) { + reconcileMatchPool( + nextMatches, + cachedMatchStoresById, + cachedMatchesId, + createMutableStore, + batch, + ) } return store } + +function readPoolMatches( + pool: Map<string, MatchStore>, + ids: Array<string>, +): Array<AnyRouteMatch> { + const matches: Array<AnyRouteMatch> = [] + for (const id of ids) { + const matchStore = pool.get(id) + if (matchStore) { + matches.push(matchStore.state) + } + } + return matches +} + +function reconcileMatchPool( + nextMatches: Array<AnyRouteMatch>, + pool: Map<string, MatchStore>, + idStore: RouterWritableStore<Array<string>>, + createMutableStore: MutableStoreFactory, + batch: RouterBatchFn, +): void { + const nextIds = nextMatches.map((d) => d.id) + const nextIdSet = new Set(nextIds) + + batch(() => { + for (const id of pool.keys()) { + if (!nextIdSet.has(id)) { + pool.delete(id) + } + } + + for (const nextMatch of nextMatches) { + const existing = pool.get(nextMatch.id) + if (!existing) { + const matchStore = createMutableStore(nextMatch) as MatchStore + matchStore.routeId = nextMatch.routeId + pool.set(nextMatch.id, matchStore) + continue + } + + existing.routeId = nextMatch.routeId + if (existing.state !== nextMatch) { + existing.setState(() => nextMatch) + } + } + + if (!arraysEqual(idStore.state, nextIds)) { + idStore.setState(() => nextIds) + } + }) +} diff --git a/packages/router-core/src/utils.ts b/packages/router-core/src/utils.ts index 63aa518695..3a283e270c 100644 --- a/packages/router-core/src/utils.ts +++ b/packages/router-core/src/utils.ts @@ -193,6 +193,10 @@ 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. @@ -201,163 +205,144 @@ export function functionalUpdate<TPrevious, TResult = TPrevious>( updater: Updater<TPrevious, TResult> | NonNullableUpdater<TPrevious, TResult>, previous: TPrevious, ): TResult { - if (typeof updater === 'function') { - return (updater as Function)(previous) + if (isFunction(updater)) { + return updater(previous) } return updater } -export const hasOwn = Object.prototype.hasOwnProperty +const hasOwn = Object.prototype.hasOwnProperty +const isEnumerable = Object.prototype.propertyIsEnumerable -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. +const createNull = () => Object.create(null) export const nullReplaceEqualDeep: typeof replaceEqualDeep = (prev, next) => - replaceEqualDeep(prev, next, true) + replaceEqualDeep(prev, next, createNull) /** - * 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. + * 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 */ export function replaceEqualDeep<T>( prev: any, - next: T, - _nullProto?: boolean, - _depth?: number, -): T -export function replaceEqualDeep( - prev: any, - next: any, - _nullProto?: boolean, + _next: T, + _makeObj = () => ({}), _depth = 0, -): any { +): T { if (isServer) { - return next + return _next } - if (prev === next) { + if (prev === _next) { return prev } - if (_depth++ > 500) { - return next + if (_depth > 500) return _next + + const next = _next as any + + const array = isPlainArray(prev) && isPlainArray(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) : _makeObj() + + let equalItems = 0 + + 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 ( + p === null || + n === null || + typeof p !== 'object' || + typeof n !== 'object' + ) { + copy[key] = n + continue + } + + const v = replaceEqualDeep(p, n, _makeObj, _depth + 1) + copy[key] = v + if (v === p) equalItems++ } - const array = Array.isArray(prev) && Array.isArray(next) - - if (!array && !(isPlainObject(prev) && isPlainObject(next))) { - return next - } - - 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 i = 0 - let child: any - let previous: any - let key: any - - 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 (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 - } - } - - // 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 + return prevSize === nextSize && equalItems === prevSize ? prev : copy } -export function isPlainObject(o: unknown): boolean { - if (!o || typeof o !== 'object') { +/** + * Equivalent to `Reflect.ownKeys`, but ensures that objects are "clone-friendly": + * will return false if object has any non-enumerable properties. + * + * Optimized for the common case where objects have no symbol properties. + */ +function getEnumerableOwnKeys(o: object) { + const names = Object.getOwnPropertyNames(o) + + // Fast path: check all string property names are enumerable + for (const name of names) { + if (!isEnumerable.call(o, name)) return false + } + + // Only check symbols if the object has any (most plain objects don't) + const symbols = Object.getOwnPropertySymbols(o) + + // Fast path: no symbols, return names directly (avoids array allocation/concat) + if (symbols.length === 0) return names + + // Slow path: has symbols, need to check and merge + const keys: Array<string | symbol> = names + for (const symbol of symbols) { + if (!isEnumerable.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)) { return false } - // An own constructor is data, so classify the actual prototype. - return (Object.getPrototypeOf(o)?.constructor ?? Object) === Object + + // 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]' } /** @@ -368,48 +353,44 @@ export function isPlainArray(value: unknown): value is Array<unknown> { } /** - * 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. + * Perform a deep equality check with options for partial comparison and + * ignoring `undefined` values. Optimized for router state comparisons. */ export function deepEqual( a: any, b: any, - partial?: boolean, - explicitUndefined?: boolean, + opts?: { partial?: boolean; ignoreUndefined?: 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++) { - const av = a[i] - const bv = b[i] - if (av !== bv && !deepEqual(av, bv, partial, explicitUndefined)) { - return false - } + if (!deepEqual(a[i], b[i], opts)) return false } return true } if (isPlainObject(a) && isPlainObject(b)) { - if (partial) { + const ignoreUndefined = opts?.ignoreUndefined ?? true + + if (opts?.partial) { for (const k in b) { - if (explicitUndefined || b[k] !== undefined) { - if (!deepEqual(a[k], b[k], partial, explicitUndefined)) return false + if (!ignoreUndefined || b[k] !== undefined) { + if (!deepEqual(a[k], b[k], opts)) return false } } return true } let aCount = 0 - if (explicitUndefined) { + if (!ignoreUndefined) { aCount = Object.keys(a).length } else { for (const k in a) { @@ -417,18 +398,15 @@ export function deepEqual( } } + let bCount = 0 for (const k in b) { - if (explicitUndefined || b[k] !== undefined) { - if ( - aCount-- === 0 || - !deepEqual(a[k], b[k], partial, explicitUndefined) - ) { - return false - } + if (!ignoreUndefined || b[k] !== undefined) { + bCount++ + if (bCount > aCount || !deepEqual(a[k], b[k], opts)) return false } } - return aCount === 0 + return aCount === bCount } return false @@ -538,26 +516,15 @@ export function findLast<T>( } /** - * 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. + * Remove control characters that can cause open redirect vulnerabilities. + * Characters like \r (CR) and \n (LF) can trick URL parsers into interpreting + * paths like "/\r/evil.com" as "http://evil.com". */ -// 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'), - ) + // Remove ASCII control characters (0x00-0x1F) and DEL (0x7F) + // These include CR (\r = 0x0D), LF (\n = 0x0A), and other potentially dangerous characters + // eslint-disable-next-line no-control-regex + return segment.replace(/[\x00-\x1f\x7f]/g, '') } function decodeSegment(segment: string): string { @@ -592,51 +559,19 @@ export const DEFAULT_PROTOCOL_ALLOWLIST = [ ] /** - * Extract the explicit URL scheme, including its colon, using WHATWG - * normalization rules. This does not validate the rest of the URL. + * Check if a URL string uses a protocol that is not in the allowlist. + * Returns true for blocked protocols like javascript:, blob:, data:, etc. * - * 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 - } - 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: + * The URL constructor correctly normalizes: * - Mixed case (JavaScript: → javascript:) * - Whitespace/control characters (java\nscript: → javascript:) * - Leading whitespace * - * For relative URLs without a protocol-relative prefix, returns false. + * For relative URLs (no protocol), returns false (safe). * * @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 + * @returns true if the URL uses a protocol that is not allowed */ export function isDangerousProtocol( url: string, @@ -644,14 +579,16 @@ export function isDangerousProtocol( ): 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 + try { + // Use the URL constructor - it correctly normalizes protocols + // per WHATWG URL spec, handling all bypass attempts automatically + const parsed = new URL(url) + return !allowlist.has(parsed.protocol) + } catch { + // URL constructor throws for relative URLs (no protocol) + // These are safe - they can't execute scripts + return false } - - const scheme = getUrlScheme(url) - return scheme ? !allowlist.has(scheme) : false } // This utility is based on https://github.com/zertosh/htmlescape @@ -677,27 +614,38 @@ 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 + if (!path) return { path, handledProtocolRelativeURL: false } + + // Fast path: most paths are already decoded and safe. + // Only fall back to the slower scan/regex path when we see a '%' (encoded), + // a backslash (explicitly handled), a control character, or a protocol-relative + // prefix which needs collapsing. // 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) + if (!/[%\\\x00-\x1f\x7f]/.test(path) && !path.startsWith('//')) { + return { path, handledProtocolRelativeURL: false } } - return result + const re = /%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 + } + result = result + decodeSegment(cursor ? path.slice(cursor) : path) + + // Prevent open redirect via protocol-relative URLs (e.g. "//evil.com") + // After sanitizing control characters, paths like "/\r/evil.com" become "//evil.com" + // Collapse leading double slashes to a single slash + let handledProtocolRelativeURL = false + if (result.startsWith('//')) { + handledProtocolRelativeURL = true + result = '/' + result.replace(/^\/+/, '') + } + + return { path: result, handledProtocolRelativeURL } } /** @@ -720,12 +668,11 @@ export function decodePath(path: string) { * 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 - } + // Encode whitespace and non-ASCII characters that browsers encode in URLs + + // biome-ignore lint/suspicious/noControlCharactersInRegex: intentional ASCII range check + // eslint-disable-next-line no-control-regex + if (!/\s|[^\u0000-\u007F]/.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) diff --git a/packages/router-core/tests/RawStream.test.ts b/packages/router-core/tests/RawStream.test.ts index aa3a2aca48..106f0a7c21 100644 --- a/packages/router-core/tests/RawStream.test.ts +++ b/packages/router-core/tests/RawStream.test.ts @@ -1,100 +1,10 @@ -import { describe, expect, it, vi } from 'vitest' +import { describe, expect, it } from 'vitest' +import { toCrossJSONAsync, fromCrossJSON } from 'seroval' 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, + RawStream, 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 - }, - } -} + createRawStreamDeserializePlugin, +} from '../src/ssr/serializer/RawStream' describe('RawStream', () => { describe('RawStream class', () => { @@ -135,7 +45,7 @@ describe('RawStream', () => { }) describe('createRawStreamRPCPlugin', () => { - it('should call onRawStream callback with stream id and stream', () => { + it('should call onRawStream callback with stream id and stream', async () => { const collectedStreams = new Map<number, ReadableStream<Uint8Array>>() const plugin = createRawStreamRPCPlugin((id, stream) => { @@ -151,10 +61,9 @@ describe('RawStream', () => { const rawStream = new RawStream(testStream) - toCrossJSONStream(rawStream, { + await toCrossJSONAsync(rawStream, { refs: new Map(), plugins: [plugin], - onParse() {}, }) expect(collectedStreams.size).toBe(1) @@ -164,19 +73,15 @@ describe('RawStream', () => { expect(streamEntry![1]).toBe(testStream) }) - it('should serialize with tss/RawStream tag', () => { + it('should serialize with tss/RawStream tag', async () => { const plugin = createRawStreamRPCPlugin(() => {}) const testStream = new ReadableStream<Uint8Array>() const rawStream = new RawStream(testStream) - const serialized = new Array<unknown>() - toCrossJSONStream(rawStream, { + const serialized = await toCrossJSONAsync(rawStream, { refs: new Map(), plugins: [plugin], - onParse(value) { - serialized.push(value) - }, }) // The serialized output should have the plugin tag and contain streamId @@ -185,7 +90,7 @@ describe('RawStream', () => { expect(jsonStr).toContain('streamId') }) - it('should collect multiple streams with unique ids', () => { + it('should collect multiple streams with unique ids', async () => { const collectedStreams = new Map<number, ReadableStream<Uint8Array>>() const plugin = createRawStreamRPCPlugin((id, stream) => { @@ -200,10 +105,9 @@ describe('RawStream', () => { second: new RawStream(stream2), } - toCrossJSONStream(data, { + await toCrossJSONAsync(data, { refs: new Map(), plugins: [plugin], - onParse() {}, }) expect(collectedStreams.size).toBe(2) @@ -212,190 +116,62 @@ describe('RawStream', () => { }) }) - 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>({ + describe('createRawStreamDeserializePlugin', () => { + it('should reconstruct stream from getOrCreateStream function', () => { + const mockStream = 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.enqueue(new Uint8Array([42])) 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() + const streams = new Map<number, ReadableStream<Uint8Array>>() + streams.set(5, mockStream) - 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) + // getOrCreateStream function that returns from map + const getOrCreateStream = (id: number) => { + let stream = streams.get(id) + if (!stream) { + stream = new ReadableStream<Uint8Array>() + streams.set(id, stream) } + return stream + } - expect(actual.map((chunk) => Array.from(chunk))).toEqual( - expected.map((chunk) => Array.from(chunk)), - ) - }, - ) + const plugin = createRawStreamDeserializePlugin(getOrCreateStream) - 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 } + // Simulate seroval calling deserialize with a node + const node = { streamId: 5 } - 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 }) + // Access the deserialize function directly + const deserializedStream = (plugin as any).deserialize(node, {}) + + expect(deserializedStream).toBe(mockStream) }) + it('should create stream if not found', () => { + const streams = new Map<number, ReadableStream<Uint8Array>>() + + const getOrCreateStream = (id: number) => { + let stream = streams.get(id) + if (!stream) { + stream = new ReadableStream<Uint8Array>() + streams.set(id, stream) + } + return stream + } + + const plugin = createRawStreamDeserializePlugin(getOrCreateStream) + + const node = { streamId: 999 } + + const result = (plugin as any).deserialize(node, {}) + expect(result).toBeInstanceOf(ReadableStream) + expect(streams.get(999)).toBe(result) + }) + }) + + describe('round-trip serialization', () => { it('should serialize and deserialize RawStream correctly', async () => { // Collect streams during serialization const collectedStreams = new Map<number, ReadableStream<Uint8Array>>() @@ -417,13 +193,9 @@ describe('RawStream', () => { // Serialize using RPC plugin const refs = new Map() - let serialized: SerovalNode | undefined - toCrossJSONStream(data, { + const serialized = await toCrossJSONAsync(data, { refs, plugins: [rpcPlugin], - onParse(value) { - serialized = value - }, }) // Verify we collected the stream @@ -444,7 +216,7 @@ describe('RawStream', () => { createRawStreamDeserializePlugin(getOrCreateStream) // Deserialize - const deserialized = fromCrossJSON(serialized!, { + const deserialized = fromCrossJSON(serialized, { refs: new Map(), plugins: [deserializePlugin], }) as any @@ -453,176 +225,4 @@ describe('RawStream', () => { 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 deleted file mode 100644 index 0748895afe..0000000000 --- a/packages/router-core/tests/asset-projection-order.test.ts +++ /dev/null @@ -1,121 +0,0 @@ -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 deleted file mode 100644 index 1c39969185..0000000000 --- a/packages/router-core/tests/background-assets-stale.test.ts +++ /dev/null @@ -1,79 +0,0 @@ -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 deleted file mode 100644 index 7d23824972..0000000000 --- a/packages/router-core/tests/background-trim-abort.test.ts +++ /dev/null @@ -1,246 +0,0 @@ -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 deleted file mode 100644 index e307f35934..0000000000 --- a/packages/router-core/tests/blocked-navigation-current-load.test.ts +++ /dev/null @@ -1,75 +0,0 @@ -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 deleted file mode 100644 index e1302003d2..0000000000 --- a/packages/router-core/tests/boundary-component-chunk.test.ts +++ /dev/null @@ -1,370 +0,0 @@ -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 deleted file mode 100644 index 2b93731d2c..0000000000 --- a/packages/router-core/tests/build-location.bench.ts +++ /dev/null @@ -1,155 +0,0 @@ -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 index 99bbbc60cf..6aca9b3b6a 100644 --- a/packages/router-core/tests/build-location.test.ts +++ b/packages/router-core/tests/build-location.test.ts @@ -1,61 +1,7 @@ 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 { BaseRootRoute, BaseRoute } from '../src' 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 () => { @@ -267,571 +213,6 @@ describe('buildLocation - params function receives parsed params', () => { }) 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({ @@ -1271,32 +652,6 @@ describe('buildLocation - state', () => { }) 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 () => { @@ -1330,160 +685,6 @@ describe('buildLocation - state', () => { }) }) -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({}) @@ -1614,64 +815,6 @@ describe('buildLocation - relative paths', () => { 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({ @@ -1845,127 +988,6 @@ describe('buildLocation - basepath', () => { }) 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({ @@ -2081,242 +1103,6 @@ describe('buildLocation - params edge cases', () => { 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({ @@ -2460,28 +1246,6 @@ describe('buildLocation - location output structure', () => { 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', () => { diff --git a/packages/router-core/tests/cache-commit.bench.ts b/packages/router-core/tests/cache-commit.bench.ts deleted file mode 100644 index d570e55bf2..0000000000 --- a/packages/router-core/tests/cache-commit.bench.ts +++ /dev/null @@ -1,120 +0,0 @@ -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 deleted file mode 100644 index c7417da2e5..0000000000 --- a/packages/router-core/tests/cache-commit.test.ts +++ /dev/null @@ -1,255 +0,0 @@ -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 deleted file mode 100644 index 053aa645ac..0000000000 --- a/packages/router-core/tests/cache-navigation.bench.ts +++ /dev/null @@ -1,52 +0,0 @@ -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 7a1b062d4f..9016caced0 100644 --- a/packages/router-core/tests/callbacks.test.ts +++ b/packages/router-core/tests/callbacks.test.ts @@ -200,6 +200,10 @@ describe('callbacks', () => { )?.id expect(page2MatchId).toBeDefined() expect(page2MatchId).not.toBe(page1MatchId) + expect( + router.stores.cachedMatchesId.state.some((id) => id === page1MatchId), + ).toBe(true) + await router.navigate({ to: '/foo', search: { page: '1' } }) expect(loader).toHaveBeenCalledTimes(2) expect(router.state.matches.some((d) => d.id === page1MatchId)).toBe(true) @@ -221,6 +225,10 @@ describe('callbacks', () => { )?.id expect(post2MatchId).toBeDefined() expect(post2MatchId).not.toBe(post1MatchId) + expect( + router.stores.cachedMatchesId.state.some((id) => id === post1MatchId), + ).toBe(true) + await router.navigate({ to: '/posts/$postId', params: { postId: '1' } }) expect(loader).toHaveBeenCalledTimes(2) expect(router.state.matches.some((d) => d.id === post1MatchId)).toBe(true) diff --git a/packages/router-core/tests/chunk-failure-lifecycle.test.ts b/packages/router-core/tests/chunk-failure-lifecycle.test.ts deleted file mode 100644 index bf9fa369d4..0000000000 --- a/packages/router-core/tests/chunk-failure-lifecycle.test.ts +++ /dev/null @@ -1,82 +0,0 @@ -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 deleted file mode 100644 index 4924576759..0000000000 --- a/packages/router-core/tests/client-lane-adversarial.test.ts +++ /dev/null @@ -1,796 +0,0 @@ -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 index 641c016bb4..a924256dc2 100644 --- a/packages/router-core/tests/closing-tag-detection.bench.ts +++ b/packages/router-core/tests/closing-tag-detection.bench.ts @@ -1,7 +1,4 @@ -import { describe, test } from 'vitest' - -const BODY_END_TAG = '</body>' -const MIN_CLOSING_TAG_LENGTH = 4 +import { bench, describe } from 'vitest' /** * Benchmark comparing different approaches for finding the last closing tag in HTML chunks. @@ -203,303 +200,6 @@ function findLastClosingTagHybrid(str: string): number { 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 // ============================================================================ @@ -529,23 +229,6 @@ function generateLargeChunk(): string { return html } -function generateLargeChunkNoBody(): string { - let html = '<div class="app">' - for (let i = 0; i < 100; i++) { - html += `<div class="item item-${i}"><span class="label">Label ${i}</span><input type="text" value="${i}"/><button>Click</button></div>` - } - html += '</div>' - return html -} - -function generateUppercaseBodyChunk(): string { - return generateLargeChunk().replace('</body></html>', '</BODY></HTML>') -} - -function generateLargePlainTextBodyChunk(): string { - return '<html><body>' + 'x'.repeat(16 * 1024) + '</body></html>' -} - // Chunk with custom elements (web components) function generateWebComponentChunk(): string { let html = '<div class="app">' @@ -610,68 +293,8 @@ function verifyImplementations() { console.log('All implementations verified to produce identical results') } -function verifyBodyImplementations() { - const testCases = [ - generateLargeChunk(), - generateUppercaseBodyChunk(), - generateLargePlainTextBodyChunk(), - generateLargeChunkNoBody(), - generateNoClosingTagChunk(), - generatePartialChunk(), - '<html><body>only body</body>', - '<html><body>split</bo', - '', - ] - - for (const testCase of testCases) { - const forwardResult = findBodyEndTagForward(testCase) - const backwardResult = findBodyEndTagBackward(testCase) - const lastOpenSlashResult = findBodyEndTagLastOpenSlash(testCase) - const nativeLowerResult = - findBodyEndTagNativeLowerThenLastOpenSlash(testCase) - const combinedResult = findHtmlBoundaryCombined(testCase) - const fusedOpenSlashResult = findHtmlBoundaryLastOpenSlash(testCase) - const lazyFusedResult = findHtmlBoundaryLastOpenSlashLazy(testCase) - const lazyEncodedResult = findHtmlBoundaryLastOpenSlashLazyEncoded(testCase) - const lazyEncodedBodyEndIndex = - lazyEncodedResult < -1 ? -lazyEncodedResult - 2 : -1 - const lazyEncodedLastClosingTagEnd = - lazyEncodedResult < -1 ? -1 : lazyEncodedResult - const lastClosingTagEnd = findLastClosingTagOptimized(testCase) - - if ( - forwardResult !== backwardResult || - forwardResult !== lastOpenSlashResult || - forwardResult !== nativeLowerResult || - forwardResult !== combinedResult.bodyEndIndex || - forwardResult !== fusedOpenSlashResult.bodyEndIndex || - forwardResult !== lazyFusedResult.bodyEndIndex || - forwardResult !== lazyEncodedBodyEndIndex || - lastClosingTagEnd !== combinedResult.lastClosingTagEnd || - lastClosingTagEnd !== fusedOpenSlashResult.lastClosingTagEnd || - (forwardResult === -1 && - (lastClosingTagEnd !== lazyFusedResult.lastClosingTagEnd || - lastClosingTagEnd !== lazyEncodedLastClosingTagEnd)) - ) { - console.error('Mismatch for:', testCase.slice(0, 50)) - console.error(' Forward:', forwardResult) - console.error(' Backward:', backwardResult) - console.error(' Last </:', lastOpenSlashResult) - console.error(' Native lower:', nativeLowerResult) - console.error(' Combined:', combinedResult) - console.error(' Fused </:', fusedOpenSlashResult) - console.error(' Lazy fused </:', lazyFusedResult) - console.error(' Lazy encoded </:', lazyEncodedResult) - console.error(' Last closing:', lastClosingTagEnd) - throw new Error('Body implementation mismatch!') - } - } - console.log('All body implementations verified to produce identical results') -} - // Run verification before benchmarks verifyImplementations() -verifyBodyImplementations() // ============================================================================ // Benchmarks @@ -680,302 +303,139 @@ verifyBodyImplementations() describe('Closing Tag Detection - Small Chunk (~70 chars)', () => { const chunk = generateSmallChunk() - test('regex', async ({ bench }) => { - await bench('regex', () => { - findLastClosingTagRegex(chunk) - }).run() + bench('regex', () => { + findLastClosingTagRegex(chunk) }) - test('manual backwards scan', async ({ bench }) => { - await bench('manual backwards scan', () => { - findLastClosingTagManual(chunk) - }).run() + bench('manual backwards scan', () => { + findLastClosingTagManual(chunk) }) - test('optimized (charCodeAt)', async ({ bench }) => { - await bench('optimized (charCodeAt)', () => { - findLastClosingTagOptimized(chunk) - }).run() + bench('optimized (charCodeAt)', () => { + findLastClosingTagOptimized(chunk) }) - test('hybrid (lastIndexOf + validation)', async ({ bench }) => { - await bench('hybrid (lastIndexOf + validation)', () => { - findLastClosingTagHybrid(chunk) - }).run() + bench('hybrid (lastIndexOf + validation)', () => { + findLastClosingTagHybrid(chunk) }) }) describe('Closing Tag Detection - Medium Chunk (~1.5KB)', () => { const chunk = generateMediumChunk() - test('regex', async ({ bench }) => { - await bench('regex', () => { - findLastClosingTagRegex(chunk) - }).run() + bench('regex', () => { + findLastClosingTagRegex(chunk) }) - test('manual backwards scan', async ({ bench }) => { - await bench('manual backwards scan', () => { - findLastClosingTagManual(chunk) - }).run() + bench('manual backwards scan', () => { + findLastClosingTagManual(chunk) }) - test('optimized (charCodeAt)', async ({ bench }) => { - await bench('optimized (charCodeAt)', () => { - findLastClosingTagOptimized(chunk) - }).run() + bench('optimized (charCodeAt)', () => { + findLastClosingTagOptimized(chunk) }) - test('hybrid (lastIndexOf + validation)', async ({ bench }) => { - await bench('hybrid (lastIndexOf + validation)', () => { - findLastClosingTagHybrid(chunk) - }).run() + bench('hybrid (lastIndexOf + validation)', () => { + findLastClosingTagHybrid(chunk) }) }) describe('Closing Tag Detection - Large Chunk (~13KB)', () => { const chunk = generateLargeChunk() - test('regex', async ({ bench }) => { - await bench('regex', () => { - findLastClosingTagRegex(chunk) - }).run() + bench('regex', () => { + findLastClosingTagRegex(chunk) }) - test('manual backwards scan', async ({ bench }) => { - await bench('manual backwards scan', () => { - findLastClosingTagManual(chunk) - }).run() + bench('manual backwards scan', () => { + findLastClosingTagManual(chunk) }) - test('optimized (charCodeAt)', async ({ bench }) => { - await bench('optimized (charCodeAt)', () => { - findLastClosingTagOptimized(chunk) - }).run() + bench('optimized (charCodeAt)', () => { + findLastClosingTagOptimized(chunk) }) - test('hybrid (lastIndexOf + validation)', async ({ bench }) => { - await bench('hybrid (lastIndexOf + validation)', () => { - findLastClosingTagHybrid(chunk) - }).run() + bench('hybrid (lastIndexOf + validation)', () => { + findLastClosingTagHybrid(chunk) }) }) describe('Closing Tag Detection - Web Components', () => { const chunk = generateWebComponentChunk() - test('regex', async ({ bench }) => { - await bench('regex', () => { - findLastClosingTagRegex(chunk) - }).run() + bench('regex', () => { + findLastClosingTagRegex(chunk) }) - test('manual backwards scan', async ({ bench }) => { - await bench('manual backwards scan', () => { - findLastClosingTagManual(chunk) - }).run() + bench('manual backwards scan', () => { + findLastClosingTagManual(chunk) }) - test('optimized (charCodeAt)', async ({ bench }) => { - await bench('optimized (charCodeAt)', () => { - findLastClosingTagOptimized(chunk) - }).run() + bench('optimized (charCodeAt)', () => { + findLastClosingTagOptimized(chunk) }) - test('hybrid (lastIndexOf + validation)', async ({ bench }) => { - await bench('hybrid (lastIndexOf + validation)', () => { - findLastClosingTagHybrid(chunk) - }).run() + bench('hybrid (lastIndexOf + validation)', () => { + findLastClosingTagHybrid(chunk) }) }) describe('Closing Tag Detection - No Closing Tags (worst case for regex)', () => { const chunk = generateNoClosingTagChunk() - test('regex', async ({ bench }) => { - await bench('regex', () => { - findLastClosingTagRegex(chunk) - }).run() + bench('regex', () => { + findLastClosingTagRegex(chunk) }) - test('manual backwards scan', async ({ bench }) => { - await bench('manual backwards scan', () => { - findLastClosingTagManual(chunk) - }).run() + bench('manual backwards scan', () => { + findLastClosingTagManual(chunk) }) - test('optimized (charCodeAt)', async ({ bench }) => { - await bench('optimized (charCodeAt)', () => { - findLastClosingTagOptimized(chunk) - }).run() + bench('optimized (charCodeAt)', () => { + findLastClosingTagOptimized(chunk) }) - test('hybrid (lastIndexOf + validation)', async ({ bench }) => { - await bench('hybrid (lastIndexOf + validation)', () => { - findLastClosingTagHybrid(chunk) - }).run() + bench('hybrid (lastIndexOf + validation)', () => { + findLastClosingTagHybrid(chunk) }) }) describe('Closing Tag Detection - Nested React-like Structure', () => { const chunk = generateNestedChunk() - test('regex', async ({ bench }) => { - await bench('regex', () => { - findLastClosingTagRegex(chunk) - }).run() + bench('regex', () => { + findLastClosingTagRegex(chunk) }) - test('manual backwards scan', async ({ bench }) => { - await bench('manual backwards scan', () => { - findLastClosingTagManual(chunk) - }).run() + bench('manual backwards scan', () => { + findLastClosingTagManual(chunk) }) - test('optimized (charCodeAt)', async ({ bench }) => { - await bench('optimized (charCodeAt)', () => { - findLastClosingTagOptimized(chunk) - }).run() + bench('optimized (charCodeAt)', () => { + findLastClosingTagOptimized(chunk) }) - test('hybrid (lastIndexOf + validation)', async ({ bench }) => { - await bench('hybrid (lastIndexOf + validation)', () => { - findLastClosingTagHybrid(chunk) - }).run() + bench('hybrid (lastIndexOf + validation)', () => { + findLastClosingTagHybrid(chunk) }) }) describe('Closing Tag Detection - Partial Chunk (streaming edge case)', () => { const chunk = generatePartialChunk() - test('regex', async ({ bench }) => { - await bench('regex', () => { - findLastClosingTagRegex(chunk) - }).run() + bench('regex', () => { + findLastClosingTagRegex(chunk) }) - test('manual backwards scan', async ({ bench }) => { - await bench('manual backwards scan', () => { - findLastClosingTagManual(chunk) - }).run() + bench('manual backwards scan', () => { + findLastClosingTagManual(chunk) }) - test('optimized (charCodeAt)', async ({ bench }) => { - await bench('optimized (charCodeAt)', () => { - findLastClosingTagOptimized(chunk) - }).run() + bench('optimized (charCodeAt)', () => { + findLastClosingTagOptimized(chunk) }) - test('hybrid (lastIndexOf + validation)', async ({ bench }) => { - await bench('hybrid (lastIndexOf + validation)', () => { - findLastClosingTagHybrid(chunk) - }).run() + bench('hybrid (lastIndexOf + validation)', () => { + findLastClosingTagHybrid(chunk) }) }) - -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(</) candidates', async ({ bench }) => { - await bench('lastIndexOf(</) candidates', () => { - findBodyEndTagLastOpenSlash(chunk) - }).run() - }) - - test('native lowercase + lastIndexOf(</)', async ({ bench }) => { - 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(</) body + last closing', async ({ bench }) => { - await bench('lastIndexOf(</) body + last closing', () => { - 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(</) boundary scan', async ({ bench }) => { - await bench('fused lastIndexOf(</) boundary scan', () => { - findHtmlBoundaryLastOpenSlash(chunk) - }).run() - }) - - test('lazy fused lastIndexOf(</) boundary scan', async ({ bench }) => { - await bench('lazy fused lastIndexOf(</) boundary scan', () => { - findHtmlBoundaryLastOpenSlashLazy(chunk) - }).run() - }) - - test('lazy encoded lastIndexOf(</) boundary scan', async ({ bench }) => { - await bench('lazy encoded lastIndexOf(</) boundary scan', () => { - findHtmlBoundaryLastOpenSlashLazyEncoded(chunk) - }).run() - }) - - test('combined boundary scan', async ({ bench }) => { - await bench('combined boundary scan', () => { - findHtmlBoundaryCombined(chunk) - }).run() - }) - }) -} - -benchBodyEndTagDetection('Large Final Chunk With </body>', generateLargeChunk()) -benchBodyEndTagDetection('Uppercase </BODY>', generateUppercaseBodyChunk()) -benchBodyEndTagDetection( - 'Plain Text Body Tail (~16KB)', - generateLargePlainTextBodyChunk(), -) -benchBodyEndTagDetection( - 'Large Chunk Without </body>', - generateLargeChunkNoBody(), -) - -benchBoundaryDetection('Large Final Chunk With </body>', generateLargeChunk()) -benchBoundaryDetection( - 'Large Chunk Without </body>', - generateLargeChunkNoBody(), -) -benchBoundaryDetection('Nested Chunk Without </body>', generateNestedChunk()) diff --git a/packages/router-core/tests/curly-params-smoke.test.ts b/packages/router-core/tests/curly-params-smoke.test.ts index c566b99d2f..c52a6b33ec 100644 --- a/packages/router-core/tests/curly-params-smoke.test.ts +++ b/packages/router-core/tests/curly-params-smoke.test.ts @@ -1,6 +1,5 @@ import { describe, expect, test } from 'vitest' -import { findRouteMatch } from '../src/new-process-route-tree' -import { processTestRouteTree as processRouteTree } from './routerTestUtils' +import { findRouteMatch, processRouteTree } from '../src/new-process-route-tree' const testCases = [ { diff --git a/packages/router-core/tests/dangerous-protocols.test.ts b/packages/router-core/tests/dangerous-protocols.test.ts index 375c2f8925..1ef2b35226 100644 --- a/packages/router-core/tests/dangerous-protocols.test.ts +++ b/packages/router-core/tests/dangerous-protocols.test.ts @@ -1,39 +1,11 @@ -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 { describe, expect, it } from 'vitest' +import { DEFAULT_PROTOCOL_ALLOWLIST, isDangerousProtocol } from '../src/utils' import { redirect } from '../src/redirect' -import { BaseRootRoute, BaseRoute } from '../src' -import { createTestRouter, loadServerResponse } from './routerTestUtils' +import { BaseRootRoute } from '../src' +import { createTestRouter } 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', () => { @@ -155,7 +127,7 @@ describe('isDangerousProtocol', () => { expect(isDangerousProtocol(':::', defaultAllowlistSet)).toBe(false) expect(isDangerousProtocol('123:456', defaultAllowlistSet)).toBe(false) expect(isDangerousProtocol('//example.com', defaultAllowlistSet)).toBe( - true, + false, ) }) @@ -225,119 +197,6 @@ describe('isDangerousProtocol', () => { }) }) - describe.each([ - { name: 'default', allowlist: defaultAllowlistSet }, - { name: 'empty', allowlist: new Set<string>() }, - { - 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([ @@ -379,452 +238,6 @@ describe('redirect creation (no protocol validation)', () => { }) }) -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', diff --git a/packages/router-core/tests/deep-equal-contract.test.ts b/packages/router-core/tests/deep-equal-contract.test.ts deleted file mode 100644 index 70f0adda6f..0000000000 --- a/packages/router-core/tests/deep-equal-contract.test.ts +++ /dev/null @@ -1,111 +0,0 @@ -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<string> = [] - 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 deleted file mode 100644 index c796add1ac..0000000000 --- a/packages/router-core/tests/deep-equal.bench.ts +++ /dev/null @@ -1,166 +0,0 @@ -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 = <T>(pool: Array<T>) => 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 deleted file mode 100644 index 8dfae6d265..0000000000 --- a/packages/router-core/tests/document-navigation-blocking.test.ts +++ /dev/null @@ -1,218 +0,0 @@ -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 deleted file mode 100644 index 6c6424b01f..0000000000 --- a/packages/router-core/tests/document-navigation.test.ts +++ /dev/null @@ -1,303 +0,0 @@ -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 deleted file mode 100644 index 447dace6ea..0000000000 --- a/packages/router-core/tests/error-boundary-cache-generation.test.ts +++ /dev/null @@ -1,81 +0,0 @@ -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<void>() - 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 deleted file mode 100644 index 23df7cdcfa..0000000000 --- a/packages/router-core/tests/errorComponentProps.test-d.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { expectTypeOf, test } from 'vitest' -import type { ErrorComponentProps } from '../src' - -test('ErrorComponentProps defaults error to unknown', () => { - expectTypeOf<ErrorComponentProps['error']>().toEqualTypeOf<unknown>() - expectTypeOf<ErrorComponentProps<Error>['error']>().toEqualTypeOf<Error>() -}) diff --git a/packages/router-core/tests/fallback-route-lifecycle.bench.ts b/packages/router-core/tests/fallback-route-lifecycle.bench.ts deleted file mode 100644 index 16468d473e..0000000000 --- a/packages/router-core/tests/fallback-route-lifecycle.bench.ts +++ /dev/null @@ -1,208 +0,0 @@ -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<AnyRouteMatch>) { - const boundary = matches.findIndex( - (match) => - match.status === 'error' || - match.status === 'notFound' || - match._notFound, - ) - return boundary < 0 ? matches.length : boundary + 1 -} - -function hasLifecycleMatch( - matches: Array<AnyRouteMatch>, - 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<AnyRouteMatch>, - matches: Array<AnyRouteMatch>, - 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<string, AnyRoute>)[ - 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<string, AnyRoute>)[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<string> | 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<AnyRouteMatch> - 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<AnyRouteMatch>, - matches: Array<AnyRouteMatch>, - owner?: LoadTransaction, - ) => { - const nextEnd = (router._lifecycleEnd = lifecycleEnd(matches)) - runRouteLifecycle( - router, - previous, - matches, - previousEnd, - nextEnd, - owner, - ) - } - const originalLifecycle = ( - router: AnyRouter, - previous: Array<AnyRouteMatch>, - matches: Array<AnyRouteMatch>, - 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 deleted file mode 100644 index 3d802fa6cf..0000000000 --- a/packages/router-core/tests/fallback-route-lifecycle.test.ts +++ /dev/null @@ -1,288 +0,0 @@ -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<string> = [] - 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<void> | 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<string> = [] - 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 deleted file mode 100644 index 39c46d03ac..0000000000 --- a/packages/router-core/tests/fixtures/wpt-url/LICENSE.md +++ /dev/null @@ -1,11 +0,0 @@ -# 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 deleted file mode 100644 index 0a1774ef7d..0000000000 --- a/packages/router-core/tests/fixtures/wpt-url/README.md +++ /dev/null @@ -1,46 +0,0 @@ -# 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 deleted file mode 100644 index a3793c1f47..0000000000 --- a/packages/router-core/tests/fixtures/wpt-url/urltestdata-javascript-only.json +++ /dev/null @@ -1,18 +0,0 @@ -[ - "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 deleted file mode 100644 index aae7b1f656..0000000000 --- a/packages/router-core/tests/fixtures/wpt-url/urltestdata.json +++ /dev/null @@ -1,10643 +0,0 @@ -[ - "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://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 - }, - { - "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://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^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#foo<bar", - "base": null, - "href": "http://foo.bar/baz?qux#foo%3Cbar", - "origin": "http://foo.bar", - "protocol": "http:", - "username": "", - "password": "", - "host": "foo.bar", - "hostname": "foo.bar", - "port": "", - "pathname": "/baz", - "search": "?qux", - "searchParams": "qux=", - "hash": "#foo%3Cbar" - }, - { - "input": "http://foo.bar/baz?qux#foo>bar", - "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#<foo> <bar>", - "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#<foo> <bar>", - "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 index 89cca987b7..d459c8b418 100644 --- a/packages/router-core/tests/getNormalizedURL.test.ts +++ b/packages/router-core/tests/getNormalizedURL.test.ts @@ -2,44 +2,6 @@ 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' diff --git a/packages/router-core/tests/granular-stores.test.ts b/packages/router-core/tests/granular-stores.test.ts index 8d5b98755a..f429510b35 100644 --- a/packages/router-core/tests/granular-stores.test.ts +++ b/packages/router-core/tests/granular-stores.test.ts @@ -31,33 +31,332 @@ function createRouter() { }) } +function createLoaderRouter({ + initialEntries = ['/posts/123'], + staleTime = 0, +}: { + initialEntries?: Array<string> + staleTime?: number +} = {}) { + let resolveLoader: (() => void) | undefined + let callCount = 0 + + 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', + staleTime, + loader: () => { + callCount += 1 + + if (callCount === 1) { + return { version: 'initial' } + } + + return new Promise<{ version: string }>((resolve) => { + resolveLoader = () => resolve({ version: 'reloaded' }) + }) + }, + }) + + const routeTree = rootRoute.addChildren([indexRoute, aboutRoute, postRoute]) + + return { + router: createTestRouter({ + routeTree, + history: createMemoryHistory({ + initialEntries, + }), + }), + resolveLoader: () => resolveLoader?.(), + } +} + describe('granular stores', () => { - test('keeps ordered route state current across match generations', async () => { + test('keeps pool stores correct across active/pending/cached transitions', 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' }) + const activeMatches = router.state.matches - await router.navigate({ to: '/posts/456' }) + // Active pool contains all active matches with correct routeIds + expect(router.stores.matchesId.state).toEqual( + activeMatches.map((match) => match.id), + ) + activeMatches.forEach((match) => { + const store = router.stores.activeMatchStoresById.get(match.id) + expect(store).toBeDefined() + expect(store!.routeId).toBe(match.routeId) + // getMatchStoreByRouteId resolves to the same state + expect(router.stores.getMatchStoreByRouteId(match.routeId).state).toBe( + store!.state, + ) + }) - 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' }) + const pendingMatches = [...activeMatches].reverse().map((match, index) => ({ + ...match, + id: `${match.id}__pending_${index}`, + })) + const cachedMatches = [...activeMatches].map((match, index) => ({ + ...match, + id: `${match.id}__cached_${index}`, + })) + + router.stores.setPendingMatches(pendingMatches) + router.stores.setCachedMatches(cachedMatches) + + expect(router.stores.matchesId.state).toEqual( + activeMatches.map((match) => match.id), + ) + expect(router.stores.pendingMatchesId.state).toEqual( + pendingMatches.map((match) => match.id), + ) + expect(router.stores.cachedMatchesId.state).toEqual( + cachedMatches.map((match) => match.id), + ) + + // Pending pool has correct routeIds + pendingMatches.forEach((match) => { + const pendingStore = router.stores.pendingMatchStoresById.get(match.id) + expect(pendingStore).toBeDefined() + expect(pendingStore!.routeId).toBe(match.routeId) + // Pending match is NOT in the active pool + expect(router.stores.activeMatchStoresById.get(match.id)).toBeUndefined() + // Active pool still has a match for this routeId + expect( + router.stores.getMatchStoreByRouteId(match.routeId).state, + ).toBeDefined() + }) + + const nextActiveMatches = activeMatches.map((match, index) => ({ + ...match, + id: `${match.id}__active_next_${index}`, + })) + router.stores.setActiveMatches(nextActiveMatches) + + expect(router.stores.matchesId.state).toEqual( + nextActiveMatches.map((match) => match.id), + ) + nextActiveMatches.forEach((match) => { + const store = router.stores.activeMatchStoresById.get(match.id) + expect(store).toBeDefined() + expect(store!.routeId).toBe(match.routeId) + expect(router.stores.getMatchStoreByRouteId(match.routeId).state).toBe( + store!.state, + ) + }) + }) + + test('match store updates are isolated to the touched active match', async () => { + const router = createRouter() + await router.navigate({ to: '/posts/123' }) + + const rootMatch = router.state.matches[0] + const leafMatch = router.state.matches[1] + + expect(rootMatch).toBeDefined() + expect(leafMatch).toBeDefined() + + if (!rootMatch || !leafMatch) { + throw new Error('Expected root and leaf matches to exist') + } + + const rootStore = router.stores.activeMatchStoresById.get(rootMatch.id) + const leafStore = router.stores.activeMatchStoresById.get(leafMatch.id) + + expect(rootStore).toBeDefined() + expect(leafStore).toBeDefined() + + if (!rootStore || !leafStore) { + throw new Error('Expected root and leaf match stores to exist') + } + + const rootBefore = rootStore.state + const leafBefore = leafStore.state + + router.updateMatch(leafMatch.id, (prev) => ({ + ...prev, + status: 'pending', + })) + + expect(rootStore.state).toBe(rootBefore) + expect(leafStore.state).not.toBe(leafBefore) + expect(leafStore.state.status).toBe('pending') + }) + + test('getMatchStoreByRouteId caches store instances and clears when route is inactive', async () => { + const router = createRouter() + await router.navigate({ to: '/posts/123' }) + + const postsStore = router.stores.getMatchStoreByRouteId('/posts/$postId') + + expect(router.stores.getMatchStoreByRouteId('/posts/$postId')).toBe( + postsStore, + ) + expect(postsStore.state?.routeId).toBe('/posts/$postId') await router.navigate({ to: '/about' }) - expect(router.state.location.pathname).toBe('/about') - expect(router.state.matches.map((match) => match.routeId)).toEqual([ - '__root__', - '/about', - ]) + expect(router.stores.getMatchStoreByRouteId('/posts/$postId')).toBe( + postsStore, + ) + expect(postsStore.state).toBeUndefined() + }) + + test('no-op match pool reconciliation preserves ids and match state references', async () => { + const router = createRouter() + await router.navigate({ to: '/posts/123' }) + + const activeMatches = router.state.matches + const activeIdsBefore = router.stores.matchesId.state + const activeStoresBefore = activeMatches.map((match) => + router.stores.activeMatchStoresById.get(match.id), + ) + const activeStatesBefore = activeStoresBefore.map((store) => store?.state) + + router.stores.setActiveMatches(activeMatches) + + expect(router.stores.matchesId.state).toBe(activeIdsBefore) + expect(router.stores.activeMatchesSnapshot.state).toBe(activeMatches) + for (let i = 0; i < activeMatches.length; i++) { + const match = activeMatches[i]! + const store = router.stores.activeMatchStoresById.get(match.id) + expect(store).toBe(activeStoresBefore[i]) + expect(store?.state).toBe(activeStatesBefore[i]) + } + + const pendingMatches = activeMatches.map((match) => ({ + ...match, + id: `${match.id}__pending`, + status: 'pending' as const, + })) + + router.stores.setPendingMatches(pendingMatches) + + const pendingIdsBefore = router.stores.pendingMatchesId.state + const pendingStoresBefore = pendingMatches.map((match) => + router.stores.pendingMatchStoresById.get(match.id), + ) + const pendingStatesBefore = pendingStoresBefore.map((store) => store?.state) + + router.stores.setPendingMatches(pendingMatches) + + expect(router.stores.pendingMatchesId.state).toBe(pendingIdsBefore) + for (let i = 0; i < pendingMatches.length; i++) { + const match = pendingMatches[i]! + const store = router.stores.pendingMatchStoresById.get(match.id) + expect(store).toBe(pendingStoresBefore[i]) + expect(store?.state).toBe(pendingStatesBefore[i]) + } + }) + + test('updateMatch prefers the pending pool when active and pending share an id', async () => { + const { router, resolveLoader } = createLoaderRouter() + + await router.load() + + const activeLeaf = router.state.matches[1] + + expect(activeLeaf).toBeDefined() + + if (!activeLeaf) { + throw new Error('Expected active leaf match to exist') + } + + const activeStore = router.stores.activeMatchStoresById.get(activeLeaf.id) + + expect(activeStore).toBeDefined() + + if (!activeStore) { + throw new Error('Expected active leaf store to exist') + } + + const activeBefore = activeStore.state + + const reloadPromise = router.load() + await Promise.resolve() + + const pendingStore = router.stores.pendingMatchStoresById.get(activeLeaf.id) + + expect(pendingStore).toBeDefined() + expect(router.stores.activeMatchStoresById.get(activeLeaf.id)).toBe( + activeStore, + ) + + if (!pendingStore) { + throw new Error('Expected pending leaf store to exist') + } + + router.updateMatch(activeLeaf.id, (prev) => ({ + ...prev, + status: 'error', + error: new Error('pending-only-update'), + })) + + expect(activeStore.state).toBe(activeBefore) + expect(activeStore.state.status).toBe('success') + expect(pendingStore.state.status).toBe('error') + expect(pendingStore.state.error).toEqual(new Error('pending-only-update')) + + resolveLoader() + await reloadPromise + }) + + test('supports duplicate ids across pools without cross-pool contamination', async () => { + const router = createRouter() + await router.navigate({ to: '/posts/123' }) + + const activeLeaf = router.state.matches[1]! + const duplicatedId = activeLeaf.id + const pendingDuplicate = { + ...activeLeaf, + status: 'pending' as const, + } + const cachedDuplicate = { + ...activeLeaf, + status: 'success' as const, + } + + router.stores.setPendingMatches([pendingDuplicate]) + router.stores.setCachedMatches([cachedDuplicate]) + + router.stores.setActiveMatches( + router.state.matches.map((match) => + match.id === duplicatedId + ? { + ...match, + status: 'error' as const, + error: new Error('active-only-update'), + } + : match, + ), + ) + + expect( + router.stores.activeMatchStoresById.get(duplicatedId)?.state.status, + ).toBe('error') + expect( + router.stores.getMatchStoreByRouteId(activeLeaf.routeId).state?.status, + ).toBe('error') + // Pending pool has its own store for this id + expect( + router.stores.pendingMatchStoresById.get(duplicatedId)?.state.status, + ).toBe('pending') + expect(router.stores.pendingMatchesSnapshot.state[0]?.status).toBe( + 'pending', + ) + expect(router.stores.cachedMatchesSnapshot.state[0]?.status).toBe('success') + expect(router.getMatch(duplicatedId)?.status).toBe('success') }) }) diff --git a/packages/router-core/tests/history-normalization.test.ts b/packages/router-core/tests/history-normalization.test.ts deleted file mode 100644 index b862a35b7d..0000000000 --- a/packages/router-core/tests/history-normalization.test.ts +++ /dev/null @@ -1,215 +0,0 @@ -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<string> = [] - 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 deleted file mode 100644 index c115b8fff7..0000000000 --- a/packages/router-core/tests/hmr-refresh-lifecycle.test.ts +++ /dev/null @@ -1,411 +0,0 @@ -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<string> = [] - 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<void> | 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<void> | undefined - let router!: ReturnType<typeof createTestRouter> - 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<AbortSignal> = [] - 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<boolean>() - const firstPublished = createControlledPromise<void>() - 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<void>() - 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<boolean>() - const refreshPublished = createControlledPromise<void>() - 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<void>() - 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 deleted file mode 100644 index 05dfa5543e..0000000000 --- a/packages/router-core/tests/htmlBoundaryScanner.test.ts +++ /dev/null @@ -1,256 +0,0 @@ -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('<next>') - 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('<next>') - }) - - 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('</script><div></div></script><next>') - - const end = advanceByteMatcher(matcher, value, 0, true) - expect(new TextDecoder().decode(value.subarray(0, end))).toBe( - '</script><div></div></script>', - ) - }) - - 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 37685b48ef..e9bb82018a 100644 --- a/packages/router-core/tests/hydrate.test.ts +++ b/packages/router-core/tests/hydrate.test.ts @@ -1,38 +1,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { createMemoryHistory } from '@tanstack/history' -import { - BaseRootRoute, - BaseRoute, - _getAssetMatches, - createSerializationAdapter, - isNotFound, - notFound, -} from '../src' +import { BaseRootRoute, BaseRoute, notFound } from '../src' import { hydrate } from '../src/ssr/client' +import { createTestRouter } from './routerTestUtils' 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' - -const testManifest: ServerManifest = { - routes: {}, -} - -function createMockBootstrap( - router?: NonNullable<TsrSsrGlobal['router']>, -): TsrSsrGlobal { - return { - router, - h: vi.fn(), - e: vi.fn(), - c: vi.fn(), - p: vi.fn(), - buffer: [], - initialized: false, - } -} +import type { AnyRouteMatch } from '../src' describe('hydrate', () => { let mockWindow: { $_TSR?: TsrSsrGlobal } @@ -40,13 +13,17 @@ describe('hydrate', () => { let mockHead: any beforeEach(() => { + // Reset global window mock mockWindow = {} - vi.stubGlobal('window', mockWindow) + ;(global as any).window = mockWindow + // Reset mock head function mockHead = vi.fn() const history = createMemoryHistory({ initialEntries: ['/'] }) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ getParentRoute: () => rootRoute, path: '/', @@ -55,782 +32,417 @@ describe('hydrate', () => { head: mockHead, }) - mockRouter = createTestRouter({ - routeTree: rootRoute.addChildren([indexRoute]), - history, - isServer: false, + const otherRoute = new BaseRoute({ + getParentRoute: () => indexRoute, + path: '/other', + component: () => 'Other', }) + + const routeTree = rootRoute.addChildren([ + indexRoute.addChildren([otherRoute]), + ]) + + mockRouter = createTestRouter({ routeTree, history, isServer: true }) }) afterEach(() => { - vi.restoreAllMocks() - vi.unstubAllGlobals() + vi.resetAllMocks() + delete (global as any).window }) - it.each([ - [ - 'window.$_TSR', - () => {}, + it('should throw error if window.$_TSR is not available', async () => { + await expect(hydrate(mockRouter)).rejects.toThrow( 'Expected to find bootstrap data on window.$_TSR, but we did not. Please file an issue!', - ], - [ - 'window.$_TSR.router', - () => { - mockWindow.$_TSR = createMockBootstrap() - }, + ) + }) + + 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( '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() - - await expect(hydrate(mockRouter)).rejects.toThrow(message) - }, - ) - - 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('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, - }) - - 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 + 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: {}, }, } - 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, - }) + mockRouter.options.serializationAdapters = [mockSerializer] - mockWindow.$_TSR = await dehydrateToBootstrap(serverRouter, testManifest) + const mockMatches = [{ id: '/', routeId: '/', index: 0, _nonReactive: {} }] + mockRouter.matchRoutes = vi.fn().mockReturnValue(mockMatches) + mockRouter.state.matches = mockMatches - 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([ - { - routeId: clientRootRoute.id, - status: 'success', - loaderData: undefined, + const mockBuffer = [vi.fn(), vi.fn()] + mockWindow.$_TSR = { + router: { + manifest: { routes: {} }, + dehydratedData: {}, + lastMatchId: '/', + matches: [], }, - { - 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(), - })), - }) + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: mockBuffer, + initialized: false, + } await hydrate(mockRouter) - 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(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({ + manifest: testManifest, + }) + }) + + it('should hydrate matches', async () => { + const mockMatches = [ + { + id: '/', + routeId: '/', + index: 0, + ssr: undefined, + _nonReactive: {}, + }, + { + id: '/other', + routeId: '/other', + index: 1, + ssr: undefined, + _nonReactive: {}, + }, + ] + + const dehydratedMatches = [ + { + i: '/', + l: { indexData: 'server-data' }, + 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 hydrate globalNotFound when dehydrated flag is present', async () => { + const mockMatches = [ + { + id: '/', + routeId: '/', + index: 0, + ssr: undefined, + _nonReactive: {}, + }, + ] + + const dehydratedMatches = [ + { + i: '/', + s: 'success' as const, + ssr: true, + u: Date.now(), + g: true as const, + }, + ] + + 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) + + expect((mockMatches[0] as AnyRouteMatch).globalNotFound).toBe(true) + }) + + it('should leave globalNotFound undefined when dehydrated flag is omitted', async () => { + const mockMatches = [ + { + id: '/', + routeId: '/', + index: 0, + ssr: undefined, + _nonReactive: {}, + }, + ] + + const dehydratedMatches = [ + { + i: '/', + 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) + + expect((mockMatches[0] as AnyRouteMatch).globalNotFound).toBeUndefined() + }) + + it('should preserve existing globalNotFound when dehydrated flag is omitted', async () => { + const mockMatches = [ + { + id: '/', + routeId: '/', + index: 0, + ssr: undefined, + _nonReactive: {}, + globalNotFound: true, + }, + ] + + const dehydratedMatches = [ + { + i: '/', + 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) + + expect((mockMatches[0] as AnyRouteMatch).globalNotFound).toBe(true) + }) + + it('should decode dehydrated match ids before hydration lookup and SPA-mode checks', async () => { + const loadSpy = vi.spyOn(mockRouter, 'load') + + const mockMatches = [ + { + id: '/', + routeId: '/', + index: 0, + ssr: undefined, + _nonReactive: {}, + }, + ] + + mockRouter.matchRoutes = vi.fn().mockReturnValue(mockMatches) + mockRouter.state.matches = mockMatches + + mockWindow.$_TSR = { + router: { + manifest: { routes: {} }, + dehydratedData: {}, + lastMatchId: dehydrateSsrMatchId('/'), + matches: [ + { + i: dehydrateSsrMatchId('/'), + l: { indexData: 'server-data' }, + 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) + + expect(loadSpy).not.toHaveBeenCalled() + expect((mockRouter.state.matches[0] as AnyRouteMatch).id).toBe('/') + }) + + 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 }) + expect(consoleSpy).toHaveBeenCalledWith( + 'NotFound error during hydration for routeId: /', expect.objectContaining({ isNotFound: true, - data: { source: 'index head' }, }), ) - }) -}) -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<key', - 'back\bspace', - 'tab\tkey', - 'form\ffeed', - 'line\nbreak', - 'carriage\rreturn', - 'line\u2028separator', - 'paragraph\u2029separator', - 'unpaired-high-\ud800', - 'unpaired-low-\udc00', - 'surrogate-pair-🚀', - ]) { - expect(() => 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() - } + consoleSpy.mockRestore() }) }) diff --git a/packages/router-core/tests/hydrated-stay-match-data.test.ts b/packages/router-core/tests/hydrated-stay-match-data.test.ts deleted file mode 100644 index 6e269e86c3..0000000000 --- a/packages/router-core/tests/hydrated-stay-match-data.test.ts +++ /dev/null @@ -1,135 +0,0 @@ -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 deleted file mode 100644 index 014e338b32..0000000000 --- a/packages/router-core/tests/hydration-asset-context-order.test.ts +++ /dev/null @@ -1,75 +0,0 @@ -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<AnyRouteMatch> }) => { - 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 deleted file mode 100644 index 0d5c9a0af6..0000000000 --- a/packages/router-core/tests/hydration-boundary-chunks.test.ts +++ /dev/null @@ -1,210 +0,0 @@ -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 deleted file mode 100644 index 03ad11998b..0000000000 --- a/packages/router-core/tests/hydration-currentness.test.ts +++ /dev/null @@ -1,662 +0,0 @@ -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<string>() - 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<void>() - const hydrateStarted = createControlledPromise<void>() - 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<void>() - const oldChunkStarted = createControlledPromise<void>() - 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<boolean>() - const firstPublished = createControlledPromise<void>() - 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<void> | 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 deleted file mode 100644 index e0acbd9780..0000000000 --- a/packages/router-core/tests/hydration-terminal-error-child-head.test.ts +++ /dev/null @@ -1,206 +0,0 @@ -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 deleted file mode 100644 index 04679b3c5c..0000000000 --- a/packages/router-core/tests/hydrationQueue.bench.ts +++ /dev/null @@ -1,107 +0,0 @@ -import { describe, test } from 'vitest' - -const MAX_DYNAMIC_RECORD_CODE_UNITS = 64 * 1024 -const SOURCE_SEPARATOR = ';' -const SCRIPT_OPENING_CODE_UNITS = '<script>'.length -const DYNAMIC_CLOSE_CODE_UNITS = 'document.currentScript.remove()</script>' - .length - -function getBatchLength( - values: ReadonlyArray<string | undefined>, - 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<string>) { - 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<string | undefined>) { - 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 deleted file mode 100644 index 911e7cd78d..0000000000 --- a/packages/router-core/tests/hydrationScripts.test.ts +++ /dev/null @@ -1,808 +0,0 @@ -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<Uint8Array> = [] - while ( - output.state === HydrationScriptOutputState.Ready || - output.state === HydrationScriptOutputState.Active - ) { - chunks.push(output.pullChunk()) - } - return chunks -} - -function decodeChunks(chunks: ReadonlyArray<Uint8Array>) { - 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( - '<script>boot();late();document.currentScript.remove()</script>', - ) - 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( - '<script>first();second();document.currentScript.remove()</script>', - ) - 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( - '<script nonce="a&"'<>">first();second();document.currentScript.remove()</script>', - ) - 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( - `<script>${expected};document.currentScript.remove()</script>`, - ) - 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( - '<script>small();document.currentScript.remove()</script>', - ) - scripts.cleanup() - }) - - test('can produce a record that is exactly one maximum-sized chunk', async () => { - const prefix = '<script>' - const suffix = ';document.currentScript.remove()</script>' - 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( - `<script>${source};document.currentScript.remove()</script>` + - '<script>tail();document.currentScript.remove()</script>', - ) - 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('<script>') - .update(source) - .update(';document.currentScript.remove()</script>') - .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('<script>').byteLength + - source.length + - encoder.encode(';document.currentScript.remove()</script>').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('</script>') - ) { - 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<number> = [] - 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( - '<script>value();$_TSR.e();document.currentScript.remove()</script>', - ) - 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<number> = [] - 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('<script>').byteLength - const separatorBytes = encoder.encode(';').byteLength - const minimumSourceBytes = 17 * 1024 * 1024 - const sourceBytes = - Math.ceil( - (minimumSourceBytes + openingBytes + separatorBytes) / - MAX_HYDRATION_OUTPUT_CHUNK_BYTES, - ) * - MAX_HYDRATION_OUTPUT_CHUNK_BYTES - - openingBytes - - separatorBytes - const source = 'x'.repeat(sourceBytes) - const chunksBeforeClose = - (openingBytes + sourceBytes + separatorBytes) / - MAX_HYDRATION_OUTPUT_CHUNK_BYTES - const { scripts, output } = createReadyOutput() - - scripts.pushSource(source) - for (let index = 0; index < chunksBeforeClose; index++) { - expect(output.pullChunk()).toHaveLength(MAX_HYDRATION_OUTPUT_CHUNK_BYTES) - } - - expect(output.state).toBe(HydrationScriptOutputState.Active) - scripts.pushSource(source) - expect(output.state).toBe(HydrationScriptOutputState.Active) - expect(output.error).toBeUndefined() - - expect(decoder.decode(output.pullChunk())).toBe( - 'document.currentScript.remove()</script>', - ) - 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 deleted file mode 100644 index 084fbe8d31..0000000000 --- a/packages/router-core/tests/invalidate-pre-rematch-failure.test.ts +++ /dev/null @@ -1,63 +0,0 @@ -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<AbortSignal> = [] - - 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 deleted file mode 100644 index d9f3aff105..0000000000 --- a/packages/router-core/tests/invalidation-reserved-flight.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -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<void>() - const data = createControlledPromise<string>() - const entered = createControlledPromise<void>() - const before = createControlledPromise<void>() - 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<string, unknown>) => ({ - 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 deleted file mode 100644 index c465961dc2..0000000000 --- a/packages/router-core/tests/issue-3179-preload-cached-cause.test.ts +++ /dev/null @@ -1,59 +0,0 @@ -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 deleted file mode 100644 index a1be910314..0000000000 --- a/packages/router-core/tests/issue-3293-on-enter-after-loader.test.ts +++ /dev/null @@ -1,108 +0,0 @@ -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 deleted file mode 100644 index 6df66a08fa..0000000000 --- a/packages/router-core/tests/issue-3920-on-before-navigate-after-initial-redirect.test.ts +++ /dev/null @@ -1,41 +0,0 @@ -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<string> = [] - 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 deleted file mode 100644 index a16258be0b..0000000000 --- a/packages/router-core/tests/issue-3928-rapid-reload-abort.test.ts +++ /dev/null @@ -1,138 +0,0 @@ -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<string>((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<string, LoaderInvocation>() - const indexInvocations = new Map<string, LoaderInvocation>() - - 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<string, unknown> - const filter = typeof search.filter === 'string' ? search.filter : '' - rootInvocations.set(filter, invocation) - return promise - }, - }) - const indexRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/', - validateSearch: (search: Record<string, unknown>) => ({ - 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 deleted file mode 100644 index c33521597b..0000000000 --- a/packages/router-core/tests/issue-4078-loader-notfound-root-boundary.test.ts +++ /dev/null @@ -1,111 +0,0 @@ -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<string>) => { - const loaderStarted = createControlledPromise<void>() - const loaderResponse = createControlledPromise<void>() - 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<typeof setup>['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 deleted file mode 100644 index 9a996f9e4a..0000000000 --- a/packages/router-core/tests/issue-4444-param-parse-error-lazy-child.test.ts +++ /dev/null @@ -1,74 +0,0 @@ -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 deleted file mode 100644 index 23495e5001..0000000000 --- a/packages/router-core/tests/issue-4572-preload-root-beforeload-flags.test.ts +++ /dev/null @@ -1,173 +0,0 @@ -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 deleted file mode 100644 index 6bf84e75ce..0000000000 --- a/packages/router-core/tests/issue-4684-head-on-beforeload-error.test.ts +++ /dev/null @@ -1,84 +0,0 @@ -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 deleted file mode 100644 index 20ef368318..0000000000 --- a/packages/router-core/tests/issue-4696-parent-context-search-normalization.test.ts +++ /dev/null @@ -1,102 +0,0 @@ -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<string, unknown> }) => context, - ) - const dashboardBeforeLoad = vi.fn( - ({ context }: { context: Record<string, unknown> }) => { - 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 deleted file mode 100644 index 5ee450ee35..0000000000 --- a/packages/router-core/tests/issue-5106-hydrated-notfound-boundary.test.ts +++ /dev/null @@ -1,274 +0,0 @@ -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 deleted file mode 100644 index 0a6119b349..0000000000 --- a/packages/router-core/tests/issue-5427-hydration-root-global-not-found.test.ts +++ /dev/null @@ -1,136 +0,0 @@ -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 deleted file mode 100644 index 32539b3676..0000000000 --- a/packages/router-core/tests/issue-6107-preload-chunk-failure.test.ts +++ /dev/null @@ -1,47 +0,0 @@ -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 deleted file mode 100644 index a9f56ba8d3..0000000000 --- a/packages/router-core/tests/issue-6221-head-waits-for-loader.test.ts +++ /dev/null @@ -1,162 +0,0 @@ -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<void>() - - 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<void>() - 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<void>() - 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 deleted file mode 100644 index 9fec0992a4..0000000000 --- a/packages/router-core/tests/issue-6351-fuzzy-notfound-layout.test.ts +++ /dev/null @@ -1,142 +0,0 @@ -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<string, never> - agentsBeforeLoad?: () => Record<string, never> - 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 deleted file mode 100644 index 6f039b45da..0000000000 --- a/packages/router-core/tests/issue-6371-search-default-normalization-abort.test.ts +++ /dev/null @@ -1,96 +0,0 @@ -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<string, unknown>) => ({ - page: typeof search.page === 'number' ? search.page : 1, - }), - loader: ({ abortController }: { abortController: AbortController }) => - new Promise<string>((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 deleted file mode 100644 index 1768988e47..0000000000 --- a/packages/router-core/tests/issue-7379-head-matches-direct-load.test.ts +++ /dev/null @@ -1,81 +0,0 @@ -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 deleted file mode 100644 index 41549b58fd..0000000000 --- a/packages/router-core/tests/issue-7602-parent-beforeload-context-child-loader.test.ts +++ /dev/null @@ -1,108 +0,0 @@ -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<void>() - 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 deleted file mode 100644 index 66f76aaa33..0000000000 --- a/packages/router-core/tests/issue-7759-in-flight-preload-eviction.test.ts +++ /dev/null @@ -1,43 +0,0 @@ -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<void>((resolve) => { - signalLoaderStarted = resolve - }) - const loaderResult = new Promise<string>((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 deleted file mode 100644 index 116a527191..0000000000 --- a/packages/router-core/tests/issue-7942-repro.test.ts +++ /dev/null @@ -1,271 +0,0 @@ -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<T>() { - let resolve!: (value: T) => void - const promise = new Promise<T>((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<Uint8Array> | undefined - const cancelled = { value: false } - const encoder = new TextEncoder() - const stream = new ReadableStream<Uint8Array>({ - 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 `<script${id}>${tag.children ?? ''}</script>` -} - -function renderManagedScripts(tags: Array<RouterManagedTag>) { - 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<Uint8Array>) { - const reader = stream.getReader() - const decoder = new TextDecoder() - const chunks: Array<string> = [] - const chunkSizes: Array<number> = [] - 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<string>() - 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 = - `<html><body>${renderManagedScripts([ - ...initialScripts.before, - initialScripts.boundary, - ])}` + `<main>app</main>` - 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 = '</body></html>' - upstream.push(tail) - upstream.close() - - const result = await outputPromise - const renderedInitialScripts = renderManagedScripts([ - ...initialScripts.before, - initialScripts.boundary, - ]) - const earliestInjectionOffset = - '<html><body>'.length + renderedInitialScripts.length - const payloadOffset = result.text.indexOf(payload) - const injectedStart = result.text.lastIndexOf('<script>', payloadOffset) - const dynamicClose = 'document.currentScript.remove()</script>' - 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<string>(), - ) - 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( - `<html><body>${renderManagedScripts([ - ...initialScripts.before, - initialScripts.boundary, - ])}<main>app</main>`, - ) - 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/legacy-not-found-interpolation.test.ts b/packages/router-core/tests/legacy-not-found-interpolation.test.ts deleted file mode 100644 index 4f524c68a3..0000000000 --- a/packages/router-core/tests/legacy-not-found-interpolation.test.ts +++ /dev/null @@ -1,105 +0,0 @@ -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<AnyRoute>({ - 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 deleted file mode 100644 index 12767c5a97..0000000000 --- a/packages/router-core/tests/lifecycle-dispatch.test.ts +++ /dev/null @@ -1,82 +0,0 @@ -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<string> = [] - const owner = {} as LoadTransaction - const matches = ['parent', 'child'].map((routeId) => ({ - routeId, - status: 'success', - })) as Array<AnyRouteMatch> - 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<string> = [] - const previous = [ - { routeId: 'parent', status: 'notFound' }, - { routeId: 'child', status: 'success' }, - ] as Array<AnyRouteMatch> - 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 deleted file mode 100644 index 44f70c9d53..0000000000 --- a/packages/router-core/tests/lightweight-location.bench.ts +++ /dev/null @@ -1,66 +0,0 @@ -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 deleted file mode 100644 index fdf5397a16..0000000000 --- a/packages/router-core/tests/load-client-wait-for.test.ts +++ /dev/null @@ -1,377 +0,0 @@ -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<never>((_, 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<never> = { - 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<string>((resolve) => { - resolveFirst = resolve - }) - const second = new Promise<string>((_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<string>((resolve) => { - resolveFirst = resolve - }) - const second = new Promise<string>((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<string>((resolve) => { - resolveFirst = resolve - }) - const second = new Promise<string>((_, reject) => { - rejectSecond = reject - }) - const third = new Promise<string>((_, 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<string>((resolve) => { - resolveFirst = resolve - }) - const second = new Promise<string>((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<string>((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<unknown> = [] - 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<unknown>) => { - 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<void>((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 deleted file mode 100644 index 73179f9f32..0000000000 --- a/packages/router-core/tests/load-route-chunk.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -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 484e8d0e71..142fea1fe1 100644 --- a/packages/router-core/tests/load.test.ts +++ b/packages/router-core/tests/load.test.ts @@ -3,13 +3,14 @@ import { createMemoryHistory } from '@tanstack/history' import { BaseRootRoute, BaseRoute, - createControlledPromise, notFound, redirect, rootRouteId, } from '../src' -import { createTestRouter, loadServerResponse } from './routerTestUtils' +import { createTestRouter } from './routerTestUtils' +import { loadMatches } from '../src/load-matches' import type { + AnyRouter, LoaderStaleReloadMode, RootRouteOptions, RouterCore, @@ -69,306 +70,16 @@ describe('redirect resolution', () => { isServer: true, }) - const response = await loadServerResponse(router, initialPath) + await router.load() - 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/), + expect(router.state.redirect).toEqual( + expect.objectContaining({ + options: expect.objectContaining({ href: '/undefined' }), }), - }) + ) + expect(router.state.redirect?.headers.get('Location')).toBe('/undefined') }, ) - - 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', () => { @@ -406,7 +117,12 @@ describe('beforeLoad skip or exec', () => { test('exec on regular nav', async () => { const beforeLoad = vi.fn(() => Promise.resolve({ hello: 'world' })) const router = setup({ beforeLoad }) - await router.navigate({ to: '/foo' }) + const navigation = router.navigate({ to: '/foo' }) + expect(beforeLoad).toHaveBeenCalledTimes(1) + expect(router.stores.pendingMatchesSnapshot.state).toEqual( + expect.arrayContaining([expect.objectContaining({ id: '/foo/foo' })]), + ) + await navigation expect(router.state.location.pathname).toBe('/foo') expect(router.state.matches).toEqual( expect.arrayContaining([ @@ -421,48 +137,16 @@ describe('beforeLoad skip or exec', () => { expect(beforeLoad).toHaveBeenCalledTimes(1) }) - test('preserves primitive errors thrown from beforeLoad', async () => { - const beforeLoad = vi.fn<BeforeLoad>(() => { - 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<BeforeLoad>(() => { - 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.stores.cachedMatchesSnapshot.state).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) }) @@ -471,9 +155,11 @@ describe('beforeLoad skip or exec', () => { const router = setup({ beforeLoad }) router.preloadRoute({ to: '/foo' }) await Promise.resolve() + expect(router.stores.cachedMatchesSnapshot.state).toEqual( + expect.arrayContaining([expect.objectContaining({ id: '/foo/foo' })]), + ) await router.navigate({ to: '/foo' }) - expect(router.state.location.pathname).toBe('/foo') expect(beforeLoad).toHaveBeenCalledTimes(2) }) @@ -516,11 +202,20 @@ describe('beforeLoad skip or exec', () => { beforeLoad, }) await router.preloadRoute({ to: '/foo' }) + expect( + router.stores.cachedMatchesSnapshot.state.some( + (d) => d.status === 'redirected', + ), + ).toBe(false) await sleep(10) await router.navigate({ to: '/foo' }) expect(router.state.location.pathname).toBe('/foo') - expect(router.state.matches.at(-1)?.status).toBe('success') + expect( + router.stores.cachedMatchesSnapshot.state.some( + (d) => d.status === 'redirected', + ), + ).toBe(false) expect(beforeLoad).toHaveBeenCalledTimes(2) }) @@ -534,10 +229,19 @@ describe('beforeLoad skip or exec', () => { }) router.preloadRoute({ to: '/foo' }) await Promise.resolve() + expect( + router.stores.cachedMatchesSnapshot.state.some( + (d) => d.status === 'redirected', + ), + ).toBe(false) await router.navigate({ to: '/foo' }) expect(router.state.location.pathname).toBe('/foo') - expect(router.state.matches.at(-1)?.status).toBe('success') + expect( + router.stores.cachedMatchesSnapshot.state.some( + (d) => d.status === 'redirected', + ), + ).toBe(false) expect(beforeLoad).toHaveBeenCalledTimes(2) }) @@ -556,41 +260,6 @@ describe('beforeLoad skip or exec', () => { expect(beforeLoad).toHaveBeenCalledTimes(2) }) - test('skip child beforeLoad when parent beforeLoad throws during preload', async () => { - const parentBeforeLoad = vi.fn<BeforeLoad>(async ({ preload }) => { - if (preload) throw new Error('parent error') - }) - const childBeforeLoad = vi.fn<BeforeLoad>() - 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<BeforeLoad>(async ({ preload }) => { await sleep(100) @@ -653,7 +322,12 @@ describe('loader skip or exec', () => { test('exec on regular nav', async () => { const loader = vi.fn(() => Promise.resolve({ hello: 'world' })) const router = setup({ loader }) - await router.navigate({ to: '/foo' }) + const navigation = router.navigate({ to: '/foo' }) + expect(loader).toHaveBeenCalledTimes(1) + expect(router.stores.pendingMatchesSnapshot.state).toEqual( + expect.arrayContaining([expect.objectContaining({ id: '/foo/foo' })]), + ) + await navigation expect(router.state.location.pathname).toBe('/foo') expect(router.state.matches).toEqual( expect.arrayContaining([ @@ -672,21 +346,25 @@ describe('loader skip or exec', () => { const loader = vi.fn() const router = setup({ loader }) await router.preloadRoute({ to: '/foo' }) + expect(router.stores.cachedMatchesSnapshot.state).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) + expect(loader).toHaveBeenCalledTimes(2) }) 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.stores.cachedMatchesSnapshot.state).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) }) @@ -695,9 +373,11 @@ describe('loader skip or exec', () => { const router = setup({ loader }) router.preloadRoute({ to: '/foo' }) await Promise.resolve() + expect(router.stores.cachedMatchesSnapshot.state).toEqual( + expect.arrayContaining([expect.objectContaining({ id: '/foo/foo' })]), + ) await router.navigate({ to: '/foo' }) - expect(router.state.location.pathname).toBe('/foo') expect(loader).toHaveBeenCalledTimes(1) }) @@ -716,35 +396,19 @@ describe('loader skip or exec', () => { expect(loader).toHaveBeenCalledTimes(2) }) - test('navigation shares a pending preload loader notFound', async () => { - const loaderGate = createControlledPromise<void>() + test('skip if pending preload (notFound)', async () => { const loader: Loader = vi.fn(async ({ preload }) => { - await loaderGate + await sleep(100) if (preload) throw notFound() }) const router = setup({ loader, }) - const preload = router.preloadRoute({ to: '/foo' }) - await vi.waitFor(() => expect(loader).toHaveBeenCalledOnce()) - - const navigation = router.navigate({ to: '/foo' }) + router.preloadRoute({ to: '/foo' }) await Promise.resolve() - expect(loader).toHaveBeenCalledOnce() + await router.navigate({ to: '/foo' }) - 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() + expect(loader).toHaveBeenCalledTimes(1) }) test('exec if rejected preload (redirect)', async () => { @@ -756,15 +420,24 @@ describe('loader skip or exec', () => { loader, }) await router.preloadRoute({ to: '/foo' }) + expect( + router.stores.cachedMatchesSnapshot.state.some( + (d) => d.status === 'redirected', + ), + ).toBe(false) await sleep(10) await router.navigate({ to: '/foo' }) expect(router.state.location.pathname).toBe('/foo') - expect(router.state.matches.at(-1)?.status).toBe('success') + expect( + router.stores.cachedMatchesSnapshot.state.some( + (d) => d.status === 'redirected', + ), + ).toBe(false) expect(loader).toHaveBeenCalledTimes(2) }) - test('exec if pending preload redirects', async () => { + test('skip if pending preload (redirect)', async () => { const loader: Loader = vi.fn(async ({ preload }) => { await sleep(100) if (preload) throw redirect({ to: '/bar' }) @@ -774,13 +447,48 @@ describe('loader skip or exec', () => { }) router.preloadRoute({ to: '/foo' }) await Promise.resolve() + expect( + router.stores.cachedMatchesSnapshot.state.some( + (d) => d.status === 'redirected', + ), + ).toBe(false) await router.navigate({ to: '/foo' }) expect(router.state.location.pathname).toBe('/bar') - expect(router.state.matches.at(-1)?.status).toBe('success') + expect( + router.stores.cachedMatchesSnapshot.state.some( + (d) => d.status === 'redirected', + ), + ).toBe(false) expect(loader).toHaveBeenCalledTimes(1) }) + test('updateMatch removes redirected matches from cachedMatches', async () => { + const loader = vi.fn() + const router = setup({ loader }) + + await router.preloadRoute({ to: '/foo' }) + expect(router.stores.cachedMatchesSnapshot.state).toEqual( + expect.arrayContaining([expect.objectContaining({ id: '/foo/foo' })]), + ) + + router.updateMatch('/foo/foo', (prev) => ({ + ...prev, + status: 'redirected', + })) + + expect( + router.stores.cachedMatchesSnapshot.state.some( + (d) => d.id === '/foo/foo', + ), + ).toBe(false) + expect( + router.stores.cachedMatchesSnapshot.state.some( + (d) => d.status === 'redirected', + ), + ).toBe(false) + }) + test('exec if rejected preload (error)', async () => { const loader: Loader = vi.fn(async ({ preload }) => { if (preload) throw new Error('error') @@ -796,33 +504,19 @@ describe('loader skip or exec', () => { expect(loader).toHaveBeenCalledTimes(2) }) - test('navigation shares a pending preload loader error', async () => { - const loaderGate = createControlledPromise<void>() - const failure = new Error('preload failed') + test('skip if pending preload (error)', async () => { const loader: Loader = vi.fn(async ({ preload }) => { - await loaderGate - if (preload) throw failure + await sleep(100) + if (preload) throw new Error('error') }) const router = setup({ loader, }) - const preload = router.preloadRoute({ to: '/foo' }) - await vi.waitFor(() => expect(loader).toHaveBeenCalledOnce()) - - const navigation = router.navigate({ to: '/foo' }) + router.preloadRoute({ to: '/foo' }) await Promise.resolve() - expect(loader).toHaveBeenCalledOnce() + await router.navigate({ to: '/foo' }) - 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() + expect(loader).toHaveBeenCalledTimes(1) }) }) @@ -917,13 +611,26 @@ describe('stale loader reload triggers', () => { const getMatchById = ( router: RouterCore<any, any, any, any, any>, id: string, - ) => router.state.matches.find((match) => match.id === id) + ) => + router.state.matches.find((match) => match.id === id) ?? + router.stores.pendingMatchesSnapshot.state.find( + (match) => match.id === id, + ) ?? + router.stores.cachedMatchesSnapshot.state.find((match) => match.id === id) const hasActiveMatch = ( router: RouterCore<any, any, any, any, any>, id: string, ) => router.state.matches.some((match) => match.id === id) + const hasPendingMatch = ( + router: RouterCore<any, any, any, any, any>, + id: string, + ) => + router.stores.pendingMatchesSnapshot.state.some( + (match) => match.id === id, + ) ?? false + const setup = ({ loader, staleTime, @@ -993,30 +700,24 @@ describe('stale loader reload triggers', () => { await router.navigate({ to: '/bar' }) await vi.advanceTimersByTimeAsync(1) - let revisitSettled = false - const revisit = router.navigate({ to: '/foo' }).then(() => { - revisitSettled = true - }) + const revisit = router.navigate({ to: '/foo' }) + await Promise.resolve() - await vi.waitFor(() => { - expect(loader).toHaveBeenCalledTimes(2) - }) - expect(revisitSettled).toBe(false) - expect(router.state.status).toBe('pending') - expect(router.state.isLoading).toBe(true) + expect(loader).toHaveBeenCalledTimes(2) expect(hasActiveMatch(router, '/bar/bar')).toBe(true) expect(hasActiveMatch(router, '/foo/foo')).toBe(false) + expect(hasPendingMatch(router, '/foo/foo')).toBe(true) + expect(getMatchById(router, '/foo/foo')?.loaderData).toEqual({ + value: 'first', + }) 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(hasPendingMatch(router, '/foo/foo')).toBe(false) expect(router.state.location.pathname).toBe('/foo') - expect(router.state.resolvedLocation?.pathname).toBe('/foo') expect(getMatchById(router, '/foo/foo')?.loaderData).toEqual({ value: 'second', }) @@ -1034,28 +735,27 @@ describe('stale loader reload triggers', () => { await router.navigate({ to: '/bar' }) await vi.advanceTimersByTimeAsync(1) - let revisitSettled = false - const revisit = router.navigate({ to: '/foo' }).then(() => { - revisitSettled = true - }) - await revisit + const revisit = router.navigate({ to: '/foo' }) - expect(revisitSettled).toBe(true) - expect(router.state.status).toBe('idle') - expect(router.state.isLoading).toBe(false) expect(loader).toHaveBeenCalledTimes(2) + + await revisit + const backgroundReloadPromise = getMatchById(router, '/foo/foo') + ?._nonReactive.loaderPromise + + expect(backgroundReloadPromise).toBeDefined() expect(hasActiveMatch(router, '/foo/foo')).toBe(true) + expect(hasPendingMatch(router, '/foo/foo')).toBe(false) 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', - }) + await backgroundReloadPromise + + expect(getMatchById(router, '/foo/foo')?.loaderData).toEqual({ + value: 'second', }) } @@ -1117,7 +817,7 @@ describe('stale loader reload triggers', () => { expect(loader).toHaveBeenCalledTimes(2) }) - test('reuses a fresh preloaded loader when switching to a different match id of the same route', async () => { + test('reloads a stale 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 })) @@ -1175,8 +875,8 @@ describe('stale loader reload triggers', () => { search: { page: '2' }, }) - expect(rootLoader).toHaveBeenCalledTimes(2) - expect(childLoader).toHaveBeenCalledTimes(2) + expect(rootLoader).toHaveBeenCalledTimes(3) + expect(childLoader).toHaveBeenCalledTimes(3) }) test('skips stale ancestor loader when only a child path param changes', async () => { @@ -1371,23 +1071,24 @@ describe('stale loader reload triggers', () => { }) }) -test('navigating away from a pending route aborts its loader', async () => { - let loaderSignal: AbortSignal | undefined +test('cancelMatches after pending timeout', async () => { + const WAIT_TIME = 5 + const onAbortMock = vi.fn() const rootRoute = new BaseRootRoute({}) const fooRoute = new BaseRoute({ getParentRoute: () => rootRoute, path: '/foo', - pendingMs: 0, + pendingMs: WAIT_TIME * 20, loader: async ({ abortController }) => { - loaderSignal = abortController.signal await new Promise<void>((resolve) => { - abortController.signal.addEventListener( - 'abort', - () => { - resolve() - }, - { once: true }, - ) + const timer = setTimeout(() => { + resolve() + }, WAIT_TIME * 40) + abortController.signal.addEventListener('abort', () => { + onAbortMock() + clearTimeout(timer) + resolve() + }) }) }, pendingComponent: {}, @@ -1400,36 +1101,26 @@ test('navigating away from a pending route aborts its loader', async () => { const router = createTestRouter({ routeTree, history: createMemoryHistory() }) await router.load() - const fooNavigation = router.navigate({ to: '/foo' }) + router.navigate({ to: '/foo' }) + await sleep(WAIT_TIME * 30) - await vi.waitFor(() => { - expect(loaderSignal).toBeDefined() - expect(router.state.matches.at(-1)).toMatchObject({ - routeId: fooRoute.id, - status: 'pending', - }) - }) + // At this point, pending timeout should have triggered + const fooMatch = router.getMatch('/foo/foo') + expect(fooMatch).toBeDefined() + // Navigate away, which should cancel the pending match await router.navigate({ to: '/bar' }) - await fooNavigation + await router.latestLoadPromise 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> = [] @@ -1506,12 +1197,14 @@ describe('head execution', () => { const heads = routes.map( (route) => route.options.head as ReturnType<typeof makeHead>, ) + return { router, routes, loaders, heads, loaderResolvers, + throwAtIndex, } } @@ -1527,27 +1220,26 @@ describe('head execution', () => { await Promise.resolve() await Promise.resolve() + for (let i = 0; i < routes.length; i++) { + const loader = loaders[i]! + const expectedCalls = i < throwAtIndex ? 1 : 0 + expect(loader).toHaveBeenCalledTimes(expectedCalls) + } + 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++) { + expect(loaderResolvers[i]).toBeDefined() 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 < heads.length; i++) { + const head = heads[i]! + const expectedCalls = i <= throwAtIndex ? 1 : 0 + expect(head).toHaveBeenCalledTimes(expectedCalls) + } for (let i = 0; i < throwAtIndex; i++) { const route = routes[i]! @@ -1568,7 +1260,7 @@ describe('head execution', () => { }) }) - test('projects head when loader throws notFound', async () => { + test('executes head once when loader throws notFound', async () => { const head = vi.fn(() => ({ meta: [{ title: 'Test' }] })) const rootRoute = new BaseRootRoute({}) const testRoute = new BaseRoute({ @@ -1587,16 +1279,16 @@ describe('head execution', () => { await router.load() + expect(head).toHaveBeenCalledTimes(1) 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, @@ -1604,6 +1296,7 @@ describe('head execution', () => { const childLoader = vi.fn(() => ({ level: 1 })) const childHead = vi.fn(() => ({ meta: [{ title: 'Child' }] })) + const childRoute = new BaseRoute({ getParentRoute: () => rootRoute, path: '/test', @@ -1620,17 +1313,23 @@ describe('head execution', () => { history: createMemoryHistory({ initialEntries: ['/test'] }), }) - await router.load() + const location = router.latestLocation + const matches = router.matchRoutes(location) + router.stores.setPendingMatches(matches) - expect( - router.state.matches.find((match) => match.routeId === childRoute.id) - ?.error, - ).toBe(beforeLoadError) + await expect( + loadMatches({ + router, + location, + matches, + updateMatch: router.updateMatch, + }), + ).rejects.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(childLoader).toHaveBeenCalledTimes(0) + // Head functions still run for ancestors up to the erroring match so that + // SSR produces valid <head> content (e.g. charset, viewport, stylesheets). expect(rootHead).toHaveBeenCalledTimes(1) expect(childHead).toHaveBeenCalledTimes(1) }) @@ -1639,6 +1338,7 @@ describe('head execution', () => { 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, @@ -1646,6 +1346,7 @@ describe('head execution', () => { const childLoader = vi.fn(() => ({ level: 1 })) const childHead = vi.fn(() => ({ meta: [{ title: 'Child' }] })) + const childRoute = new BaseRoute({ getParentRoute: () => rootRoute, path: '/test', @@ -1663,17 +1364,23 @@ describe('head execution', () => { history: createMemoryHistory({ initialEntries: ['/test'] }), }) - await router.load() + const location = router.latestLocation + const matches = router.matchRoutes(location) + router.stores.setPendingMatches(matches) - expect( - router.state.matches.find((match) => match.routeId === childRoute.id) - ?.error, - ).toBe(beforeLoadError) + await expect( + loadMatches({ + router, + location, + matches, + updateMatch: router.updateMatch, + }), + ).rejects.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(childLoader).toHaveBeenCalledTimes(0) + // Head functions still run for ancestors up to the erroring match so that + // SSR produces valid <head> content (e.g. charset, viewport, stylesheets). expect(rootHead).toHaveBeenCalledTimes(1) expect(childHead).toHaveBeenCalledTimes(1) }) @@ -1686,47 +1393,40 @@ describe('head execution', () => { name: string throwAtIndex: ThrowAtIndex parentFailures: ParentFailureMap - expectedErrorKind: 'notFound' | 'redirect' + expectedErrorKind: 'notFound' | 'redirect' | 'error' expectedErrorSource?: string - expectedBoundaryIndex?: 0 | 1 | 2 | 3 - expectedLoaderCount: number - expectedHeadTitles: Array<string> + expectedErrorRouteIndex?: 0 | 1 | 2 | 3 + expectedLoaderMaxIndex: number + expectedRenderedHeadMaxIndex: number + withDefaultNotFoundComponent?: boolean beforeLoadNotFoundFactory?: ( routes: readonly [any, any, any, any], ) => ReturnType<typeof notFound> + expectRootNotFoundComponentAssigned?: boolean } const setupScenario = ({ throwAtIndex, parentFailures, beforeLoadNotFoundFactory, - skipRootLoaderOnReload = false, + withDefaultNotFoundComponent, }: { throwAtIndex: ThrowAtIndex parentFailures: ParentFailureMap beforeLoadNotFoundFactory?: Scenario['beforeLoadNotFoundFactory'] - skipRootLoaderOnReload?: boolean + withDefaultNotFoundComponent?: 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`) - } + vi.fn(() => { + 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' }) } return { level: index } }) @@ -1734,9 +1434,6 @@ describe('head execution', () => { const rootRoute = new BaseRootRoute({ loader: makeLoader(0), head: makeHead('Root'), - ...(skipRootLoaderOnReload - ? { staleTime: Infinity, shouldReload: () => false } - : {}), }) const level1Route = new BaseRoute({ @@ -1771,12 +1468,14 @@ describe('head execution', () => { ]) const routes = [rootRoute, level1Route, level2Route, level3Route] as const - const loaders = routes.map( - (route) => route.options.loader as ReturnType<typeof makeLoader>, - ) - const heads = routes.map( - (route) => route.options.head as ReturnType<typeof makeHead>, - ) + + ;([0, 1, 2] as const).forEach((index) => { + if (parentFailures[index] === 'error') { + ;(routes[index].options as any).shouldReload = () => { + throw new Error(`loader-${index}-error`) + } + } + }) const throwRoute = routes[throwAtIndex]! throwRoute.options.beforeLoad = () => { @@ -1791,8 +1490,18 @@ describe('head execution', () => { history: createMemoryHistory({ initialEntries: ['/level-1/level-2/level-3'], }), + ...(withDefaultNotFoundComponent + ? { defaultNotFoundComponent: () => null } + : {}), }) + const loaders = routes.map( + (route) => route.options.loader as ReturnType<typeof makeLoader>, + ) + const heads = routes.map( + (route) => route.options.head as ReturnType<typeof makeHead>, + ) + return { router, routes, @@ -1801,6 +1510,24 @@ describe('head execution', () => { } } + const runLoadMatchesAndCapture = async (router: AnyRouter) => { + const location = router.latestLocation + const matches = router.matchRoutes(location) + router.stores.setPendingMatches(matches) + + try { + await loadMatches({ + router, + location, + matches, + updateMatch: router.updateMatch, + }) + return { error: undefined, matches } + } catch (error) { + return { error, matches } + } + } + const scenarios = [ { name: 'throws beforeLoad notFound when parent loaders succeed', @@ -1808,39 +1535,35 @@ describe('head execution', () => { parentFailures: {} as ParentFailureMap, expectedErrorKind: 'notFound' as const, expectedErrorSource: 'beforeLoad-3', - expectedBoundaryIndex: 3, - expectedLoaderCount: 3, - expectedHeadTitles: ['Root', 'Level 1', 'Level 2', 'Level 3'], + expectedLoaderMaxIndex: 2, + expectedRenderedHeadMaxIndex: 3, }, { - name: 'promotes a fresh parent loader notFound above a serial child notFound', + name: 'uses parent loader notFound when parent loader throws 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'], + expectedLoaderMaxIndex: 2, + expectedRenderedHeadMaxIndex: 1, }, { - name: 'promotes the first fresh parent loader failure above a serial child notFound', + name: 'uses first parent loader notFound when multiple parent loaders throw 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'], + expectedLoaderMaxIndex: 2, + expectedRenderedHeadMaxIndex: 1, }, { - name: 'promotes a fresh root loader notFound above a serial child notFound', + name: 'uses parent loader notFound when root loader throws notFound', throwAtIndex: 2 as const, parentFailures: { 0: 'notFound' } as ParentFailureMap, expectedErrorKind: 'notFound' as const, expectedErrorSource: 'loader-0', - expectedBoundaryIndex: 0, - expectedLoaderCount: 2, - expectedHeadTitles: ['Root'], + expectedLoaderMaxIndex: 1, + expectedRenderedHeadMaxIndex: 0, }, { name: 'uses explicit routeId from beforeLoad notFound to target ancestor boundary', @@ -1848,9 +1571,9 @@ describe('head execution', () => { parentFailures: {} as ParentFailureMap, expectedErrorKind: 'notFound' as const, expectedErrorSource: 'beforeLoad-explicit-level1', - expectedBoundaryIndex: 1, - expectedLoaderCount: 2, - expectedHeadTitles: ['Root', 'Level 1'], + expectedErrorRouteIndex: 1, + expectedLoaderMaxIndex: 1, + expectedRenderedHeadMaxIndex: 1, beforeLoadNotFoundFactory: (routes) => notFound({ routeId: routes[1].id as never, @@ -1863,9 +1586,8 @@ describe('head execution', () => { parentFailures: {} as ParentFailureMap, expectedErrorKind: 'notFound' as const, expectedErrorSource: 'beforeLoad-invalid-route', - expectedBoundaryIndex: 0, - expectedLoaderCount: 1, - expectedHeadTitles: ['Root'], + expectedLoaderMaxIndex: 0, + expectedRenderedHeadMaxIndex: 0, beforeLoadNotFoundFactory: () => notFound({ routeId: '/does-not-exist' as never, @@ -1878,23 +1600,38 @@ describe('head execution', () => { parentFailures: {} as ParentFailureMap, expectedErrorKind: 'notFound' as const, expectedErrorSource: 'beforeLoad-non-exact-route', - expectedBoundaryIndex: 0, - expectedLoaderCount: 1, - expectedHeadTitles: ['Root'], + expectedLoaderMaxIndex: 0, + expectedRenderedHeadMaxIndex: 0, beforeLoadNotFoundFactory: (routes) => notFound({ routeId: `${routes[1].id}/` as never, data: { source: 'beforeLoad-non-exact-route' }, }), }, + { + name: 'assigns defaultNotFoundComponent on root when unknown routeId falls back to root', + throwAtIndex: 3 as const, + parentFailures: {} as ParentFailureMap, + expectedErrorKind: 'notFound' as const, + expectedErrorSource: 'beforeLoad-invalid-route-default', + expectedLoaderMaxIndex: 0, + expectedRenderedHeadMaxIndex: 0, + withDefaultNotFoundComponent: true, + expectRootNotFoundComponentAssigned: true, + beforeLoadNotFoundFactory: () => + notFound({ + routeId: '/does-not-exist' as never, + data: { source: 'beforeLoad-invalid-route-default' }, + }), + }, { 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'], + expectedLoaderMaxIndex: 2, + expectedRenderedHeadMaxIndex: -1, }, { name: 'prioritizes redirect over root-loader notFound when both appear in settled loaders', @@ -1902,18 +1639,17 @@ describe('head execution', () => { parentFailures: { 0: 'notFound', 1: 'redirect' } as ParentFailureMap, expectedErrorKind: 'redirect' as const, expectedErrorSource: undefined, - expectedLoaderCount: 3, - expectedHeadTitles: ['Root'], + expectedLoaderMaxIndex: 2, + expectedRenderedHeadMaxIndex: -1, }, { - name: 'promotes the first fresh parent failure when later loaders fail differently', + name: 'propagates regular loader error when mixed with loader notFound in settled loaders', 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'], + expectedErrorKind: 'error' as const, + expectedErrorSource: 'loader-2-error', + expectedLoaderMaxIndex: 1, + expectedRenderedHeadMaxIndex: -1, }, ] satisfies Array<Scenario> @@ -1922,68 +1658,60 @@ describe('head execution', () => { throwAtIndex: scenario.throwAtIndex, parentFailures: scenario.parentFailures, beforeLoadNotFoundFactory: scenario.beforeLoadNotFoundFactory, + withDefaultNotFoundComponent: scenario.withDefaultNotFoundComponent, }) - await router.load() - const matches = router.state.matches + const { error, matches } = await runLoadMatchesAndCapture(router) - 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 }), - ) - } + for (let i = 0; i < routes.length; i++) { + const loader = loaders[i]! + const expectedCalls = i <= scenario.expectedLoaderMaxIndex ? 1 : 0 + expect(loader).toHaveBeenCalledTimes(expectedCalls) } - loaders.forEach((loader, index) => { - const originalLaneCalls = loader.mock.calls.filter( - ([options]) => - options.location.pathname === '/level-1/level-2/level-3', + for (let i = 0; i < heads.length; i++) { + const head = heads[i]! + const expectedCalls = i <= scenario.expectedRenderedHeadMaxIndex ? 1 : 0 + expect(head).toHaveBeenCalledTimes(expectedCalls) + } + + if (scenario.expectedErrorKind === 'redirect') { + expect(error).toEqual( + expect.objectContaining({ + redirectHandled: true, + options: expect.objectContaining({ + to: '/redirect-target', + }), + }), ) - expect(originalLaneCalls).toHaveLength( - index < scenario.expectedLoaderCount ? 1 : 0, + return + } + + if (scenario.expectedErrorKind === 'error') { + expect(error).toBeInstanceOf(Error) + expect((error as Error).message).toBe(scenario.expectedErrorSource) + return + } + + expect(error).toEqual( + expect.objectContaining({ + isNotFound: true, + data: { source: scenario.expectedErrorSource }, + }), + ) + + if (scenario.expectedErrorRouteIndex !== undefined) { + expect((error as { routeId?: string }).routeId).toBe( + routes[scenario.expectedErrorRouteIndex]!.id, ) - }) - 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') + } + + if (scenario.expectRootNotFoundComponentAssigned) { + expect(routes[0].options.notFoundComponent).toBeTypeOf('function') + } }) - test('sets _notFound on root match when beforeLoad notFound targets root boundary', async () => { + test('sets globalNotFound on root match when beforeLoad notFound targets root boundary', async () => { const { router, routes } = setupScenario({ throwAtIndex: 3, parentFailures: {}, @@ -1994,27 +1722,28 @@ describe('head execution', () => { }), }) - await router.load() + const { error, matches } = await runLoadMatchesAndCapture(router) - 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(error).toEqual( expect.objectContaining({ isNotFound: true, data: { source: 'beforeLoad-root-explicit' }, }), ) + + const rootMatch = router.stores.pendingMatchesSnapshot.state.find( + (m) => m.routeId === routes[0].id, + ) + + expect(rootMatch?.globalNotFound).toBe(true) + expect(rootMatch?.status).toBe('success') + expect(rootMatch?.error).toBeUndefined() }) - test('clears stale root _notFound when the root loader is skipped on a successful reload', async () => { - const { router, routes, loaders } = setupScenario({ + test('clears stale root globalNotFound on subsequent successful load', async () => { + const { router, routes } = setupScenario({ throwAtIndex: 3, parentFailures: {}, - skipRootLoaderOnReload: true, beforeLoadNotFoundFactory: (innerRoutes) => notFound({ routeId: innerRoutes[0].id as never, @@ -2022,31 +1751,88 @@ describe('head execution', () => { }), }) - 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 first = await runLoadMatchesAndCapture(router) + expect(first.error).toEqual(expect.objectContaining({ isNotFound: true })) const throwingRoute = routes[3] throwingRoute.options.beforeLoad = undefined - await router.load() + const second = await runLoadMatchesAndCapture(router) + expect(second.error).toBeUndefined() - const rootMatch = router.state.matches.find( + const rootMatch = router.stores.pendingMatchesSnapshot.state.find( (m) => m.routeId === routes[0].id, ) - expect(rootMatch?._notFound).toBe(false) - expect(rootMatch?.status).toBe('success') - expect(loaders[0]).toHaveBeenCalledTimes(1) + expect(rootMatch?.globalNotFound).toBe(false) + }) + + test('clears stale root globalNotFound when root loader is skipped', async () => { + const rootLoader = vi.fn(() => ({ level: 0 })) + const rootRoute = new BaseRootRoute({ + loader: rootLoader, + staleTime: Infinity, + shouldReload: () => false, + }) + + const childLoader = vi.fn(() => ({ level: 1 })) + const childRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/test', + loader: childLoader, + staleTime: Infinity, + shouldReload: () => false, + }) + + const routeTree = rootRoute.addChildren([childRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/test'] }), + }) + + const first = await runLoadMatchesAndCapture(router) + expect(first.error).toBeUndefined() + expect(rootLoader).toHaveBeenCalledTimes(1) + + const staleRootNotFound = notFound({ data: { source: 'stale-root' } }) + const currentRootMatchId = + router.stores.pendingMatchesSnapshot.state.find( + (m) => m.routeId === rootRoute.id, + )!.id + + router.updateMatch(currentRootMatchId, (prev) => ({ + ...prev, + status: 'success', + globalNotFound: true, + error: staleRootNotFound, + })) + + const location = router.latestLocation + const matches = router.matchRoutes(location) + const pendingRootMatch = matches.find((m) => m.routeId === rootRoute.id)! + pendingRootMatch.status = 'success' + pendingRootMatch.globalNotFound = false + pendingRootMatch.error = undefined + router.stores.setPendingMatches(matches) + + await expect( + loadMatches({ + router, + location, + matches, + updateMatch: router.updateMatch, + }), + ).resolves.toBe(matches) + + expect(rootLoader).toHaveBeenCalledTimes(1) + + const rootMatch = router.stores.pendingMatchesSnapshot.state.find( + (m) => m.routeId === rootRoute.id, + ) + + expect(rootMatch?.globalNotFound).toBe(false) + expect(rootMatch?.error).toBeUndefined() }) }) }) @@ -2075,9 +1861,9 @@ describe('params.parse notFound', () => { await router.load() - const match = router.stores.matches - .get() - .find((m) => m.routeId === testRoute.id) + const match = router.stores.activeMatchesSnapshot.state.find( + (m) => m.routeId === testRoute.id, + ) expect(match?.status).toBe('notFound') }) @@ -2107,6 +1893,7 @@ 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) }) }) diff --git a/packages/router-core/tests/loader-architecture-regressions.test.ts b/packages/router-core/tests/loader-architecture-regressions.test.ts deleted file mode 100644 index 97561a9f72..0000000000 --- a/packages/router-core/tests/loader-architecture-regressions.test.ts +++ /dev/null @@ -1,1188 +0,0 @@ -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<void>() - const childGate = createControlledPromise<void>() - 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<void>() - const secondGate = createControlledPromise<void>() - const rootRoute = new BaseRootRoute({}) - const pageRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/page', - validateSearch: (search: Record<string, unknown>) => ({ - 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<string>() - const childGate = createControlledPromise<string>() - 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<void>() - 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<void> | undefined - - const rootRoute = new BaseRootRoute({}) - const parentRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/parent', - validateSearch: (search: Record<string, unknown>) => ({ - 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<number>() - const beforeLoadStarted = createControlledPromise<void>() - const beforeLoadGate = createControlledPromise<void>() - const signals: Array<AbortSignal> = [] - let generation = 0 - - const rootRoute = new BaseRootRoute({}) - const route = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/page', - validateSearch: (search: Record<string, unknown>) => ({ - 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<number>() - const signals: Array<AbortSignal> = [] - let generation = 0 - - const rootRoute = new BaseRootRoute({}) - const parentRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/parent', - validateSearch: (search: Record<string, unknown>) => ({ - 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<void> | 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<void>() - const childRedirect = createControlledPromise<void>() - 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<string, unknown>) => ({ - 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<void>() - const releasePreloadRedirect = createControlledPromise<void>() - 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<string, unknown>) => ({ - 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<string, never> => { - 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<void>() - 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<false>((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<void>() - const chunk = createControlledPromise<void>() - 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<false>((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<void>() - const chunk = createControlledPromise<void>() - 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<false>((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<void> | undefined - let router: ReturnType<typeof createTestRouter> - 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<void> | undefined - let redirected = false - let router: ReturnType<typeof createTestRouter> - - 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 deleted file mode 100644 index 68916b1d68..0000000000 --- a/packages/router-core/tests/loader-self-abort.test.ts +++ /dev/null @@ -1,73 +0,0 @@ -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 deleted file mode 100644 index e45eede84f..0000000000 --- a/packages/router-core/tests/loader-thrown-promise.test.ts +++ /dev/null @@ -1,57 +0,0 @@ -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 new file mode 100644 index 0000000000..f601816596 --- /dev/null +++ b/packages/router-core/tests/lru.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, it } from 'vitest' +import { createLRUCache } from '../src/lru-cache' + +describe('LRU Cache', () => { + it('evicts oldest set', () => { + const cache = createLRUCache<string, number>(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<string, number>(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 deleted file mode 100644 index f9d5d961df..0000000000 --- a/packages/router-core/tests/manifest.test.ts +++ /dev/null @@ -1,117 +0,0 @@ -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<RouterManagedTag> = [] - - 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<RouterManagedTag> = [] - - 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<RouterManagedTag> = [] - - 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<RouterManagedTag> = [] - - 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 3722aa6a1b..7e46303787 100644 --- a/packages/router-core/tests/mask.test.ts +++ b/packages/router-core/tests/mask.test.ts @@ -92,29 +92,6 @@ 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<RouteMask<any>> = [ - { - 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<RouteMask<any>> = [ { @@ -645,201 +622,3 @@ 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<RouteMask<any>>) => { - 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<string, unknown>) => - 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 deleted file mode 100644 index 9738b42261..0000000000 --- a/packages/router-core/tests/masked-location-state-commit.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -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 301eb846d0..f742c22df9 100644 --- a/packages/router-core/tests/match-by-path.test.ts +++ b/packages/router-core/tests/match-by-path.test.ts @@ -1,6 +1,8 @@ import { describe, expect, it } from 'vitest' -import { findSingleMatch } from '../src/new-process-route-tree' -import { processTestRouteTree as processRouteTree } from './routerTestUtils' +import { + findSingleMatch, + processRouteTree, +} from '../src/new-process-route-tree' const { processedTree } = processRouteTree({ id: '__root__', diff --git a/packages/router-core/tests/match-params.test.ts b/packages/router-core/tests/match-params.test.ts deleted file mode 100644 index 9b254834f9..0000000000 --- a/packages/router-core/tests/match-params.test.ts +++ /dev/null @@ -1,792 +0,0 @@ -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<string, string>) => unknown - priority?: number - } - } - children?: Array<TestRoute> -} - -const root = (children: Array<TestRoute>): TestRoute => ({ - id: '__root__', - isRoot: true, - fullPath: '/', - path: '/', - children, -}) - -const parseWhen = (predicate: (params: Record<string, string>) => boolean) => { - return (params: Record<string, string>) => - 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<string, string>) => { - 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<string, string>) => 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<string, string>) => { - return params - }) - const priorityNegativeOneParse = vi.fn( - (params: Record<string, string>) => { - 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<string, string>) => { - 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 deleted file mode 100644 index 03fe060bfa..0000000000 --- a/packages/router-core/tests/matching-interpolation.bench.ts +++ /dev/null @@ -1,121 +0,0 @@ -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 deleted file mode 100644 index 1a0f165f93..0000000000 --- a/packages/router-core/tests/navigation-awaitable.test.ts +++ /dev/null @@ -1,200 +0,0 @@ -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 deleted file mode 100644 index 3ea034aa5a..0000000000 --- a/packages/router-core/tests/navigation-burst-settle.test.ts +++ /dev/null @@ -1,66 +0,0 @@ -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 deleted file mode 100644 index b45a814349..0000000000 --- a/packages/router-core/tests/navigation-settled-cache.test.ts +++ /dev/null @@ -1,74 +0,0 @@ -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<never>((_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 86a7c4e659..936df988c1 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 { beforeAll, describe, expect, it, vi } from 'vitest' +import { describe, expect, it } 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<string>) { @@ -22,44 +22,6 @@ function makeTree(routes: Array<string>) { } 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', () => { @@ -114,10 +76,6 @@ 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/$']) @@ -131,90 +89,6 @@ 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<string, string>) => params, - }, - }, - }, - { - id: `high-${siblingKind}`, - fullPath, - path: fullPath.slice(1), - options: { - params: { - priority: 2, - parse: (params: Record<string, string>) => - 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', () => { @@ -359,64 +233,6 @@ 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}') - }) }) }) @@ -478,63 +294,6 @@ 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__', @@ -627,31 +386,6 @@ 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', () => { @@ -711,22 +445,6 @@ 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', () => { @@ -758,16 +476,6 @@ 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( @@ -1068,77 +776,6 @@ describe('findRouteMatch', () => { 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', () => { @@ -1249,333 +886,9 @@ describe('findRouteMatch', () => { 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<string, string>) => { - 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<string, string>) => { - higherPriorityCalls++ - return params - }, - }, - }, - }, - { - id: '/a/$', - fullPath: '/a/$', - path: 'a/$', - isRoot: false, - options: { - params: { - parse: (params: Record<string, string>) => { - 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<string, string>) => { - 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<string, string>) => { - 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<string, string> | undefined - const tree = { - id: '__root__', - fullPath: '/', - path: '/', - isRoot: true, - options: {}, - children: [ - { - id: '/a/$', - fullPath: '/a/$', - path: 'a/$', - isRoot: false, - options: { - params: { - parse: (params: Record<string, string>) => { - 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<string, string>) => 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: '/', @@ -1594,7 +907,10 @@ describe('findRouteMatch', () => { path: '$foo', fullPath: '/$foo', options: { - params: { parse: (params: Record<string, string>) => params }, + params: { parse: () => {} }, + skipRouteOnParseError: { + params: true, + }, }, children: [ { @@ -1622,113 +938,61 @@ describe('findRouteMatch', () => { const { processedTree } = processRouteTree(tree) expect(processedTree.segmentTree).toMatchInlineSnapshot(` { - "caseSensitive": undefined, - "data": undefined, "depth": 0, "dynamic": [ { "caseSensitive": false, - "data": undefined, "depth": 1, "dynamic": null, + "fullPath": "/$foo", "index": null, "kind": 1, "optional": null, "parent": [Circular], "parse": null, + "parsingPriority": 0, "pathless": [ { - "caseSensitive": undefined, - "data": [ - [ - 1, - "foo", - "/", - "", - ], - ], "depth": 2, "dynamic": null, + "fullPath": "/$foo", "index": { - "caseSensitive": undefined, - "data": [ - [ - 1, - "foo", - "/", - "", - ], - ], "depth": 3, "dynamic": null, + "fullPath": "/$foo/", "index": null, "kind": 4, "optional": null, "parent": [Circular], "parse": null, + "parsingPriority": 0, "pathless": null, - "prefix": undefined, - "priority": 0, "route": { - "_interpolation": [ - [ - 1, - "foo", - "/", - "", - ], - ], "fullPath": "/$foo/", "id": "/$foo/_layout/", "options": {}, "path": "/", }, + "skipOnParamError": false, "static": null, "staticInsensitive": null, - "suffix": undefined, "wildcard": null, }, "kind": 5, "optional": null, "parent": [Circular], "parse": [Function], + "parsingPriority": 0, "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": {}, @@ -1741,144 +1005,106 @@ describe('findRouteMatch', () => { "params": { "parse": [Function], }, + "skipRouteOnParseError": { + "params": true, + }, }, "path": "$foo", }, + "skipOnParamError": true, "static": null, "staticInsensitive": Map { "bar" => { - "caseSensitive": undefined, - "data": [ - [ - 1, - "foo", - "/", - "", - ], - "/bar", - ], "depth": 3, "dynamic": null, + "fullPath": "/$foo/bar", "index": null, "kind": 0, "optional": null, "parent": [Circular], "parse": null, + "parsingPriority": 0, "pathless": null, - "prefix": undefined, - "priority": 0, "route": { - "_interpolation": [ - [ - 1, - "foo", - "/", - "", - ], - "/bar", - ], "fullPath": "/$foo/bar", "id": "/$foo/_layout/bar", "options": {}, "path": "bar", }, + "skipOnParamError": false, "static": null, "staticInsensitive": null, - "suffix": undefined, "wildcard": null, }, }, - "suffix": undefined, "wildcard": null, }, ], - "prefix": "", - "priority": 0, + "prefix": undefined, "route": null, + "skipOnParamError": false, "static": null, "staticInsensitive": Map { "hello" => { - "caseSensitive": undefined, - "data": [ - [ - 1, - "foo", - "/", - "", - ], - "/hello", - ], "depth": 2, "dynamic": null, + "fullPath": "/$foo/hello", "index": null, "kind": 0, "optional": null, "parent": [Circular], "parse": null, + "parsingPriority": 0, "pathless": null, - "prefix": undefined, - "priority": 0, "route": { - "_interpolation": [ - [ - 1, - "foo", - "/", - "", - ], - "/hello", - ], "fullPath": "/$foo/hello", "id": "/$foo/hello", "options": {}, "path": "$foo/hello", }, + "skipOnParamError": false, "static": null, "staticInsensitive": null, - "suffix": undefined, "wildcard": null, }, }, - "suffix": "", + "suffix": undefined, "wildcard": null, }, ], + "fullPath": "/", "index": { - "caseSensitive": undefined, - "data": undefined, "depth": 1, "dynamic": null, + "fullPath": "/", "index": null, "kind": 4, "optional": null, "parent": [Circular], "parse": null, + "parsingPriority": 0, "pathless": null, - "prefix": undefined, - "priority": 0, "route": { - "_interpolation": undefined, "fullPath": "/", "id": "/", "options": {}, "path": "/", }, + "skipOnParamError": false, "static": null, "staticInsensitive": null, - "suffix": undefined, "wildcard": null, }, "kind": 0, "optional": null, - "parent": undefined, + "parent": null, "parse": null, + "parsingPriority": 0, "pathless": null, - "prefix": undefined, - "priority": 0, "route": null, + "skipOnParamError": false, "static": null, "staticInsensitive": null, - "suffix": undefined, "wildcard": null, } `) @@ -1899,6 +1125,7 @@ describe('findRouteMatch', () => { parse: (params: Record<string, string>) => params, }, // force the creation of a pathless node + skipRouteOnParseError: { params: true }, }, children: [ { @@ -1932,6 +1159,7 @@ describe('findRouteMatch', () => { parse: (params: Record<string, string>) => params, }, // force the creation of a pathless node + skipRouteOnParseError: { params: true }, }, children: [ { @@ -1961,34 +1189,22 @@ describe('findRouteMatch', () => { }) }) -describe('processRouteMasks', { concurrent: false }, () => { +describe('processRouteMasks', { sequential: true }, () => { const routeTree = { id: '__root__', isRoot: true, fullPath: '/', } as AnyRoute const { processedTree } = processRouteTree(routeTree) - const routeMasks: Array<RouteMask<AnyRoute>> = [ - { 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 routeMasks: Array<RouteMask<AnyRoute>> = [ + { 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 }, + ] + processRouteMasks(routeMasks, processedTree) const aBranch = processedTree.masksTree?.staticInsensitive?.get('a') expect(aBranch).toBeDefined() expect(aBranch?.staticInsensitive?.get('b')).toBeDefined() @@ -1999,20 +1215,6 @@ describe('processRouteMasks', { concurrent: false }, () => { 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') @@ -2028,44 +1230,4 @@ describe('processRouteMasks', { concurrent: false }, () => { expect(res?.route.from).toBe('/a/b/{$}.txt') 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 deleted file mode 100644 index 7fb50b6c89..0000000000 --- a/packages/router-core/tests/not-found-navigation-lifecycle.test.ts +++ /dev/null @@ -1,174 +0,0 @@ -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<void>() - const ownerBeforeLoadGate = createControlledPromise<void>() - const childBeforeLoadStarted = createControlledPromise<void>() - const childBeforeLoadGate = createControlledPromise<void>() - 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<void> | 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 36ed96f227..e3a09c2cf2 100644 --- a/packages/router-core/tests/optional-path-params-clean.test.ts +++ b/packages/router-core/tests/optional-path-params-clean.test.ts @@ -1,20 +1,55 @@ 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, - parseSegments, + parseSegment, + processRouteTree, } 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<PathSegment> = [] + 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([ @@ -52,40 +87,53 @@ describe('Optional Path Parameters - Clean Comprehensive Tests', () => { describe('interpolatePath', () => { it('should interpolate optional dynamic params when present', () => { - const path = '/posts/{-$category}' - const segments = parseSegments(false, { fullPath: path }, 0) - expect(interpolatePath(path, segments, { category: 'tech' })).toBe( - '/posts/tech', - ) + const result = interpolatePath({ + path: '/posts/{-$category}', + params: { category: 'tech' }, + }) + expect(result.interpolatedPath).toBe('/posts/tech') }) it('should omit optional dynamic params when missing', () => { - const path = '/posts/{-$category}' - const segments = parseSegments(false, { fullPath: path }, 0) - expect(interpolatePath(path, segments, {})).toBe('/posts') + const result = interpolatePath({ + path: '/posts/{-$category}', + params: {}, + }) + expect(result.interpolatedPath).toBe('/posts') }) it('should handle multiple optional dynamic params', () => { - 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') + 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') }) it('should handle mixed required and optional dynamic params', () => { - 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', - ) + 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') }) }) @@ -158,46 +206,44 @@ describe('Optional Path Parameters - Clean Comprehensive Tests', () => { describe('Edge Cases', () => { it('should handle optional params with wildcards', () => { - 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', - ) + 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') }) 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 - expect( - interpolatePath(pattern, segments, { - env: 'prod', - version: 'v2', - id: '123', - tab: 'settings', - }), - ).toBe('/app/prod/api/v2/users/123/settings') - - // Only required param - expect(interpolatePath(pattern, segments, { id: '123' })).toBe( - '/app/api/users/123', + 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', ) + // Only required param + const result2 = interpolatePath({ + path: pattern, + params: { id: '123' }, + }) + expect(result2.interpolatedPath).toBe('/app/api/users/123') + // Mix of optional and required - expect( - interpolatePath(pattern, segments, { - env: 'dev', - id: '456', - tab: 'profile', - }), - ).toBe('/app/dev/api/users/456/profile') + const result3 = interpolatePath({ + path: pattern, + params: { env: 'dev', id: '456', tab: 'profile' }, + }) + expect(result3.interpolatedPath).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 4d3c2ee76e..b58c0b14af 100644 --- a/packages/router-core/tests/optional-path-params.test.ts +++ b/packages/router-core/tests/optional-path-params.test.ts @@ -1,16 +1,13 @@ 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, - parseSegments, + parseSegment, + processRouteTree, } from '../src/new-process-route-tree' import type { SegmentKind } from '../src/new-process-route-tree' @@ -28,6 +25,34 @@ 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<PathSegment> = [] + 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', @@ -144,30 +169,6 @@ 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) @@ -344,8 +345,7 @@ describe('Optional Path Parameters', () => { result: '/posts/42', }, ])('$name', ({ path, params, result }) => { - const segments = parseSegments(false, { fullPath: path }, 0) - expect(interpolatePath(path, segments, params)).toBe(result) + expect(interpolatePath({ path, params }).interpolatedPath).toBe(result) }) }) @@ -474,9 +474,10 @@ 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, segments, params)).toBe('/posts/tech') + expect(interpolatePath({ path, params }).interpolatedPath).toBe( + '/posts/tech', + ) }) it('should handle multiple consecutive optional parameters correctly', () => { diff --git a/packages/router-core/tests/original-param-names.test.ts b/packages/router-core/tests/original-param-names.test.ts deleted file mode 100644 index aca4c61ae4..0000000000 --- a/packages/router-core/tests/original-param-names.test.ts +++ /dev/null @@ -1,143 +0,0 @@ -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<string, string>) => 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<Record<string, string>> = [] - 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<string, string>) => { - 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 deleted file mode 100644 index 5513067027..0000000000 --- a/packages/router-core/tests/parent-match-promise.test.ts +++ /dev/null @@ -1,121 +0,0 @@ -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<unknown> = [] - 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<unknown> = [] - 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 deleted file mode 100644 index 4b160f4644..0000000000 --- a/packages/router-core/tests/parse-segment.test.ts +++ /dev/null @@ -1,52 +0,0 @@ -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 deleted file mode 100644 index 4c56a8aa76..0000000000 --- a/packages/router-core/tests/path-decoder.bench.ts +++ /dev/null @@ -1,66 +0,0 @@ -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 deleted file mode 100644 index bf27b93134..0000000000 --- a/packages/router-core/tests/path-decoder.test.ts +++ /dev/null @@ -1,92 +0,0 @@ -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 deleted file mode 100644 index 80d3478594..0000000000 --- a/packages/router-core/tests/path-interpolation.bench.ts +++ /dev/null @@ -1,290 +0,0 @@ -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<PathInterpolationTestOptions> - 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<string, unknown>, - 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 dac91a80fa..1eab00f04f 100644 --- a/packages/router-core/tests/path.test.ts +++ b/packages/router-core/tests/path.test.ts @@ -1,8 +1,7 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' +import { describe, expect, it } from 'vitest' import { compileDecodeCharMap, exactPathTest, - hasMissingPathParams, interpolatePath, removeTrailingSlash, resolvePath, @@ -13,372 +12,11 @@ import { SEGMENT_TYPE_PATHNAME, SEGMENT_TYPE_WILDCARD, findSingleMatch, - getParamNames, - parseSegments, + parseSegment, + processRouteTree, } 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<string, unknown> = 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<string, unknown> = 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<string, unknown> = 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 }) => { @@ -455,9 +93,6 @@ 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'], @@ -470,62 +105,79 @@ 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(a, b)).toEqual(eq) + expect(resolvePath({ base: a, to: b })).toEqual(eq) }) it(`${a}/ to ${b} === ${eq} (trailing slash)`, () => { - expect(resolvePath(a + '/', b)).toEqual(eq) + expect(resolvePath({ base: a + '/', to: b })).toEqual(eq) }) it(`${a}/ to ${b}/ === ${eq} (trailing slash + trailing slash)`, () => { - expect(resolvePath(a + '/', b + '/')).toEqual(eq) + expect(resolvePath({ base: a + '/', to: 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('/a/b/c', 'd/', 'always')).toBe('/a/b/c/d/') + expect( + resolvePath({ + base: '/a/b/c', + to: 'd/', + trailingSlash: 'always', + }), + ).toBe('/a/b/c/d/') }) it('adds trailing slash', () => { - expect(resolvePath('/a/b/c', 'd', 'always')).toBe('/a/b/c/d/') + expect( + resolvePath({ + base: '/a/b/c', + to: 'd', + trailingSlash: 'always', + }), + ).toBe('/a/b/c/d/') }) }) describe(`'never'`, () => { it('removes trailing slash', () => { - expect(resolvePath('/a/b/c', 'd/', 'never')).toBe('/a/b/c/d') + expect( + resolvePath({ + base: '/a/b/c', + to: 'd/', + trailingSlash: 'never', + }), + ).toBe('/a/b/c/d') }) it('does not add trailing slash', () => { - expect(resolvePath('/a/b/c', 'd', 'never')).toBe('/a/b/c/d') + expect( + resolvePath({ + base: '/a/b/c', + to: 'd', + trailingSlash: 'never', + }), + ).toBe('/a/b/c/d') }) }) describe(`'preserve'`, () => { it('keeps trailing slash', () => { - expect(resolvePath('/a/b/c', 'd/', 'preserve')).toBe('/a/b/c/d/') + expect( + resolvePath({ + base: '/a/b/c', + to: 'd/', + trailingSlash: 'preserve', + }), + ).toBe('/a/b/c/d/') }) it('does not add trailing slash', () => { - expect(resolvePath('/a/b/c', 'd', 'preserve')).toBe('/a/b/c/d') + expect( + resolvePath({ + base: '/a/b/c', + to: 'd', + trailingSlash: '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' }])( @@ -549,7 +201,13 @@ describe('resolvePath', () => { }, ])('$name', ({ to }) => { const candidate = base + trimPathLeft(to) - expect(resolvePath(base, candidate, 'never')).toEqual(candidate) + expect( + resolvePath({ + base, + to: candidate, + trailingSlash: 'never', + }), + ).toEqual(candidate) }) }) @@ -571,465 +229,414 @@ describe('resolvePath', () => { }, ])('$name', ({ to }) => { const candidate = base + trimPathLeft(to) - expect(resolvePath(base, candidate, 'never')).toEqual(candidate) + expect( + resolvePath({ + base, + to: candidate, + trailingSlash: '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<string, string>(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') +describe.each([{ server: true }, { server: false }])( + 'interpolatePath (server: $server)', + ({ server }) => { + describe('regular usage', () => { + it.each([ + { + name: 'should interpolate the path', + path: '/users/$id', + params: { id: '123' }, + result: '/users/123', + }, + { + name: 'should interpolate the path', + path: '/users/$id', + params: { id: '123_' }, + result: '/users/123_', + }, + { + name: 'should interpolate the path with multiple params', + path: '/users/$id/$name', + params: { id: '123', name: 'tanner' }, + result: '/users/123/tanner', + }, + { + name: 'should interpolate the path with multiple params', + path: '/users/$id/$name', + params: { id: '123_', name: 'tanner' }, + result: '/users/123_/tanner', + }, + { + name: 'should interpolate the path with extra params', + path: '/users/$id', + params: { id: '123', name: 'tanner' }, + result: '/users/123', + }, + { + name: 'should interpolate the path with missing params', + path: '/users/$id/$name', + params: { id: '123' }, + result: '/users/123/undefined', + }, + { + name: 'should interpolate the path with missing params and extra params', + path: '/users/$id', + params: { name: 'john' }, + result: '/users/undefined', + }, + { + name: 'should interpolate the path with the param being a number', + path: '/users/$id', + params: { id: 123 }, + result: '/users/123', + }, + { + name: 'should interpolate the path with the param being a falsey number', + path: '/users/$id', + params: { id: 0 }, + result: '/users/0', + }, + { + name: 'should interpolate the path with URI component encoding', + path: '/users/$id', + params: { id: '?#@john+smith' }, + result: '/users/%3F%23%40john%2Bsmith', + }, + { + name: 'should interpolate the path without URI encoding characters in decodeCharMap', + path: '/users/$id', + params: { id: '?#@john+smith' }, + result: '/users/%3F%23@john+smith', + decoder: compileDecodeCharMap(['@', '+']), + }, + { + name: 'should interpolate the path with the splat param at the end', + path: '/users/$', + params: { _splat: '123' }, + result: '/users/123', + }, + { + name: 'should interpolate the path with a single named path param and the splat param at the end', + path: '/users/$username/$', + params: { username: 'seancassiere', _splat: '123' }, + result: '/users/seancassiere/123', + }, + { + name: 'should interpolate the path with 2 named path params with the splat param at the end', + path: '/users/$username/$id/$', + params: { username: 'seancassiere', id: '123', _splat: '456' }, + result: '/users/seancassiere/123/456', + }, + { + name: 'should interpolate the path with multiple named path params with the splat param at the end', + path: '/$username/settings/$repo/$id/$', + params: { + username: 'sean-cassiere', + repo: 'my-repo', + id: '123', + _splat: '456', + }, + result: '/sean-cassiere/settings/my-repo/123/456', + }, + { + name: 'should interpolate the path with the splat param containing slashes', + path: '/users/$', + params: { _splat: 'sean/cassiere' }, + result: '/users/sean/cassiere', + }, + ])('$name', ({ path, params, decoder, result }) => { + expect( + interpolatePath({ + path, + params, + decoder, + server, + }).interpolatedPath, + ).toBe(result) + }) + }) + + describe('preserve trailing slash', () => { + it.each([ + { + path: '/', + params: {}, + result: '/', + }, + { + path: '/a/b/', + params: {}, + result: '/a/b/', + }, + { + path: '/a/$id/', + params: { id: '123' }, + result: '/a/123/', + }, + { + path: '/a/{-$id}/', + params: { id: '123' }, + result: '/a/123/', + }, + ])( + 'should preserve trailing slash for $path', + ({ path, params, result }) => { + expect( + interpolatePath({ + path, + params, + server, + }).interpolatedPath, + ).toBe(result) }, - } - const segments = parseSegments( - false, - { fullPath: '/files/$/$ignored' }, - 0, ) - const used: Record<string, unknown> = 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<string, unknown> = 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([ - { - name: 'should interpolate the path', - path: '/users/$id', - params: { id: '123' }, - result: '/users/123', - }, - { - name: 'should interpolate the path', - path: '/users/$id', - params: { id: '123_' }, - result: '/users/123_', - }, - { - name: 'should interpolate the path with multiple params', - path: '/users/$id/$name', - params: { id: '123', name: 'tanner' }, - result: '/users/123/tanner', - }, - { - name: 'should interpolate the path with multiple params', - path: '/users/$id/$name', - params: { id: '123_', name: 'tanner' }, - result: '/users/123_/tanner', - }, - { - name: 'should interpolate the path with extra params', - path: '/users/$id', - params: { id: '123', name: 'tanner' }, - result: '/users/123', - }, - { - name: 'should interpolate the path with missing params', - path: '/users/$id/$name', - params: { id: '123' }, - result: '/users/123/undefined', - }, - { - name: 'should interpolate the path with missing params and extra params', - path: '/users/$id', - params: { name: 'john' }, - result: '/users/undefined', - }, - { - name: 'should interpolate the path with the param being a number', - path: '/users/$id', - params: { id: 123 }, - result: '/users/123', - }, - { - name: 'should interpolate the path with the param being a falsey number', - path: '/users/$id', - 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', - params: { id: '?#@john+smith' }, - result: '/users/%3F%23%40john%2Bsmith', - }, - { - name: 'should interpolate the path without URI encoding characters in decodeCharMap', - path: '/users/$id', - params: { id: '?#@john+smith' }, - result: '/users/%3F%23@john+smith', - decoder: compileDecodeCharMap(['@', '+']), - }, - { - name: 'should interpolate the path with the splat param at the end', - path: '/users/$', - params: { _splat: '123' }, - result: '/users/123', - }, - { - name: 'should interpolate the path with a single named path param and the splat param at the end', - path: '/users/$username/$', - params: { username: 'seancassiere', _splat: '123' }, - result: '/users/seancassiere/123', - }, - { - name: 'should interpolate the path with 2 named path params with the splat param at the end', - path: '/users/$username/$id/$', - params: { username: 'seancassiere', id: '123', _splat: '456' }, - result: '/users/seancassiere/123/456', - }, - { - name: 'should interpolate the path with multiple named path params with the splat param at the end', - path: '/$username/settings/$repo/$id/$', - params: { - username: 'sean-cassiere', - repo: 'my-repo', - id: '123', - _splat: '456', + describe('wildcard (prefix + suffix)', () => { + it.each([ + { + name: 'regular', + to: '/$', + params: { _splat: 'bar/foo/me' }, + result: '/bar/foo/me', }, - result: '/sean-cassiere/settings/my-repo/123/456', - }, - { - name: 'should interpolate the path with the splat param containing slashes', - path: '/users/$', - params: { _splat: 'sean/cassiere' }, - result: '/users/sean/cassiere', - }, - ])('$name', ({ path, params, decoder, result }) => { - const segments = parseSegments(false, { fullPath: path }, 0) - expect(interpolatePath(path, segments, params, decoder)).toBe(result) - }) - }) - - describe('preserve trailing slash', () => { - it.each([ - { - path: '/', - params: {}, - result: '/', - }, - { - path: '/a/b/', - params: {}, - result: '/a/b/', - }, - { - path: '/a/$id/', - params: { id: '123' }, - result: '/a/123/', - }, - { - path: '/a/{-$id}/', - params: { id: '123' }, - result: '/a/123/', - }, - ])( - 'should preserve trailing slash for $path', - ({ path, params, result }) => { - const segments = parseSegments(false, { fullPath: path }, 0) - expect(interpolatePath(path, segments, params)).toBe(result) - }, - ) - }) - - describe('wildcard (prefix + suffix)', () => { - it.each([ - { - name: 'regular', - to: '/$', - params: { _splat: 'bar/foo/me' }, - result: '/bar/foo/me', - }, - { - name: 'regular curly braces', - to: '/{$}', - params: { _splat: 'bar/foo/me' }, - result: '/bar/foo/me', - }, - { - name: 'with prefix', - to: '/prefix{$}', - params: { _splat: 'bar' }, - result: '/prefixbar', - }, - { - name: 'with suffix', - to: '/{$}-suffix', - params: { _splat: 'bar' }, - result: '/bar-suffix', - }, - { - name: 'with prefix + suffix', - to: '/prefix{$}-suffix', - params: { _splat: 'bar' }, - result: '/prefixbar-suffix', - }, - ])('$name', ({ to, params, 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) - }) - }) - - describe('named params (prefix + suffix)', () => { - it.each([ - { - name: 'regular', - to: '/$foo', - params: { foo: 'bar' }, - result: '/bar', - }, - { - name: 'regular curly braces', - to: '/{$foo}', - params: { foo: 'bar' }, - result: '/bar', - }, - { - name: 'with prefix', - to: '/prefix{$bar}', - params: { bar: 'baz' }, - result: '/prefixbaz', - }, - { - name: 'with suffix', - to: '/{$foo}.suffix', - params: { foo: 'bar' }, - result: '/bar.suffix', - }, - { - name: 'with suffix', - to: '/{$foo}.suffix', - params: { foo: 'bar_' }, - result: '/bar_.suffix', - }, - { - name: 'with prefix and suffix', - to: '/prefix{$param}.suffix', - params: { param: 'foobar' }, - result: '/prefixfoobar.suffix', - }, - ])('$name', ({ to, params, result }) => { - const segments = parseSegments(false, { fullPath: to }, 0) - expect(interpolatePath(to, segments, params)).toBe(result) - }) - }) - - describe('should handle missing _splat parameter for', () => { - it.each([ - { - name: 'basic splat route', - path: '/hello/$', - params: {}, - expectedResult: '/hello', - }, - { - name: 'splat route with prefix', - path: '/hello/prefix{$}', - params: {}, - expectedResult: '/hello/prefix', - }, - { - name: 'splat route with suffix', - path: '/hello/{$}suffix', - params: {}, - expectedResult: '/hello/suffix', - }, - { - name: 'splat route with prefix and suffix', - path: '/hello/prefix{$}suffix', - params: {}, - expectedResult: '/hello/prefixsuffix', - }, - { - name: 'splat route with empty splat', - path: '/hello/$', - params: { - _splat: '', + { + name: 'regular curly braces', + to: '/{$}', + params: { _splat: 'bar/foo/me' }, + result: '/bar/foo/me', }, - expectedResult: '/hello', - }, - { - name: 'splat route with undefined splat', - path: '/hello/$', - params: { - _splat: undefined, + { + name: 'with prefix', + to: '/prefix{$}', + params: { _splat: 'bar' }, + result: '/prefixbar', }, - expectedResult: '/hello', - }, - ])('$name', ({ path, params, expectedResult }) => { - const segments = parseSegments(false, { fullPath: path }, 0) - expect(interpolatePath(path, segments, params)).toBe(expectedResult) - expect(hasMissingPathParams(segments, params)).toBe(true) + { + name: 'with suffix', + to: '/{$}-suffix', + params: { _splat: 'bar' }, + result: '/bar-suffix', + }, + { + name: 'with prefix + suffix', + to: '/prefix{$}-suffix', + params: { _splat: 'bar' }, + result: '/prefixbar-suffix', + }, + ])('$name', ({ to, params, result }) => { + expect( + interpolatePath({ + path: to, + params, + server, + }).interpolatedPath, + ).toBe(result) + }) }) - }) - 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('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 }) => { + expect( + interpolatePath({ + path, + params, + server, + }).interpolatedPath, + ).toBe(result) + }) + }) + + describe('named params (prefix + suffix)', () => { + it.each([ + { + name: 'regular', + to: '/$foo', + params: { foo: 'bar' }, + result: '/bar', + }, + { + name: 'regular curly braces', + to: '/{$foo}', + params: { foo: 'bar' }, + result: '/bar', + }, + { + name: 'with prefix', + to: '/prefix{$bar}', + params: { bar: 'baz' }, + result: '/prefixbaz', + }, + { + name: 'with suffix', + to: '/{$foo}.suffix', + params: { foo: 'bar' }, + result: '/bar.suffix', + }, + { + name: 'with suffix', + to: '/{$foo}.suffix', + params: { foo: 'bar_' }, + result: '/bar_.suffix', + }, + { + name: 'with prefix and suffix', + to: '/prefix{$param}.suffix', + params: { param: 'foobar' }, + result: '/prefixfoobar.suffix', + }, + ])('$name', ({ to, params, result }) => { + expect( + interpolatePath({ + path: to, + params, + server, + }).interpolatedPath, + ).toBe(result) + }) + }) + + describe('should handle missing _splat parameter for', () => { + it.each([ + { + name: 'basic splat route', + path: '/hello/$', + params: {}, + expectedResult: '/hello', + }, + { + name: 'splat route with prefix', + path: '/hello/prefix{$}', + params: {}, + expectedResult: '/hello/prefix', + }, + { + name: 'splat route with suffix', + path: '/hello/{$}suffix', + params: {}, + expectedResult: '/hello/suffix', + }, + { + name: 'splat route with prefix and suffix', + path: '/hello/prefix{$}suffix', + params: {}, + expectedResult: '/hello/prefixsuffix', + }, + { + name: 'splat route with empty splat', + path: '/hello/$', + params: { + _splat: '', + }, + expectedResult: '/hello', + }, + { + name: 'splat route with undefined splat', + path: '/hello/$', + params: { + _splat: undefined, + }, + expectedResult: '/hello', + }, + ])('$name', ({ path, params, expectedResult }) => { + const result = interpolatePath({ + path, + params, + server, + }) + expect(result.interpolatedPath).toBe(expectedResult) + expect(result.isMissingParams).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, + server, + }).interpolatedPath + expect(interpolatedNextTo).toBe(`/splat${tail}`) + }, + ) + }) + }, +) describe('matchPathname', () => { const { processedTree } = processRouteTree({ @@ -1080,7 +687,7 @@ describe('matchPathname', () => { expectedMatchedParams: { id: '123' }, }, { - name: 'should match and return the splat param', + name: 'should match and return the the splat param', input: '/users/123', matchingOptions: { to: '/users/$', @@ -1292,6 +899,35 @@ describe('parsePathname', () => { suffixSegment?: string } + const parsePathname = (to: string | undefined) => { + let cursor = 0 + let data + const path = to ?? '' + const segments: Array<PathSegment> = [] + 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([ { diff --git a/packages/router-core/tests/preflight-reentrant-context.test.ts b/packages/router-core/tests/preflight-reentrant-context.test.ts deleted file mode 100644 index 415e5f0e50..0000000000 --- a/packages/router-core/tests/preflight-reentrant-context.test.ts +++ /dev/null @@ -1,101 +0,0 @@ -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<void> | 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<void> | 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 deleted file mode 100644 index 23519edfec..0000000000 --- a/packages/router-core/tests/preflight-signal-currentness.test.ts +++ /dev/null @@ -1,49 +0,0 @@ -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 deleted file mode 100644 index 94d31e2e94..0000000000 --- a/packages/router-core/tests/preload-adoption.test.ts +++ /dev/null @@ -1,367 +0,0 @@ -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<string> - }>() - const revalidationStarted = createControlledPromise<void>() - 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<void>() - const preloadSerialStarted = createControlledPromise<void>() - 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<string>() - const loaderStarted = createControlledPromise<void>() - 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<undefined>() - const loaderStarted = createControlledPromise<void>() - 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<void>() - const preloadFailureGate = createControlledPromise<void>() - const childStarted = createControlledPromise<void>() - const childGate = createControlledPromise<string>() - 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 deleted file mode 100644 index 3dcbb62824..0000000000 --- a/packages/router-core/tests/preload-background-parent-coherence.test.ts +++ /dev/null @@ -1,88 +0,0 @@ -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<void>() - 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 deleted file mode 100644 index c9d70bae5d..0000000000 --- a/packages/router-core/tests/preload-beforeload-reuse.test.ts +++ /dev/null @@ -1,669 +0,0 @@ -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<string>() - 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<string, unknown>) => ({ - 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<boolean> = [] - 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<boolean> = [] - const childSeen: Array<boolean> = [] - 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<boolean> = [] - 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<string>() - 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<boolean> = [] - 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 deleted file mode 100644 index 058c401f30..0000000000 --- a/packages/router-core/tests/preload-navigation-adoption.test.ts +++ /dev/null @@ -1,221 +0,0 @@ -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<string>() - const loaderStarted = createControlledPromise<void>() - 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<string>() - const beforeLoad = vi.fn( - ({ - context, - preload, - }: { - context: { auth: boolean } - preload: boolean - }) => ({ authorization: `${context.auth}:${preload}` }), - ) - const loader = vi.fn(() => loaderGate) - const rootRoute = new BaseRootRoute<any, undefined, { auth: boolean }>({}) - 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<string>() - 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<string>() - 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 deleted file mode 100644 index 2ad8017ee5..0000000000 --- a/packages/router-core/tests/preload-public-cache-behavior.test.ts +++ /dev/null @@ -1,785 +0,0 @@ -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<string>() - const loader = vi - .fn<() => string | Promise<string>>() - .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<void>() - 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<string>((_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<string>() - 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<void> | undefined - let router: ReturnType<typeof createTestRouter> - const loader = vi.fn( - ({ abortController }: { abortController: AbortController }) => { - const generation = loader.mock.calls.length - if (generation !== 2) { - return `generation ${generation}` - } - return new Promise<string>((_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<void> | undefined - let router: ReturnType<typeof createTestRouter> - const firstBeforeLoad = vi.fn( - ({ abortController }: { abortController: AbortController }) => - new Promise<void>((_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<string>((_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<string>() - 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<string>() - const secondGate = createControlledPromise<string>() - 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<string>() - 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<string>() - 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<string, unknown>) => ({ - 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<void> | undefined - let generation = 0 - let router: ReturnType<typeof createTestRouter> - 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 deleted file mode 100644 index b884a3b9ad..0000000000 --- a/packages/router-core/tests/preload-public-signal-lifetime.test.ts +++ /dev/null @@ -1,155 +0,0 @@ -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<void> - - 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 deleted file mode 100644 index 169f9e89dc..0000000000 --- a/packages/router-core/tests/public-client-loading-contract.test.ts +++ /dev/null @@ -1,768 +0,0 @@ -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<string>() - 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<void>() - const initialRenderAck = createControlledPromise<boolean>() - const successorStarted = createControlledPromise<void>() - const successorLoader = createControlledPromise<string>() - 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<void> | 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<string>() - const successorPlanned = createControlledPromise<void>() - 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<string, unknown>) => ({ - 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<void>() - const childRedirect = createControlledPromise<void>() - 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<void>() - 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<void>() - const freshHeadStarted = createControlledPromise<void>() - 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<void>() - const finalRootData = createControlledPromise<string>() - const errorComponentStarted = createControlledPromise<void>() - const errorComponentGate = createControlledPromise<void>() - 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 deleted file mode 100644 index aea458b3f5..0000000000 --- a/packages/router-core/tests/public-hydration-contract.test.ts +++ /dev/null @@ -1,1607 +0,0 @@ -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<void>() - 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<Array<string>> = [] - const headLanes: Array<Array<string>> = [] - 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<Array<string>> = [] - const headLanes: Array<Array<string>> = [] - 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<Array<string>> = [] - const headLanes: Array<Array<string>> = [] - const observeContext = ({ matches }: { matches: Array<AnyRouteMatch> }) => { - contextLanes.push(matches.map((match) => match.routeId)) - return {} - } - const observeHead = ({ matches }: { matches: Array<AnyRouteMatch> }) => { - 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<void>>() - .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<AbortSignal> = [] - 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<void>() - 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<void> | 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<void> | 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<void> | 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<string, unknown> = {} - 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<string, unknown> = {} - 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<void>() - const rootChunkStarted = createControlledPromise<void>() - 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<void>() - const childChunkStarted = createControlledPromise<void>() - 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 deleted file mode 100644 index a16c64b2dc..0000000000 --- a/packages/router-core/tests/public-preload-lane-contract.test.ts +++ /dev/null @@ -1,1475 +0,0 @@ -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<typeof createControlledPromise<void>> - >() - const beforeLoad = vi.fn(({ search }: { search: { version: number } }) => { - let gate = gates.get(search.version) - if (!gate) { - gate = createControlledPromise<void>() - 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<string, unknown>) => ({ - 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<void>() - 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<void>() - 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<unknown> | undefined - let navigation: Promise<unknown> | undefined - onTestFinished(async () => { - redirectGate.resolve() - const activeWork: Array<Promise<unknown>> = [] - 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<void>() - const loaderGate = createControlledPromise<string>() - 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<unknown> | undefined - let navigation: Promise<unknown> | 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<Promise<unknown>> = [] - 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<void>() - const loaderGate = createControlledPromise<void>() - 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<void>() - 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<string>() - 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<string>() - const navigationBeforeLoadGate = createControlledPromise<void>() - 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<string>() - const navigationBeforeLoadGate = createControlledPromise<void>() - 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<string, unknown>) => ({ - 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<string>() - 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<string, unknown>) => ({ - 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<void>() - 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<void>() - 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<string, unknown>) => ({ - 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<string>() - 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<string, unknown>) => ({ - 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<string, unknown>) => ({ - 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<string, unknown>) => ({ - 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<void>() - const failingBeforeLoadGate = createControlledPromise<void>() - 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<string, unknown>) => ({ - 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<string>() - 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 3ced74266c..ce92857ab5 100644 --- a/packages/router-core/tests/qss.test.ts +++ b/packages/router-core/tests/qss.test.ts @@ -1,74 +1,7 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' +import { describe, expect, it } 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<string> = [] - 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 deleted file mode 100644 index 9d7f611b79..0000000000 --- a/packages/router-core/tests/ready-route-loading.test.ts +++ /dev/null @@ -1,136 +0,0 @@ -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<void>() - const started = createControlledPromise<void>() - 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 deleted file mode 100644 index 63d410352a..0000000000 --- a/packages/router-core/tests/ready-route-parent-snapshot.test.ts +++ /dev/null @@ -1,103 +0,0 @@ -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<void>() - const childGate = createControlledPromise<string>() - 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 deleted file mode 100644 index b8fa439609..0000000000 --- a/packages/router-core/tests/redirect-resolution.test.ts +++ /dev/null @@ -1,144 +0,0 @@ -import { createMemoryHistory } from '@tanstack/history' -import { describe, expect, test } from 'vitest' -import { BaseRootRoute, redirect } from '../src' -import { createTestRouter } from './routerTestUtils' - -function createRouter(protocolAllowlist?: Array<string>) { - 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 deleted file mode 100644 index 4a6f5cb8fd..0000000000 --- a/packages/router-core/tests/redirect-target-error.test.ts +++ /dev/null @@ -1,635 +0,0 @@ -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<void>() - const errorComponentStarted = createControlledPromise<void>() - 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<void>() - const loaderGate = createControlledPromise<ReturnType<typeof redirect>>() - 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<void>((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<void>() - const reloadGate = createControlledPromise<ReturnType<typeof redirect>>() - 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<void>() - const loaderGate = createControlledPromise<ReturnType<typeof redirect>>() - 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<string, unknown>) => ({ - version: Number(search.version), - }), - loader: sourceLoader, - }) - const targetRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/target', - validateSearch: (search: Record<string, unknown>) => ({ - 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<void>() - const loaderGate = createControlledPromise<ReturnType<typeof redirect>>() - 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<string, unknown>) => ({ - 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/rendered-matches.test.ts b/packages/router-core/tests/rendered-matches.test.ts deleted file mode 100644 index 2a2ea362ae..0000000000 --- a/packages/router-core/tests/rendered-matches.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -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<AnyRouteMatch> - - 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<AnyRouteMatch> - - 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 deleted file mode 100644 index 044fbe38bc..0000000000 --- a/packages/router-core/tests/replace-equal-deep.bench.ts +++ /dev/null @@ -1,665 +0,0 @@ -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 deleted file mode 100644 index 1f7b88d610..0000000000 --- a/packages/router-core/tests/rewrite.bench.ts +++ /dev/null @@ -1,180 +0,0 @@ -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 deleted file mode 100644 index 2494f050e5..0000000000 --- a/packages/router-core/tests/rewrite.test.ts +++ /dev/null @@ -1,404 +0,0 @@ -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<string> = [] - 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<string> = [] - 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 deleted file mode 100644 index 8d44447b43..0000000000 --- a/packages/router-core/tests/route-initialization.test.ts +++ /dev/null @@ -1,60 +0,0 @@ -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<AnyRoute>( - 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<AnyRoute>( - 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 deleted file mode 100644 index 8743f8bc04..0000000000 --- a/packages/router-core/tests/route-interpolation.test.ts +++ /dev/null @@ -1,280 +0,0 @@ -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<Record<string, unknown>> = [ - {}, - { 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 deleted file mode 100644 index 5f2f4721cf..0000000000 --- a/packages/router-core/tests/route-tree-caches.test.ts +++ /dev/null @@ -1,415 +0,0 @@ -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<AnyRouter> = [] - 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 deleted file mode 100644 index e567f06d36..0000000000 --- a/packages/router-core/tests/route-tree-construction.bench.ts +++ /dev/null @@ -1,103 +0,0 @@ -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<Shape>(['static', 'dynamic', 'nested', 'mixed'])( - `route-tree construction (${count} routes, %s)`, - (shape) => { - let tree = createTree(count, shape) - let result = processRouteTree<AnyRoute>(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<AnyRoute>(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<AnyRoute>(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 deleted file mode 100644 index 901dedad08..0000000000 --- a/packages/router-core/tests/router-origin.test.ts +++ /dev/null @@ -1,61 +0,0 @@ -// @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 index 79a4122c74..f1c2ac40ad 100644 --- a/packages/router-core/tests/routerTestUtils.ts +++ b/packages/router-core/tests/routerTestUtils.ts @@ -1,33 +1,15 @@ -import { runInNewContext } from 'node:vm' -import { expect } from 'vitest' -import { batch, createAtom } from '@tanstack/store' -import { createMemoryHistory } from '@tanstack/history' +import { batch, createStore } from '@tanstack/store' 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' @@ -41,8 +23,8 @@ const getStoreConfig: GetStoreConfig = (opts) => { } return { - createMutableStore: createAtom, - createReadonlyStore: createAtom, + createMutableStore: createStore, + createReadonlyStore: createStore, batch, } } @@ -64,158 +46,3 @@ export function createTestRouter< ) { return new RouterCore(options, getStoreConfig) } - -type RouteTreeInput = Parameters<typeof processRouteTree>[0] -type FixtureNode = { - init?: RouteTreeInput['init'] - children?: ReadonlyArray<FixtureNode> -} - -const fixtureInit = () => {} - -function prepareFixture<T extends FixtureNode>( - route: T, -): asserts route is T & Pick<RouteTreeInput, 'init'> { - 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<RouteTreeInput, 'init'>, ->(routeTree: TRoute, caseSensitive = false) { - prepareFixture(routeTree) - return processRouteTree(routeTree, caseSensitive) -} - -export type PathInterpolationTestOptions = { - path: string - params: Record<string, unknown> - decoder?: Parameters<typeof interpolatePath>[3] - server?: boolean -} - -export function createTestPathInterpolator( - options: Pick< - RouterOptions<AnyRoute, 'never'>, - 'isServer' | 'pathParamsAllowedCharacters' - > = {}, -) { - const router = createTestRouter({ - routeTree: new BaseRootRoute({}), - history: createMemoryHistory({ initialEntries: ['/'] }), - scrollRestoration: false, - trailingSlash: 'preserve', - ...options, - }) - router.history.destroy() - return ( - options: Pick<PathInterpolationTestOptions, 'path' | 'params'>, - ): 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<TsrSsrGlobal> { - 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<string, any> = { - 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 deleted file mode 100644 index c6d65fe525..0000000000 --- a/packages/router-core/tests/same-destination-navigation-join.test.ts +++ /dev/null @@ -1,331 +0,0 @@ -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<string>() - 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<void>() - 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<void>() - const failure = new Error('first generation failed') - let successor: Promise<void> | undefined - let router: ReturnType<typeof createTestRouter> - 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<string>() - const successorBeforeLoadStarted = createControlledPromise<void>() - const successorBeforeLoadGate = createControlledPromise<void>() - const failure = new Error('reserved generation failed') - const signals: Array<AbortSignal> = [] - 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<string, unknown>) => ({ - 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<string>() - 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<string, unknown>) => ({ - 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 deleted file mode 100644 index e410d9aa55..0000000000 --- a/packages/router-core/tests/scroll-restoration-lifecycle.test.ts +++ /dev/null @@ -1,187 +0,0 @@ -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<typeof createTestRouter>[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<ScrollRestoration> = [] - 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<unknown> = [] - 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 deleted file mode 100644 index ed1f151562..0000000000 --- a/packages/router-core/tests/scroll-restoration-script.test.ts +++ /dev/null @@ -1,155 +0,0 @@ -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 deleted file mode 100644 index 03e957e3da..0000000000 --- a/packages/router-core/tests/scroll-restoration.test.ts +++ /dev/null @@ -1,322 +0,0 @@ -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<string | (() => 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<typeof createRouter>, - pathname: string, -) { - return { - ...router.latestLocation, - href: pathname, - pathname, - } -} - -function emitNavigation( - router: ReturnType<typeof createRouter>, - 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 deleted file mode 100644 index 5daec53aaa..0000000000 --- a/packages/router-core/tests/search-context-boundaries.test.ts +++ /dev/null @@ -1,57 +0,0 @@ -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<string, unknown> => 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 deleted file mode 100644 index 8f68d91b21..0000000000 --- a/packages/router-core/tests/searchMiddleware.test-d.ts +++ /dev/null @@ -1,76 +0,0 @@ -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<SearchInput, SearchOutput> = { - 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<SearchOutput>() - expectTypeOf(next).toBeCallableWith({ page: 2 }) - expectTypeOf(next).parameter(0).toEqualTypeOf<SearchOutput>() - expectTypeOf(next({ page: 2 })).toEqualTypeOf<SearchOutput>() - - 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<SearchInput, SearchOutput> = { - 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 index ee05ef8abc..10c131bfd5 100644 --- a/packages/router-core/tests/searchMiddleware.test.ts +++ b/packages/router-core/tests/searchMiddleware.test.ts @@ -13,11 +13,7 @@ describe('searchMiddleware - mutation prevention', () => { // so retainSearchParams should add them from search const result = middleware({ search: originalSearch, - next: () => - ({ - search: { page: 'new' }, - meta: {}, - }) as any, + next: () => ({ page: 'new' }) as any, }) expect(originalSearch).toEqual(originalCopy) @@ -33,11 +29,7 @@ describe('searchMiddleware - mutation prevention', () => { // next() returns object without 'id' and 'filter' keys const result1 = middleware({ search: sharedSearch, - next: () => - ({ - search: { page: '2' }, - meta: {}, - }) as any, + next: () => ({ page: '2' }) as any, }) expect(sharedSearch).toEqual({ id: '1', filter: 'active', page: '1' }) @@ -45,11 +37,7 @@ describe('searchMiddleware - mutation prevention', () => { const result2 = middleware({ search: sharedSearch, - next: () => - ({ - search: { page: '3' }, - meta: {}, - }) as any, + next: () => ({ page: '3' }) as any, }) expect(sharedSearch).toEqual({ id: '1', filter: 'active', page: '1' }) @@ -64,11 +52,7 @@ describe('searchMiddleware - mutation prevention', () => { const result = middleware({ search: originalSearch, - next: () => - ({ - search: { id: '2' }, - meta: {}, - }) as any, + next: () => ({ id: '2' }) as any, }) expect(originalSearch).toEqual(originalCopy) diff --git a/packages/router-core/tests/searchParams-parse.bench.ts b/packages/router-core/tests/searchParams-parse.bench.ts deleted file mode 100644 index 79f7e3e5ac..0000000000 --- a/packages/router-core/tests/searchParams-parse.bench.ts +++ /dev/null @@ -1,328 +0,0 @@ -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, string>): 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 deleted file mode 100644 index 32d42b96fd..0000000000 --- a/packages/router-core/tests/searchParams.bench.ts +++ /dev/null @@ -1,200 +0,0 @@ -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<string, unknown>) { - 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 ab63e6ce3b..006e119be5 100644 --- a/packages/router-core/tests/searchParams.test.ts +++ b/packages/router-core/tests/searchParams.test.ts @@ -1,10 +1,5 @@ -import { describe, expect, test, vi } from 'vitest' -import { - defaultParseSearch, - defaultStringifySearch, - parseSearchWith, - stringifySearchWith, -} from '../src' +import { describe, expect, test } from 'vitest' +import { defaultParseSearch, defaultStringifySearch } from '../src' describe('Search Params serialization and deserialization', () => { /* @@ -52,176 +47,6 @@ 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 deleted file mode 100644 index ef57474288..0000000000 --- a/packages/router-core/tests/serial-failure-foreground-prefix.test.ts +++ /dev/null @@ -1,71 +0,0 @@ -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 a688ed3b4a..4df82d5b73 100644 --- a/packages/router-core/tests/serializer-recursion.test-d.ts +++ b/packages/router-core/tests/serializer-recursion.test-d.ts @@ -3,6 +3,7 @@ import { describe, expectTypeOf, it } from 'vitest' import type { Serializable, ValidateSerializable, + ValidateSerializableResult, } from '../src/ssr/serializer/transformer' describe('ValidateSerializable array handling', () => { @@ -50,4 +51,30 @@ describe('ValidateSerializable array handling', () => { ValidateSerializable<InputStream, Serializable> >().branded.toEqualTypeOf<InputStream>() }) + + it('should preserve recursive payload without infinite expansion', () => { + type Result = Array<Result> | { [key: string]: Result } + expectTypeOf< + ValidateSerializableResult<Result, Serializable> + >().branded.toEqualTypeOf<Result>() + }) + + it('should preserve recursive tuples without infinite expansion', () => { + type ResultTuple = readonly [ + ReadonlyArray<ResultTuple>, + { [key: string]: ResultTuple }, + ] + expectTypeOf< + ValidateSerializableResult<ResultTuple, Serializable> + >().branded.toEqualTypeOf<ResultTuple>() + }) + + it('should preserve readonly recursive arrays without infinite expansion', () => { + type ResultReadonlyArray = ReadonlyArray< + ResultReadonlyArray | { [key: string]: ResultReadonlyArray } + > + expectTypeOf< + ValidateSerializableResult<ResultReadonlyArray, Serializable> + >().branded.toEqualTypeOf<ResultReadonlyArray>() + }) }) diff --git a/packages/router-core/tests/serializer.test-d.ts b/packages/router-core/tests/serializer.test-d.ts index 5ef3e3964b..4fd2c69faa 100644 --- a/packages/router-core/tests/serializer.test-d.ts +++ b/packages/router-core/tests/serializer.test-d.ts @@ -1,18 +1,68 @@ import { describe, expectTypeOf, it } from 'vitest' -import type { +import { 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<typeof value, Serializable> + >().toBeString() + }) + it('number', () => { + const value: number = 123 + + expectTypeOf< + ValidateSerializableResult<typeof value, Serializable> + >().toBeNumber() + }) + it('boolean', () => { + const value: boolean = true + + expectTypeOf< + ValidateSerializableResult<typeof value, Serializable> + >().toBeBoolean() + }) + it('null', () => { + const value = null + + expectTypeOf< + ValidateSerializableResult<typeof value, Serializable> + >().toBeNull() + }) + it('undefined', () => { + const value = undefined + + expectTypeOf< + ValidateSerializableResult<typeof value, Serializable> + >().toBeUndefined() + }) + it('bigint', () => { + const value = BigInt(123) + + expectTypeOf< + ValidateSerializableResult<typeof value, Serializable> + >().toBeBigInt() + }) + it('Date', () => { + const value = new Date() + + expectTypeOf< + ValidateSerializableResult<typeof value, Serializable> + >().toEqualTypeOf<Date>() + }) + }) it('fails for non-serializable types', () => { const value = () => {} expectTypeOf< ValidateSerializable<typeof value, Serializable> - >().toEqualTypeOf<SerializationError<'Function may not be serializable'>>() + >().toEqualTypeOf<'Function is not serializable'>() }) 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 deleted file mode 100644 index 454e6a6bb8..0000000000 --- a/packages/router-core/tests/server-async-headers-decorative-hang.test.ts +++ /dev/null @@ -1,52 +0,0 @@ -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<Record<string, string>>() - 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 deleted file mode 100644 index 4779001305..0000000000 --- a/packages/router-core/tests/server-beforeload-preload-flag.test.ts +++ /dev/null @@ -1,88 +0,0 @@ -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<boolean> = [] - 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 deleted file mode 100644 index 662fab95f9..0000000000 --- a/packages/router-core/tests/server-chunk-failure-lifecycle.test.ts +++ /dev/null @@ -1,238 +0,0 @@ -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<unknown> = [] - const events: Array<string> = [] - - 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<void>() - const childConverted = createControlledPromise<void>() - 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<void>() - const childChunkGate = createControlledPromise<void>() - const rootChunkStarted = createControlledPromise<void>() - const childChunkStarted = createControlledPromise<void>() - 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<unknown> = [] - 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<void>((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 deleted file mode 100644 index 5fc3cc63f9..0000000000 --- a/packages/router-core/tests/server-concurrent-error-notfound.test.ts +++ /dev/null @@ -1,467 +0,0 @@ -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<void>() - const childGate = createControlledPromise<void>() - const parentStarted = createControlledPromise<void>() - const childStarted = createControlledPromise<void>() - const parentSettled = createControlledPromise<void>() - const childSettled = createControlledPromise<void>() - const settlements: Array<string> = [] - 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<void>() - const childGate = createControlledPromise<void>() - const ancestorStarted = createControlledPromise<void>() - const childStarted = createControlledPromise<void>() - const ancestorSettled = createControlledPromise<void>() - const childSettled = createControlledPromise<void>() - const settlements: Array<string> = [] - 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<AbortSignal> = [] - 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<void>() - const childRedirect = createControlledPromise<void>() - 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<void>() - const childLoader = createControlledPromise<never>() - 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 deleted file mode 100644 index 6343a08cd2..0000000000 --- a/packages/router-core/tests/server-history.test.ts +++ /dev/null @@ -1,246 +0,0 @@ -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<void> - }) => { - 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 deleted file mode 100644 index e3b5d3c3ef..0000000000 --- a/packages/router-core/tests/server-loader-abort-error.test.ts +++ /dev/null @@ -1,390 +0,0 @@ -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<void>() - const controllers: Array<AbortController> = [] - 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<string>() - 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<string>() - 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<void>() - const loader = vi.fn() - const rootRoute = new BaseRootRoute({}) - const route = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/work', - beforeLoad: ({ abortController }) => { - beforeLoadStarted.resolve() - return new Promise<void>((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<void>() - const manifest = createControlledPromise<never>() - 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<void>() - const dehydrate = createControlledPromise<never>() - 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 deleted file mode 100644 index 95a3a50317..0000000000 --- a/packages/router-core/tests/server-planning-redirect.test.ts +++ /dev/null @@ -1,79 +0,0 @@ -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 deleted file mode 100644 index 7c90f87b60..0000000000 --- a/packages/router-core/tests/server-route-lifecycle.test.ts +++ /dev/null @@ -1,76 +0,0 @@ -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<string> = [] - 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 deleted file mode 100644 index 6f8c92b6ca..0000000000 --- a/packages/router-core/tests/server-serial-ssr-notfound.test.ts +++ /dev/null @@ -1,71 +0,0 @@ -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<string> = [] - - 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 deleted file mode 100644 index 5ee27fa232..0000000000 --- a/packages/router-core/tests/server-ssr-false-assets.test.ts +++ /dev/null @@ -1,192 +0,0 @@ -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 deleted file mode 100644 index f1dcf64e14..0000000000 --- a/packages/router-core/tests/server-ssr-option-error.test.ts +++ /dev/null @@ -1,178 +0,0 @@ -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 deleted file mode 100644 index 21c1b8775a..0000000000 --- a/packages/router-core/tests/server-static-ssr.test.ts +++ /dev/null @@ -1,97 +0,0 @@ -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 deleted file mode 100644 index 7ba4dbbba0..0000000000 --- a/packages/router-core/tests/server-url-encoding.test.ts +++ /dev/null @@ -1,130 +0,0 @@ -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}}', - '<test>', - '"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<string> = [] - 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 deleted file mode 100644 index 5987b056a8..0000000000 --- a/packages/router-core/tests/sieve.test.ts +++ /dev/null @@ -1,163 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { createSieveCache } from '../src/sieve-cache' - -describe('Sieve Cache', () => { - it('stores and reads back values', () => { - const cache = createSieveCache<string, number>(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<string, number>(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<string, number>(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<string, number>(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<string, number>(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<string, number>(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<string, number>(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<string, number>(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<string, number>(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<string, number>(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<number, number>(max) - for (let i = 0; i < 500; i++) { - cache.set(i, i) - } - - const present: Array<number> = [] - 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/skip-route-on-parse-error.test.ts b/packages/router-core/tests/skip-route-on-parse-error.test.ts new file mode 100644 index 0000000000..433ecc6b9a --- /dev/null +++ b/packages/router-core/tests/skip-route-on-parse-error.test.ts @@ -0,0 +1,890 @@ +import { describe, expect, it, vi } from 'vitest' +import { findRouteMatch, processRouteTree } from '../src/new-process-route-tree' + +describe('skipRouteOnParseError', () => { + describe('basic matching with parse validation', () => { + it('matches route when parse succeeds', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/$id', + fullPath: '/$id', + path: '$id', + options: { + params: { + parse: (params: Record<string, string>) => ({ + id: parseInt(params.id!, 10), + }), + }, + skipRouteOnParseError: { params: true }, + }, + }, + ], + } + const { processedTree } = processRouteTree(tree) + const result = findRouteMatch('/123', processedTree) + expect(result?.route.id).toBe('/$id') + // params contains raw string values for interpolatePath + expect(result?.rawParams).toEqual({ id: '123' }) + // parsedParams contains the transformed values from parse + expect(result?.parsedParams).toEqual({ id: 123 }) + }) + + it('skips route when parse throws and finds no alternative', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/$id', + fullPath: '/$id', + path: '$id', + options: { + params: { + parse: (params: Record<string, string>) => { + const num = parseInt(params.id!, 10) + if (isNaN(num)) throw new Error('Not a number') + return { id: num } + }, + }, + skipRouteOnParseError: { params: true }, + }, + }, + ], + } + const { processedTree } = processRouteTree(tree) + const result = findRouteMatch('/abc', processedTree) + expect(result).toBeNull() + }) + + it('skips route when parse throws and finds alternative match', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/$id', + fullPath: '/$id', + path: '$id', + options: { + params: { + parse: (params: Record<string, string>) => { + const num = parseInt(params.id!, 10) + if (isNaN(num)) throw new Error('Not a number') + return { id: num } + }, + }, + skipRouteOnParseError: { params: true }, + }, + }, + { + id: '/$slug', + fullPath: '/$slug', + path: '$slug', + options: {}, + }, + ], + } + const { processedTree } = processRouteTree(tree) + // numeric should match the validated route + const numericResult = findRouteMatch('/123', processedTree) + expect(numericResult?.route.id).toBe('/$id') + // params contains raw string values for interpolatePath + expect(numericResult?.rawParams).toEqual({ id: '123' }) + // parsedParams contains the transformed values from parse + expect(numericResult?.parsedParams).toEqual({ id: 123 }) + + // non-numeric should fall through to the non-validated route + const slugResult = findRouteMatch('/hello-world', processedTree) + expect(slugResult?.route.id).toBe('/$slug') + expect(slugResult?.rawParams).toEqual({ slug: 'hello-world' }) + }) + }) + + describe('priority: validated routes take precedence', () => { + it('validated dynamic route has priority over non-validated dynamic route', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/$slug', + fullPath: '/$slug', + path: '$slug', + options: {}, + }, + { + id: '/$id', + fullPath: '/$id', + path: '$id', + options: { + params: { + parse: (params: Record<string, string>) => { + const num = parseInt(params.id!, 10) + if (isNaN(num)) throw new Error('Not a number') + return { id: num } + }, + }, + skipRouteOnParseError: { params: true }, + }, + }, + ], + } + const { processedTree } = processRouteTree(tree) + // validated route should be tried first + const numericResult = findRouteMatch('/123', processedTree) + expect(numericResult?.route.id).toBe('/$id') + }) + + it('static route still has priority over validated dynamic route', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/settings', + fullPath: '/settings', + path: 'settings', + options: {}, + }, + { + id: '/$id', + fullPath: '/$id', + path: '$id', + options: { + params: { + parse: (params: Record<string, string>) => { + const num = parseInt(params.id!, 10) + if (isNaN(num)) throw new Error('Not a number') + return { id: num } + }, + }, + skipRouteOnParseError: { params: true }, + }, + }, + ], + } + const { processedTree } = processRouteTree(tree) + const result = findRouteMatch('/settings', processedTree) + expect(result?.route.id).toBe('/settings') + }) + + it('deep validated route can still fallback to sibling', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + children: [ + { + id: '/$a/$b/$c', + fullPath: '/$a/$b/$c', + path: '$a/$b/$c', + options: { + params: { + parse: (params: Record<string, string>) => { + // if (params.a !== 'one') throw new Error('Invalid a') + // if (params.b !== 'two') throw new Error('Invalid b') + if (params.c !== 'three') throw new Error('Invalid c') + return params + }, + }, + skipRouteOnParseError: { params: true }, + }, + }, + { + id: '/$x/$y/$z', + fullPath: '/$x/$y/$z', + path: '$x/$y/$z', + }, + ], + } + const { processedTree } = processRouteTree(tree) + { + const result = findRouteMatch('/one/two/three', processedTree) + expect(result?.route.id).toBe('/$a/$b/$c') + } + { + const result = findRouteMatch('/one/two/wrong', processedTree) + expect(result?.route.id).toBe('/$x/$y/$z') + } + }) + }) + + describe('regex-like validation patterns', () => { + it('uuid validation pattern', () => { + const uuidRegex = + /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/$uuid', + fullPath: '/$uuid', + path: '$uuid', + options: { + params: { + parse: (params: Record<string, string>) => { + if (!uuidRegex.test(params.uuid!)) + throw new Error('Not a UUID') + return params + }, + }, + skipRouteOnParseError: { params: true }, + }, + }, + { + id: '/$slug', + fullPath: '/$slug', + path: '$slug', + options: {}, + }, + ], + } + const { processedTree } = processRouteTree(tree) + + const uuidResult = findRouteMatch( + '/550e8400-e29b-41d4-a716-446655440000', + processedTree, + ) + expect(uuidResult?.route.id).toBe('/$uuid') + + const slugResult = findRouteMatch('/my-blog-post', processedTree) + expect(slugResult?.route.id).toBe('/$slug') + }) + + it('date validation pattern (YYYY-MM-DD)', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/posts/$date', + fullPath: '/posts/$date', + path: 'posts/$date', + options: { + params: { + parse: (params: Record<string, string>) => { + const date = new Date(params.date!) + if (date.toString() === 'Invalid Date') + throw new Error('Not a date') + return { date } + }, + }, + skipRouteOnParseError: { params: true }, + }, + }, + { + id: '/posts/$slug', + fullPath: '/posts/$slug', + path: 'posts/$slug', + options: {}, + }, + ], + } + const { processedTree } = processRouteTree(tree) + + const dateResult = findRouteMatch('/posts/2024-01-15', processedTree) + expect(dateResult?.route.id).toBe('/posts/$date') + // params contains raw string values for interpolatePath + expect(dateResult?.rawParams.date).toBe('2024-01-15') + // parsedParams contains the transformed values from parse + expect(dateResult?.parsedParams?.date).toBeInstanceOf(Date) + + const slugResult = findRouteMatch('/posts/my-first-post', processedTree) + expect(slugResult?.route.id).toBe('/posts/$slug') + }) + }) + + describe('nested routes with skipRouteOnParseError', () => { + it('parent validation failure prevents child matching', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/$orgId', + fullPath: '/$orgId', + path: '$orgId', + options: { + params: { + parse: (params: Record<string, string>) => { + const num = parseInt(params.orgId!, 10) + if (isNaN(num)) throw new Error('Not a number') + return { orgId: num } + }, + }, + skipRouteOnParseError: { params: true }, + }, + children: [ + { + id: '/$orgId/settings', + fullPath: '/$orgId/settings', + path: 'settings', + options: {}, + }, + ], + }, + { + id: '/$slug/about', + fullPath: '/$slug/about', + path: '$slug/about', + options: {}, + }, + ], + } + const { processedTree } = processRouteTree(tree) + + // numeric org should match the validated route + const numericResult = findRouteMatch('/123/settings', processedTree) + expect(numericResult?.route.id).toBe('/$orgId/settings') + + // non-numeric should not match /$orgId/settings, should match /$slug/about + const slugResult = findRouteMatch('/my-org/about', processedTree) + expect(slugResult?.route.id).toBe('/$slug/about') + }) + + it('child validation failure falls back to sibling', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/users', + fullPath: '/users', + path: 'users', + options: {}, + children: [ + { + id: '/users/$userId', + fullPath: '/users/$userId', + path: '$userId', + options: { + params: { + parse: (params: Record<string, string>) => { + const num = parseInt(params.userId!, 10) + if (isNaN(num)) throw new Error('Not a number') + return { userId: num } + }, + }, + skipRouteOnParseError: { params: true }, + }, + }, + { + id: '/users/$username', + fullPath: '/users/$username', + path: '$username', + options: {}, + }, + ], + }, + ], + } + const { processedTree } = processRouteTree(tree) + + const numericResult = findRouteMatch('/users/42', processedTree) + expect(numericResult?.route.id).toBe('/users/$userId') + // params contains raw string values for interpolatePath + expect(numericResult?.rawParams).toEqual({ userId: '42' }) + // parsedParams contains the transformed values from parse + expect(numericResult?.parsedParams).toEqual({ userId: 42 }) + + const usernameResult = findRouteMatch('/users/johndoe', processedTree) + expect(usernameResult?.route.id).toBe('/users/$username') + // Non-validated route: params are raw strings, parsedParams is undefined + expect(usernameResult?.rawParams).toEqual({ username: 'johndoe' }) + expect(usernameResult?.parsedParams).toBeUndefined() + }) + }) + + describe('pathless routes with skipRouteOnParseError', () => { + // Pathless layouts with skipRouteOnParseError should gate their children + it('pathless layout with validation gates children', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/', + fullPath: '/', + path: '/', + options: {}, + }, + { + id: '/$foo/_layout', + fullPath: '/$foo', + path: '$foo', + options: { + params: { + parse: (params: Record<string, string>) => { + const num = parseInt(params.foo!, 10) + if (isNaN(num)) throw new Error('Not a number') + return { foo: num } + }, + }, + skipRouteOnParseError: { params: true }, + }, + children: [ + { + id: '/$foo/_layout/bar', + fullPath: '/$foo/bar', + path: 'bar', + options: {}, + }, + { + id: '/$foo/_layout/', + fullPath: '/$foo/', + path: '/', + options: {}, + }, + ], + }, + { + id: '/$foo/hello', + fullPath: '/$foo/hello', + path: '$foo/hello', + options: {}, + }, + ], + } + const { processedTree } = processRouteTree(tree) + + // numeric foo should match through the validated layout + const numericBarResult = findRouteMatch('/123/bar', processedTree) + expect(numericBarResult?.route.id).toBe('/$foo/_layout/bar') + + const numericIndexResult = findRouteMatch('/123', processedTree) + expect(numericIndexResult?.route.id).toBe('/$foo/_layout/') + expect(numericIndexResult?.rawParams).toEqual({ foo: '123' }) + expect(numericIndexResult?.parsedParams).toEqual({ foo: 123 }) + + // non-numeric foo should fall through to the non-validated route + const helloResult = findRouteMatch('/abc/hello', processedTree) + expect(helloResult?.route.id).toBe('/$foo/hello') + expect(helloResult?.rawParams).toEqual({ foo: 'abc' }) + + // non-numeric foo should NOT match the children of the validated layout + const barResult = findRouteMatch('/abc/bar', processedTree) + expect(barResult).toBeNull() + }) + }) + + describe('optional params with skipRouteOnParseError', () => { + it('optional param with static fallback', () => { + // Optional param with validation, with a static fallback + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/{-$lang}/home', + fullPath: '/{-$lang}/home', + path: '{-$lang}/home', + options: { + params: { + parse: (params: Record<string, string>) => { + const validLangs = ['en', 'es', 'fr', 'de'] + if (params.lang && !validLangs.includes(params.lang)) { + throw new Error('Invalid language') + } + return params + }, + }, + skipRouteOnParseError: { params: true }, + }, + }, + { + id: '/home', + fullPath: '/home', + path: 'home', + options: {}, + }, + ], + } + const { processedTree } = processRouteTree(tree) + + // valid language should match the validated route + const enResult = findRouteMatch('/en/home', processedTree) + expect(enResult?.route.id).toBe('/{-$lang}/home') + expect(enResult?.parsedParams).toEqual({ lang: 'en' }) + + // root path + home - both routes can match + // The optional route (with skipped param) has greater depth, so it wins + // This is the expected behavior per the priority system + const rootResult = findRouteMatch('/home', processedTree) + expect(rootResult?.route.id).toBe('/{-$lang}/home') + + // invalid language should NOT match the validated optional route + // and since there's no dynamic fallback, it should return null + const invalidResult = findRouteMatch('/it/home', processedTree) + expect(invalidResult).toBeNull() + }) + + it('optional param at root with validation', () => { + // Optional param that validates and allows skipping + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/{-$lang}', + fullPath: '/{-$lang}', + path: '{-$lang}', + options: { + params: { + parse: (params: Record<string, string>) => { + const validLangs = ['en', 'es', 'fr', 'de'] + if (params.lang && !validLangs.includes(params.lang)) { + throw new Error('Invalid language') + } + return params + }, + }, + skipRouteOnParseError: { params: true }, + }, + }, + ], + } + const { processedTree } = processRouteTree(tree) + + // valid language should match + const enResult = findRouteMatch('/en', processedTree) + expect(enResult?.route.id).toBe('/{-$lang}') + expect(enResult?.parsedParams).toEqual({ lang: 'en' }) + + // root path should match (optional skipped) + const rootResult = findRouteMatch('/', processedTree) + expect(rootResult?.route.id).toBe('/{-$lang}') + expect(rootResult?.parsedParams).toEqual({}) + + // invalid language should NOT match (no fallback route) + const invalidResult = findRouteMatch('/about', processedTree) + expect(invalidResult).toBeNull() + }) + }) + + describe('wildcard routes with skipRouteOnParseError', () => { + it('wildcard with validation', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/files/$', + fullPath: '/files/$', + path: 'files/$', + options: { + params: { + parse: (params: Record<string, string>) => { + if (params._splat!.includes('..')) { + throw new Error('Upward navigation not allowed') + } + return params + }, + }, + skipRouteOnParseError: { params: true }, + }, + }, + { + id: '/files', + fullPath: '/files', + path: 'files', + options: {}, + }, + ], + } + const { processedTree } = processRouteTree(tree) + + // path should match the validated wildcard route + const txtResult = findRouteMatch('/files/docs/readme.txt', processedTree) + expect(txtResult?.route.id).toBe('/files/$') + + // path with upward navigation should fall through to the static /files route + const otherResult = findRouteMatch( + '/files/../../secret/photo.jpg', + processedTree, + true, + ) + expect(otherResult?.route.id).toBe('/files') + expect(otherResult?.rawParams['**']).toBe('../../secret/photo.jpg') + }) + it('index parse failure does not block wildcard sibling', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/a/', + fullPath: '/a/', + path: 'a/', + options: { + params: { + parse: () => { + throw new Error('Invalid index') + }, + }, + skipRouteOnParseError: { params: true }, + }, + }, + { + id: '/a/$', + fullPath: '/a/$', + path: 'a/$', + options: {}, + }, + ], + } + const { processedTree } = processRouteTree(tree) + const result = findRouteMatch('/a', processedTree) + expect(result?.route.id).toBe('/a/$') + expect(result?.rawParams).toEqual({ '*': '', _splat: '' }) + }) + }) + + describe('multiple validated routes competing', () => { + it('first matching validated route wins', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/$uuid', + fullPath: '/$uuid', + path: '$uuid', + options: { + params: { + parse: (params: Record<string, string>) => { + const uuidRegex = + /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i + if (!uuidRegex.test(params.uuid!)) + throw new Error('Not a UUID') + return params + }, + }, + skipRouteOnParseError: { params: true }, + }, + }, + { + id: '/$number', + fullPath: '/$number', + path: '$number', + options: { + params: { + parse: (params: Record<string, string>) => { + const num = parseInt(params.number!, 10) + if (isNaN(num)) throw new Error('Not a number') + return { number: num } + }, + }, + skipRouteOnParseError: { params: true }, + }, + }, + { + id: '/$slug', + fullPath: '/$slug', + path: '$slug', + options: {}, + }, + ], + } + const { processedTree } = processRouteTree(tree) + + const uuidResult = findRouteMatch( + '/550e8400-e29b-41d4-a716-446655440000', + processedTree, + ) + expect(uuidResult?.route.id).toBe('/$uuid') + + const numberResult = findRouteMatch('/42', processedTree) + expect(numberResult?.route.id).toBe('/$number') + // params contains raw string values for interpolatePath + expect(numberResult?.rawParams).toEqual({ number: '42' }) + // parsedParams contains the transformed values from parse + expect(numberResult?.parsedParams).toEqual({ number: 42 }) + + const slugResult = findRouteMatch('/hello-world', processedTree) + expect(slugResult?.route.id).toBe('/$slug') + }) + it('priority option can be used to influence order', () => { + const alphabetical = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/$a', + fullPath: '/$a', + path: '$a', + options: { + params: { + parse: (params: Record<string, string>) => params, + }, + skipRouteOnParseError: { + params: true, + priority: 1, // higher priority than /$z + }, + }, + }, + { + id: '/$z', + fullPath: '/$z', + path: '$z', + options: { + params: { + parse: (params: Record<string, string>) => params, + }, + skipRouteOnParseError: { + params: true, + priority: -1, // lower priority than /$a + }, + }, + }, + ], + } + { + const { processedTree } = processRouteTree(alphabetical) + const result = findRouteMatch('/123', processedTree) + expect(result?.route.id).toBe('/$a') + } + const reverse = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/$a', + fullPath: '/$a', + path: '$a', + options: { + params: { + parse: (params: Record<string, string>) => params, + }, + skipRouteOnParseError: { + params: true, + priority: -1, // lower priority than /$z + }, + }, + }, + { + id: '/$z', + fullPath: '/$z', + path: '$z', + options: { + params: { + parse: (params: Record<string, string>) => params, + }, + skipRouteOnParseError: { + params: true, + priority: 1, // higher priority than /$a + }, + }, + }, + ], + } + { + const { processedTree } = processRouteTree(reverse) + const result = findRouteMatch('/123', processedTree) + expect(result?.route.id).toBe('/$z') + } + }) + }) + + describe('params.parse without skipRouteOnParseError', () => { + it('params.parse is NOT called during matching when skipRouteOnParseError is false', () => { + const parse = vi.fn() + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/$id', + fullPath: '/$id', + path: '$id', + options: { + params: { parse }, + // skipRouteOnParseError is NOT set + }, + }, + ], + } + const { processedTree } = processRouteTree(tree) + const result = findRouteMatch('/123', processedTree) + expect(result?.route.id).toBe('/$id') + // parse should NOT be called during matching + expect(parse).not.toHaveBeenCalled() + // params should be raw strings + expect(result?.rawParams).toEqual({ id: '123' }) + }) + }) + + describe('edge cases', () => { + it('validation error type does not matter', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/$id', + fullPath: '/$id', + path: '$id', + options: { + params: { + parse: () => { + throw 'string error' // not an Error object + }, + }, + skipRouteOnParseError: { params: true }, + }, + }, + { + id: '/$fallback', + fullPath: '/$fallback', + path: '$fallback', + options: {}, + }, + ], + } + const { processedTree } = processRouteTree(tree) + const result = findRouteMatch('/test', processedTree) + expect(result?.route.id).toBe('/$fallback') + }) + }) +}) diff --git a/packages/router-core/tests/ssr-match-id.bench.ts b/packages/router-core/tests/ssr-match-id.bench.ts deleted file mode 100644 index 33e0bb5945..0000000000 --- a/packages/router-core/tests/ssr-match-id.bench.ts +++ /dev/null @@ -1,38 +0,0 @@ -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 index 221b15c3e6..77399edb5a 100644 --- a/packages/router-core/tests/ssr-match-id.test.ts +++ b/packages/router-core/tests/ssr-match-id.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { dehydrateSsrMatchId } from '../src/ssr/ssr-match-id' +import { dehydrateSsrMatchId, hydrateSsrMatchId } from '../src/ssr/ssr-match-id' describe('ssr match id codec', () => { it('removes forward slashes in dehydrated ids', () => { @@ -8,16 +8,19 @@ describe('ssr match id codec', () => { ) expect(dehydratedId).not.toContain('/') - expect(dehydratedId).not.toContain('\0') + expect(hydrateSsrMatchId(dehydratedId)).toBe( + '/$orgId/projects/$projectId//acme/projects/dashboard/{}', + ) }) it('leaves ids without slashes unchanged', () => { - expect(dehydrateSsrMatchId('plain-id')).toBe('plain-id') + const id = 'plain-id' + + expect(dehydrateSsrMatchId(id)).toBe(id) + expect(hydrateSsrMatchId(id)).toBe(id) }) - it('keeps distinct slash-delimited ids distinct', () => { - expect(dehydrateSsrMatchId('/posts/1')).not.toBe( - dehydrateSsrMatchId('/posts1'), - ) + it('decodes browser-normalized replacement chars back to slashes', () => { + expect(hydrateSsrMatchId('\uFFFDposts\uFFFD1')).toBe('/posts/1') }) }) diff --git a/packages/router-core/tests/ssr-server-cleanup.test.ts b/packages/router-core/tests/ssr-server-cleanup.test.ts deleted file mode 100644 index 84e718812c..0000000000 --- a/packages/router-core/tests/ssr-server-cleanup.test.ts +++ /dev/null @@ -1,1383 +0,0 @@ -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<typeof createHydrationScripts> -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, -'</script>'.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<string, any>) { - 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<T>() { - let resolve!: (value: T) => void - const promise = new Promise<T>((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${id}>${script.children ?? ''}</script>` - }) - .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<string> = [] - 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<string> = [] - 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<string>() - 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<void>() - let cancelCalls = 0 - const stream = new ReadableStream<Uint8Array>( - { - pull() { - pullStarted.resolve() - return new Promise<void>(() => {}) - }, - cancel() { - cancelCalls++ - return new Promise<void>(() => {}) - }, - }, - { 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<string>() - 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<unknown>() - 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<Record<string, unknown>>() - 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<Record<string, unknown>>() - 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<string>() - 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<string>() - completedStream.next('stream value') - completedStream.return('stream done') - const lateValue = deferred<string>() - 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<string>() - 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( - `<script>${HYDRATION_SCRIPT_BOUNDARY_SOURCE}</script>`, - ) - 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<any> = [] - 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<string>() - 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<unknown>() - const validValue = deferred<string>() - 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<string>() - 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<string>() - const onCleanup = vi.fn() - const cancelSource = vi.fn() - let loaderSignal: AbortSignal | undefined - let chunks = 0 - const source = new ReadableStream<Uint8Array>( - { - 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<string>() - 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<string> = [] - 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<Uint8Array>({ - 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<void>() - const renderResult = deferred<ReturnType<typeof createSsrStreamResponse>>() - let cleanupEffects = 0 - let cancelCalls = 0 - let lateStreamResponse!: ReturnType<typeof createSsrStreamResponse> - 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<void>(() => {}) - }, - }), - ), - ) - 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<void>() - const callbackResult = deferred<Response>() - const cancel = vi.fn((_reason: unknown) => new Promise<void>(() => {})) - 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<void>(() => {}) - }, - }), - ), - ) - }) - - 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<Uint8Array> - 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<Uint8Array>({ - 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( - `<html><body>${initialScriptHtml}ok</body></html>`, - ), - ) - 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<Uint8Array>({ - start(c) { - c.enqueue(new TextEncoder().encode('<html><body>')) - }, - cancel(reason) { - upstreamCancelled.value = true - upstreamCancelled.reason = reason - }, - }) - const aborts: Array<unknown> = [] - 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<void>(() => {})) - const source = new ReadableStream<Uint8Array>({ cancel: cancelSource }) - const transformed = transformReadableStreamWithRouter(router, source, { - signal: requestAbort.signal, - }) - const original = createSsrStreamResponse( - router, - new Response(transformed), - ) - const cancelFinal = vi.fn(() => new Promise<void>(() => {})) - 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<Uint8Array>({ - start(controller) { - controller.enqueue(new TextEncoder().encode('<html>done</html>')) - 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('<html>done</html>') - 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<Uint8Array>({ 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 <Scripts /> boundary anywhere in the document. - const html = '<html><body><main>static page</main></body></html>' - const appStream = new ReadableStream<Uint8Array>({ - 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 = '<html><body>no hydration</body></html>' - const text = await transformHtmlStringWithRouter(router, html) - - expect(text).toBe('<!DOCTYPE html>' + 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 deleted file mode 100644 index 95b7588e87..0000000000 --- a/packages/router-core/tests/ssr-server-manifest.test.ts +++ /dev/null @@ -1,557 +0,0 @@ -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<string, any> = { - 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 deleted file mode 100644 index a389d2be76..0000000000 --- a/packages/router-core/tests/stay-match-abort.test.ts +++ /dev/null @@ -1,247 +0,0 @@ -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 - * <Await>), 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<void>) { - 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 <Await>. 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<void>() - 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<AbortSignal> = [] - - 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 deleted file mode 100644 index 38fe3115c4..0000000000 --- a/packages/router-core/tests/superseded-load-await.test.ts +++ /dev/null @@ -1,90 +0,0 @@ -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<void>((resolve) => { - setTimeout(resolve, 0) - }) - -describe('superseded load await', () => { - test('router.load waits for a superseding navigation load to settle', async () => { - const firstLoaderGate = createControlledPromise<void>() - const secondLoaderGate = createControlledPromise<void>() - 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 deleted file mode 100644 index 12531988c0..0000000000 --- a/packages/router-core/tests/transformStreamBackpressure.perf.test.ts +++ /dev/null @@ -1,264 +0,0 @@ -// 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 = `<script>document.currentScript.remove()${new TextDecoder().decode(HYDRATION_SCRIPT_BOUNDARY_BYTES).slice(0, -'</script>'.length)}</script>` - -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<Uint8Array>({ - 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 - '<p></p>'.length) - const chunkStr = `<p>${filler}</p>` - const encoded = new TextEncoder().encode(chunkStr) - const firstFiller = 'a'.repeat( - CHUNK_BYTES - '<p></p>'.length - SCRIPT_BARRIER_HTML.length, - ) - const firstEncoded = new TextEncoder().encode( - `<p>${firstFiller}${SCRIPT_BARRIER_HTML}</p>`, - ) - - let produced = 0 - const stream = new ReadableStream<Uint8Array>({ - 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 deleted file mode 100644 index e5ce1d8d50..0000000000 --- a/packages/router-core/tests/transformStreamWithRouter.test.ts +++ /dev/null @@ -1,2877 +0,0 @@ -// 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 = `<script>${HYDRATION_SCRIPT_BOUNDARY_SOURCE}</script>` - -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<Omit<FakeServerSsr, 'hydrationScripts'>> & - Partial<FakeHydrationScripts> - -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<string>) => 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<FakeHydrationRecord> = [] - let listener: (() => void) | undefined - let state: HydrationScriptOutput['state'] = HydrationScriptOutputState.Waiting - let serializationTimeout: ReturnType<typeof setTimeout> | 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<Uint8Array> - push: (s: string) => void - close: () => void - error: (reason: unknown) => void - cancelled: { value: boolean; reason: unknown } -} { - let controllerRef: ReadableStreamDefaultController<Uint8Array> | undefined - const cancelled = { value: false, reason: undefined as unknown } - const encoder = new TextEncoder() - const stream = new ReadableStream<Uint8Array>({ - 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<Uint8Array>): Promise<string> { - 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<Uint8Array>, -): Promise<Buffer> { - const reader = stream.getReader() - const chunks: Array<Buffer> = [] - 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<Array<Buffer>> { - const chunks: Array<Buffer> = [] - for await (const chunk of stream) { - chunks.push(Buffer.from(chunk)) - } - return chunks -} - -async function readAllPipeableBytes(stream: Readable): Promise<Buffer> { - 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<T>() { - let resolve!: (value: T) => void - let reject!: (reason?: unknown) => void - const promise = new Promise<T>((res, rej) => { - resolve = res - reject = rej - }) - return { promise, resolve, reject } -} - -function createControlledStream<T>() { - let controller!: ReadableStreamDefaultController<T> - const stream = new ReadableStream<T>({ - 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 `<script${id}${className}${nonce}${streamPart}>${tag.children ?? ''}</script>` -} - -function renderManagedScripts(tags: Array<RouterManagedTag>) { - return tags.map(renderManagedScript).join('') -} - -function renderInitialScripts(scripts: { - before: Array<RouterManagedTag> - boundary: RouterManagedTag -}) { - return renderManagedScripts([...scripts.before, scripts.boundary]) -} - -function renderScriptBatch(parts: ReadonlyArray<string>) { - return `<script>${parts.join(';')};document.currentScript.remove()</script>` -} - -function createRealSsrRouter(dehydratedData: Record<string, any>) { - 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 <Scripts> 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 = `<html><body><main>app</main>${renderInitialScripts( - initialScripts!, - )}</body></html>` - - 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<string>() - 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(`<html><body><main>app</main>${initialHtml}</body></html>`) - 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('</body>'), - ) - }) - - test('fuses the final resolver and stream-end scripts', async () => { - const streamed = createControlledStream<string>() - 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( - `<html><body><main>app</main>${renderInitialScripts( - initialScripts!, - )}</body></html>`, - ) - - 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('</script>') - expect(endIndex).toBeLessThan(html.indexOf('</body>')) - }) - - 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<string>() - 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( - `<html><body>${renderInitialScripts(initialScripts)}</body></html>`, - ) - 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<string>() - 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('<html><body><main>app</main></body></html>') - upstream.close() - - const html = await readAll(output as any) - const documentEnd = html.indexOf('</html>') + '</html>'.length - expect(html.slice(0, documentEnd)).toBe( - '<html><body><main>app</main></body></html>', - ) - 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(`<html><body>${SCRIPT_BARRIER_HTML.slice(0, splitAt)}`) - upstream.push(`${SCRIPT_BARRIER_HTML.slice(splitAt)}<main>app</main>`) - upstream.push('</body></html>') - 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( - `<html><body><main>app</main>${SCRIPT_BARRIER_HTML.slice(0, splitAt)}`, - ) - upstream.push( - `${SCRIPT_BARRIER_HTML.slice(splitAt)}<section>after</section>`, - ) - finishSerialization() - upstream.push('</body></html>') - 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('<section>after</section>'), - ) - expect(html.indexOf(renderScriptBatch(['streamed()']))).toBeLessThan( - html.indexOf('</body>'), - ) - }) - - 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 = '<body-widget>content</body-widget>' - upstream.push(`<html><body>${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('<main>after</main></body></html>') - 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( - `<html><body>${SCRIPT_BARRIER_HTML}${rendererRecord}${renderScriptBatch([ - 'streamed()', - ])}<main>after</main></body></html>`, - ) - }) - - 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 = `<html><body>${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}<div>first</div>`) - expect(Buffer.from((await reader.read()).value!).toString()).toBe( - SCRIPT_BARRIER_HTML, - ) - expect(Buffer.from((await reader.read()).value!).toString()).toBe( - '<div>first</div>', - ) - - emitScriptBatch(['streamed()']) - upstream.push('<div>second</div>') - expect(Buffer.from((await reader.read()).value!).toString()).toBe( - '<div>second</div>', - ) - - 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<Uint8Array> | 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<Uint8Array> | 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, - '<html><body>ready</body></html>', - ), - ).resolves.toBe('<!DOCTYPE html><html><body>ready</body></html>') - 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( - '<html><body><main>eager ', - `</main>${SCRIPT_BARRIER_HTML}</body></html>`, - ) - expect(rendererHtml.indexOf('😀')).toBe( - MAX_HYDRATION_OUTPUT_CHUNK_BYTES - 1, - ) - await expect( - transformHtmlStringWithRouter(router as any, rendererHtml), - ).resolves.toBe( - '<!DOCTYPE html>' + - 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<Uint8Array>() - const rendererBytes = new TextEncoder().encode( - '<html><body>shell</body></html><script>rendererPatch()</script>', - ) - 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<Uint8Array>() - const encoder = new TextEncoder() - const prefix = '<html><body><main>shell</main>' - const suffix = '</body></html><script>rendererPatch()</script>' - 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 = '<div>first</div>' - - 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('<span>next</span></body></html>') - finishSerialization() - upstream.close() - - const remaining: Array<Uint8Array> = [] - 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}<span>next</span>${renderScriptBatch( - parts, - )}</body></html>`, - ) - 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 = - `<html><body><main>app</main>${SCRIPT_BARRIER_HTML}` + - '</body>\n</html>' - - 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, - '<html><body>ready</body></html>', - { 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<Uint8Array>() - 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<Uint8Array> - - // 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<Uint8Array>({ - pull() { - // Keep the transform's upstream read pending until cancellation. - }, - cancel() { - return new Promise<void>((resolve) => { - resolveCancel = resolve - }) - }, - }) - - const out = transformReadableStreamWithRouter( - router as any, - upstream as any, - ) - const reader = ( - out as any - ).getReader() as ReadableStreamDefaultReader<Uint8Array> - - 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('<html><body>done</body></html>') - 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<void>(() => {}) - }, - }) - 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<unknown> = [] - - 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<unknown> = [] - - 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<unknown> = [] - - const out = transformReadableStreamWithRouter( - router as any, - upstream.stream as any, - { - onAbort: (reason) => aborts.push(reason), - }, - ) - const reader = out.getReader() - - upstream.push(`<html><body>${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('<html><body>done</body></html>') - upstream.close() - - const text = await readAll(out as any) - expect(text).toBe('<html><body>done</body></html>') - 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(`<html><body>done${SCRIPT_BARRIER_HTML}</body></html>`) - upstream.close() - finishSerialization() - - const text = await readAll(out as any) - expect(text).toContain(renderScriptBatch(['pending()'])) - expect(text.indexOf(renderScriptBatch(['pending()']))).toBeLessThan( - text.indexOf('</body>'), - ) - }) - - 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<unknown> = [] - const onUnhandled = (e: PromiseRejectionEvent | any) => { - unhandled.push(e?.reason ?? e) - } - process.on('unhandledRejection', onUnhandled) - try { - const { router, cleanupCalls } = makeRouter() - - const stream = new ReadableStream<Uint8Array>({ - 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<Uint8Array> - - // 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 = `<html><body><!--$?--><template id="B:0"></template><p>loading</p><!--/$-->${SCRIPT_BARRIER_HTML}` - // Minimal resolved segment and replacement call. The runtime helper can be - // installed by the shell. - const rendererPatch = - '<div hidden id="S:0"><p>resolved</p></div>' + - '<script>applyPatch("B:0","S:0")</script>' - const appHtml = `${shell}</body></html>${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}</body></html>`, - ) - - 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('</body></html>')), - ) - 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 = - '<div hidden id="S:0">resolved</div><script>applyPatch()' + - SCRIPT_CLOSE.slice(0, splitAt) - const patchSuffix = SCRIPT_CLOSE.slice(splitAt) - - upstream.push(`${SCRIPT_BARRIER_HTML}${DOCUMENT_CLOSE}${patchPrefix}`) - expect(Buffer.from((await reader.read()).value!).toString()).toBe( - SCRIPT_BARRIER_HTML, - ) - expect(Buffer.from((await reader.read()).value!).toString()).toBe( - patchPrefix, - ) - - emitScriptBatch(['streamed()']) - upstream.push(`${patchSuffix}<div>later patch</div>`) - - expect(Buffer.from((await reader.read()).value!).toString()).toBe( - patchSuffix, - ) - expect(Buffer.from((await reader.read()).value!).toString()).toBe( - renderScriptBatch(['streamed()']), - ) - - finishSerialization() - upstream.close() - let remaining = '' - for (;;) { - const { done, value } = await reader.read() - if (done) { - break - } - remaining += Buffer.from(value).toString() - } - expect(remaining).toBe(`<div>later patch</div>${DOCUMENT_CLOSE}`) - }, - ) - - test('does not join a script close across skipped close-carry bytes', async () => { - 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 = '<script>foo="</scr<' - const patchSuffix = '12345678901234ipt>";more()</script>' - - 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 = - `<html><head></head><body><!--$?--><template id="B:0"></template>` + - `<p>loading</p><!--/$-->${SCRIPT_BARRIER_HTML}` + - '<script id="_R_">requestAnimationFrame(function(){})</script>' - const rendererPatch = - '<div hidden id="S:0"><p>resolved</p></div>' + - '<script>applyPatch("B:0","S:0")</script>' - - 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<Uint8Array | string>() - const output = transformReadableStreamWithRouter( - router as any, - upstream.stream, - { rendererSafePoint: 'script-close' }, - ) - const reader = output.getReader() - const patch = '<script>firstPatch()</script>' - const prefix = SCRIPT_BARRIER_HTML + patch - const filler = 'x'.repeat( - MAX_HYDRATION_OUTPUT_CHUNK_BYTES - prefix.length, - ) - const afterClose = '<script>lastPatch("😀")</script>' - 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( - ['', '</body>'].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 = `<html><body>${SCRIPT_BARRIER_HTML}` - const patch = '<script>beforeClose()</script>' - const beforeClose = `${shell}${patch}<main>app</main>` - const afterClose = '<script>rendererPatch()</script>' - 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( - '<main>app</main>' + prefix + afterClose + DOCUMENT_CLOSE, - ) - }, - ) - - test('reconstructs one emoji split across upstream UTF-8 byte chunks', async () => { - const { router, finishSerialization } = makeRouter() - const upstream = createControlledStream<Uint8Array>() - const out = transformReadableStreamWithRouter( - router as any, - upstream.stream as any, - ) - const encoder = new TextEncoder() - const emoji = encoder.encode('😀') - const html = `<html><body><p>😀</p>${SCRIPT_BARRIER_HTML}</body></html>` - - upstream.controller.enqueue(encoder.encode('<html><body><p>')) - upstream.controller.enqueue(emoji.slice(0, 2)) - upstream.controller.enqueue(emoji.slice(2)) - upstream.controller.enqueue( - encoder.encode(`</p>${SCRIPT_BARRIER_HTML}</body></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 = '<script>frameworkPatch()</script>' - - upstream.push(`<html><body>${SCRIPT_BARRIER_HTML}`) - expect(Buffer.from((await reader.read()).value!).toString()).toBe( - `<html><body>${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<Uint8Array>({ - pull(controller) { - produced++ - controller.enqueue( - encoder.encode( - produced === 1 - ? `<html><body><main>app</main>${SCRIPT_BARRIER_HTML}` - : `<p>app-${produced}</p>`, - ), - ) - }, - }) - 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(`<html><body>${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(`<html><body><main>app</main>${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(`<html><body><main>app</main>${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(`<html><body>${SCRIPT_BARRIER_HTML}</body></ht`) - expect(Buffer.from((await reader.read()).value!).toString()).toBe( - `<html><body>${SCRIPT_BARRIER_HTML}`, - ) - - const pendingRead = reader.read() - await flush() - emitScriptBatch(['pending()']) - finishSerialization() - upstream.close() - - expect(Buffer.from((await pendingRead).value!).toString()).toBe( - '</body></ht', - ) - reader.releaseLock() - expect(await readAll(out as any)).toBe( - '<script>pending();document.currentScript.remove()</script>', - ) - 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(`<html><body><div>a</div>${SCRIPT_BARRIER_HTML}`) - // Queue many script batches while app is still rendering. - for (let i = 0; i < 50; i++) { - emitScriptBatch([`S${i}`]) - } - upstream.push('</body></html>') - upstream.close() - finishSerialization() - - const full = await readAll(out as any) - - expect(full).toContain('<div>a</div>') - expect(full).toContain('</body></html>') - for (let i = 0; i < 50; i++) { - expect(full).toContain(renderScriptBatch([`S${i}`])) - } - // All scripts must appear before </body>. - expect(full.indexOf(renderScriptBatch(['S49']))).toBeLessThan( - full.indexOf('</body>'), - ) - }) -}) - -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 <Scripts> - // ran (initial take pending) must pass through without lifting. - emitScriptBatch([injected]) - upstream.push(`<html><body>${SCRIPT_BARRIER_HTML}`) - const first = await reader.read() - expect(first.done).toBe(false) - expect(decoder.decode(first.value)).toBe( - `<html><body>${SCRIPT_BARRIER_HTML}`, - ) - - // After the take, the real boundary lifts the barrier and the queued - // record is injected after it. - taken = true - upstream.push(`<main>x</main>${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 = '<script>const close = "</body></html>"</script>' - - emitScriptBatch([injected]) - upstream.push( - `<html><body>${inlineScript}<iframe><p></fake></body></p></iframe><main>x</main>${SCRIPT_BARRIER_HTML}</body></html>`, - ) - upstream.close() - finishSerialization() - - const full = await readAll(out as any) - expect(full).toContain(inlineScript) - expect(full.indexOf(rendered)).toBeGreaterThan(full.indexOf('</iframe>')) - expect(full.indexOf(rendered)).toBeLessThan(full.lastIndexOf('</body>')) - }) - - 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(`<html><body>${SCRIPT_BARRIER_HTML}</body></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('</body>'), - ) - }) - - 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(`<html><body><div>app</div>${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('</body></html>') - upstream.close() - finishSerialization() - - const full = await readAll(out as any) - - // Order: app div → scripts → body close. - expect(full).toContain('<div>app</div>') - expect(full).toContain(renderScriptBatch(['X'])) - expect(full).toContain(renderScriptBatch(['Y'])) - expect(full.indexOf('<div>app</div>')).toBeLessThan( - full.indexOf(renderScriptBatch(['X'])), - ) - expect(full.indexOf(renderScriptBatch(['Y']))).toBeLessThan( - full.indexOf('</body>'), - ) - }) - - test('onAbort: fires once when downstream cancels (readable wrapper)', async () => { - const { router, finishSerialization } = makeRouter() - finishSerialization() - - let produced = 0 - const upstream = new ReadableStream<Uint8Array>({ - pull(controller) { - produced++ - controller.enqueue(new TextEncoder().encode('<p>x</p>')) - }, - }) - - 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<Uint8Array>({ - start(controller) { - controller.enqueue(new TextEncoder().encode('<p>done</p>')) - 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 = '<html><body>string record</body></html>' - const upstream = new ReadableStream<string>({ - 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 = [ - '<html><body>', - highSurrogate, - lowSurrogate, - '</body></html>', - ] - 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('<html><body>', '</body></html>') - 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 = '<html><body>français</body></html>' - 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 = `<html><body>${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( - '<html><body><main>', - `</main>${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 = `<html><body>${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<void>((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('<p>x</p>') - // 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<Uint8Array>({ - 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<Uint8Array>({ - 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 deleted file mode 100644 index 2355e1c99a..0000000000 --- a/packages/router-core/tests/tsr-script-teardown.test.ts +++ /dev/null @@ -1,46 +0,0 @@ -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 deleted file mode 100644 index 4be6c0dfd6..0000000000 --- a/packages/router-core/tests/url-standard.test.ts +++ /dev/null @@ -1,96 +0,0 @@ -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<string>() }, - { - 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<string | UrlFixture> - 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 baeb751e8f..95874f230e 100644 --- a/packages/router-core/tests/utils.test.ts +++ b/packages/router-core/tests/utils.test.ts @@ -4,235 +4,11 @@ import { 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<unknown>) => - 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<any> = index ? [1] : [] - const next: Array<any> = 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) @@ -261,20 +37,20 @@ describe('replaceEqualDeep', () => { }) describe('symbol properties', () => { - it('passes objects with differing symbol values through untouched', () => { + it('should look at symbol properties in the object comparison', () => { const propertyKey = Symbol('property') const obj1 = { a: 1, [propertyKey]: 2 } const obj2 = { a: 1, [propertyKey]: 3 } const result = replaceEqualDeep(obj1, obj2) - expect(result).toBe(obj2) + expect(result).toStrictEqual(obj2) }) - it('never copies an object with symbol properties partially', () => { + it('should copy over symbol properties when creating a new object', () => { const propertyKey = Symbol('property') const obj1 = { a: 1, [propertyKey]: 2 } const obj2 = { a: 3, [propertyKey]: 2 } const result = replaceEqualDeep(obj1, obj2) - expect(result).toBe(obj2) + expect(result).toStrictEqual(obj2) }) }) @@ -358,6 +134,7 @@ 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', () => { @@ -366,6 +143,7 @@ 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', () => { @@ -406,6 +184,7 @@ 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]) }) @@ -473,35 +252,6 @@ 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<unknown> - 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 } }, @@ -519,6 +269,7 @@ 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) }) @@ -546,6 +297,7 @@ 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]) }) @@ -593,447 +345,6 @@ 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<string, unknown> = { 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<string, unknown> = { 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<string, unknown> = { 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', () => { @@ -1051,43 +362,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) }) }) @@ -1098,15 +409,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', () => { @@ -1114,15 +425,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) }) }) }) @@ -1131,15 +442,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, true)).toEqual(true) - expect(deepEqual(b, a, true)).toEqual(false) + expect(deepEqual(a, b, { partial: true })).toEqual(true) + expect(deepEqual(b, a, { partial: 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, true)).toEqual(true) - expect(deepEqual(b, a, true)).toEqual(false) + expect(deepEqual(a, b, { partial: true })).toEqual(true) + expect(deepEqual(b, a, { partial: true })).toEqual(false) }) }) @@ -1176,7 +487,7 @@ describe('deepEqual', () => { Object.prototype.x = 'x' const a = { a: 1 } const b = { a: 1 } - expect(deepEqual(a, b, false, true)).toEqual(true) + expect(deepEqual(a, b, { ignoreUndefined: false })).toEqual(true) }, ) @@ -1195,7 +506,7 @@ describe('decodePath', () => { 'https://mozilla.org/?x=%25%D1%88%D0%B5%5C%D0%BB%D0%BB%D1%8B%2F' const expectedResult = 'https://mozilla.org/?x=%25ше%5Cллы%2F' - const result = decodePath(stringToCheck) + const result = decodePath(stringToCheck).path expect(result).toBe(expectedResult) }) @@ -1203,114 +514,112 @@ describe('decodePath', () => { it('should handle malformed percent-encodings gracefully', () => { const stringToCheck = 'path%ZZ%D1%88test%5C%C3%A9' // Malformed sequences should remain as-is, valid ones decoded - const result = decodePath(stringToCheck) + const result = decodePath(stringToCheck).path expect(result).toBe(`path%ZZ%D1%88test%5Cé`) }) it('should return empty string unchanged', () => { - expect(decodePath('')).toBe('') + expect(decodePath('').path).toBe('') }) it('should return strings without encoding unchanged', () => { const stringToCheck = 'plain-text-path' - expect(decodePath(stringToCheck)).toBe(stringToCheck) + expect(decodePath(stringToCheck).path).toBe(stringToCheck) }) it('should handle consecutive ignored characters', () => { const stringToCheck = 'test%25%25end' const expectedResult = 'test%25%25end' - expect(decodePath(stringToCheck)).toBe(expectedResult) + expect(decodePath(stringToCheck).path).toBe(expectedResult) }) it('should handle multiple ignored items of the same type with varying case', () => { const stringToCheck = '/params-ps/named/foo%2Fabc/c%2Fh' const expectedResult = '/params-ps/named/foo%2Fabc/c%2Fh' - expect(decodePath(stringToCheck)).toBe(expectedResult) + expect(decodePath(stringToCheck).path).toBe(expectedResult) const stringToCheckWithLowerCase = '/params-ps/named/foo%2Fabc/c%5C%2f%5cAh' const expectedResultWithLowerCase = '/params-ps/named/foo%2Fabc/c%5C%2f%5cAh' - expect(decodePath(stringToCheckWithLowerCase)).toBe( + expect(decodePath(stringToCheckWithLowerCase).path).toBe( 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 + it('should strip CR (%0d) to prevent open redirect', () => { + // /%0d/google.com/ decodes to /\r/google.com/ which becomes //google.com/ + // This must be sanitized to prevent protocol-relative URL interpretation const result = decodePath('/%0d/google.com/') - expect(result).toBe('/%0D/google.com/') - expect(result).not.toMatch(/^\/\//) + expect(result.path).toBe('/google.com/') + expect(result.path).not.toMatch(/^\/\//) + expect(result.handledProtocolRelativeURL).toBe(true) }) - it('should keep LF (%0a) encoded to prevent open redirect', () => { + it('should strip LF (%0a) to prevent open redirect', () => { const result = decodePath('/%0a/evil.com/') - expect(result).toBe('/%0A/evil.com/') - expect(result).not.toMatch(/^\/\//) + expect(result.path).toBe('/evil.com/') + expect(result.path).not.toMatch(/^\/\//) + expect(result.handledProtocolRelativeURL).toBe(true) }) - it('should keep CRLF (%0d%0a) encoded to prevent open redirect', () => { + it('should strip CRLF (%0d%0a) to prevent open redirect', () => { const result = decodePath('/%0d%0a/evil.com/') - expect(result).toBe('/%0D%0A/evil.com/') - expect(result).not.toMatch(/^\/\//) + expect(result.path).toBe('/evil.com/') + expect(result.path).not.toMatch(/^\/\//) + expect(result.handledProtocolRelativeURL).toBe(true) }) - it('should keep multiple control characters encoded', () => { + it('should strip multiple control characters to prevent open redirect', () => { const result = decodePath('/%0d%0d%0d/evil.com/') - expect(result).toBe('/%0D%0D%0D/evil.com/') - expect(result).not.toMatch(/^\/\//) + expect(result.path).toBe('/evil.com/') + expect(result.path).not.toMatch(/^\/\//) + expect(result.handledProtocolRelativeURL).toBe(true) }) - it('should keep null bytes encoded', () => { + it('should strip null bytes and other control characters', () => { const result = decodePath('/%00/test/') - expect(result).toBe('/%00/test/') + expect(result.path).toBe('/test/') + expect(result.handledProtocolRelativeURL).toBe(true) + }) + + it('should collapse leading double slashes to prevent protocol-relative URLs', () => { + // After stripping control chars, ensure we don't end up with //evil.com + const result = decodePath('/%0d%0a/evil.com/path') + // Should resolve to localhost, not evil.com + const url = new URL(result.path, 'http://localhost:3000') + expect(url.origin).toBe('http://localhost:3000') + expect(result.handledProtocolRelativeURL).toBe(true) }) 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') + expect(decodePath('/users/profile/').path).toBe('/users/profile/') + expect(decodePath('/users/profile/').handledProtocolRelativeURL).toBe( + false, + ) + expect(decodePath('/api/v1/data').path).toBe('/api/v1/data') + expect(decodePath('/api/v1/data').handledProtocolRelativeURL).toBe(false) }) - 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('/шеллы') + it('should handle double slash only input', () => { + // Direct // input should also be collapsed + const result = decodePath('//') + expect(result.path).toBe('/') + expect(result.handledProtocolRelativeURL).toBe(true) }) }) }) /** - * Tests for the key handling of replaceEqualDeep. + * Tests for getEnumerableOwnKeys behavior (internal function). + * Tested indirectly through replaceEqualDeep since getEnumerableOwnKeys is not exported. * - * 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). + * getEnumerableOwnKeys should: + * 1. Return array of all enumerable own keys (strings + symbols) + * 2. Return false if any property is non-enumerable + * 3. Handle objects with no symbols efficiently (optimization target) */ -describe('key handling (via replaceEqualDeep)', () => { +describe('getEnumerableOwnKeys behavior (via replaceEqualDeep)', () => { describe('plain objects with string keys only', () => { it('should handle empty objects', () => { const prev = {} @@ -1381,24 +690,24 @@ describe('key handling (via replaceEqualDeep)', () => { }) }) - describe('objects with symbol keys pass through untouched', () => { - it('returns next for a single symbol key', () => { + describe('objects with symbol keys', () => { + it('should handle objects with single symbol key', () => { const sym = Symbol('test') const prev = { [sym]: 1 } const next = { [sym]: 1 } - expect(replaceEqualDeep(prev, next)).toBe(next) + expect(replaceEqualDeep(prev, next)).toBe(prev) }) - it('returns next for multiple symbol keys', () => { + it('should handle objects with 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) + expect(replaceEqualDeep(prev, next)).toBe(prev) }) - it('keeps differing symbol values', () => { + it('should detect differences in symbol values', () => { const sym = Symbol('test') const prev = { [sym]: 1 } const next = { [sym]: 2 } @@ -1407,100 +716,23 @@ describe('key handling (via replaceEqualDeep)', () => { expect(result[sym]).toBe(2) }) - it('returns next for global symbols', () => { + it('should handle 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') + expect(replaceEqualDeep(prev, next)).toBe(prev) }) }) describe('objects with mixed string and symbol keys', () => { - it('returns next when both string and symbol keys are present', () => { + it('should handle objects with both string and symbol keys', () => { 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) + expect(replaceEqualDeep(prev, next)).toBe(prev) }) - it('keeps string differences when symbols present', () => { + it('should detect differences in string keys when symbols present', () => { const sym = Symbol('test') const prev = { a: 1, b: 2, [sym]: 3 } const next = { a: 1, b: 99, [sym]: 3 } @@ -1510,7 +742,7 @@ describe('key handling (via replaceEqualDeep)', () => { expect(result[sym]).toBe(3) }) - it('keeps symbol differences when strings present', () => { + it('should detect differences in symbol keys when strings present', () => { const sym = Symbol('test') const prev = { a: 1, b: 2, [sym]: 3 } const next = { a: 1, b: 2, [sym]: 99 } @@ -1520,20 +752,11 @@ describe('key handling (via replaceEqualDeep)', () => { expect(result[sym]).toBe(99) }) - it('shares plain siblings around a nested symbol-keyed object', () => { + it('should handle complex nested objects with symbols', () => { 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) + const prev = { outer: { inner: 1, [sym]: { deep: 'value' } } } + const next = { outer: { inner: 1, [sym]: { deep: 'value' } } } + expect(replaceEqualDeep(prev, next)).toBe(prev) }) }) @@ -1700,53 +923,6 @@ describe('key handling (via replaceEqualDeep)', () => { ] 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<string, number> = { a: 1 } - Object.defineProperty(prevInner, 'hidden', { - value: 2, - enumerable: false, - }) - const nextInner: Record<string, number> = { 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) - }) }) }) diff --git a/packages/router-core/tsconfig.build.json b/packages/router-core/tsconfig.build.json deleted file mode 100644 index 92be18587f..0000000000 --- a/packages/router-core/tsconfig.build.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "rootDir": "./src" - }, - "include": ["src"] -} diff --git a/packages/router-core/tsconfig.json b/packages/router-core/tsconfig.json index 34cb3c4dc9..2685821ee8 100644 --- a/packages/router-core/tsconfig.json +++ b/packages/router-core/tsconfig.json @@ -1,16 +1,9 @@ { "extends": "../../tsconfig.json", "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" - ] + "include": ["src", "vite.config.ts", "tests", "vite-minify-plugin.ts"] } diff --git a/packages/router-core/vite-minify-plugin.ts b/packages/router-core/vite-minify-plugin.ts index adeb8fb5c2..e379f16ea4 100644 --- a/packages/router-core/vite-minify-plugin.ts +++ b/packages/router-core/vite-minify-plugin.ts @@ -14,16 +14,8 @@ 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(normalizedCode)};`, + code: `export default ${JSON.stringify(result.code)};`, map: null, } }, diff --git a/packages/router-core/vite.config.ts b/packages/router-core/vite.config.ts index 97859dda97..caf1c466d5 100644 --- a/packages/router-core/vite.config.ts +++ b/packages/router-core/vite.config.ts @@ -7,25 +7,12 @@ 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 @@ -44,14 +31,11 @@ export default mergeConfig( './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 index 63eb2961dd..63618f685e 100644 --- a/packages/router-devtools-core/CHANGELOG.md +++ b/packages/router-devtools-core/CHANGELOG.md @@ -1,95 +1,5 @@ # @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<boolean>` (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 diff --git a/packages/router-devtools-core/package.json b/packages/router-devtools-core/package.json index 24db637cc7..9f8cef7738 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.168.3", + "version": "1.167.0", "description": "Modern and scalable routing for Web applications", "author": "Tanner Linsley", "license": "MIT", @@ -25,15 +25,14 @@ ], "scripts": { "clean": "rimraf ./dist && rimraf ./coverage", - "test:eslint": "eslint ./src ./tests", - "test:unit": "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": "node ../../node_modules/typescript59/lib/tsc.js", - "test:types:ts60": "tsc6", - "test:types:ts70": "tsc", + "test:types:ts59": "tsc", "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", "build": "vite build" }, @@ -64,19 +63,13 @@ }, "dependencies": { "clsx": "^2.1.1", - "goober": "^2.1.16" + "goober": "^2.1.16", + "tiny-invariant": "^1.3.3" }, "devDependencies": { - "@testing-library/jest-dom": "catalog:", - "solid-js": "catalog:", + "solid-js": "^1.9.10", "vite": "*", - "vite-plugin-solid": "catalog:", - "@tanstack/vite-config": "catalog:", - "vitest": "catalog:", - "jsdom": "catalog:", - "@arethetypeswrong/cli": "catalog:", - "publint": "catalog:", - "rimraf": "catalog:" + "vite-plugin-solid": "^2.11.10" }, "peerDependencies": { "@tanstack/router-core": "workspace:^", diff --git a/packages/router-devtools-core/src/AgeTicker.tsx b/packages/router-devtools-core/src/AgeTicker.tsx index 5a615be54f..27d179fda1 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 { AnyRoute, AnyRouteMatch, AnyRouter } from '@tanstack/router-core' +import type { AnyRouteMatch, AnyRouter } from '@tanstack/router-core' import type { Accessor } from 'solid-js' function formatTime(ms: number) { @@ -35,9 +35,7 @@ export function AgeTicker({ return null } - const route = (router().routesById as Record<string, AnyRoute>)[ - match.routeId - ]! + const route = router().looseRoutesById[match.routeId]! if (!route.options.loader) { return null @@ -47,7 +45,7 @@ export function AgeTicker({ const staleTime = route.options.staleTime ?? router().options.defaultStaleTime ?? 0 const gcTime = - route.options.gcTime ?? router().options.defaultGcTime ?? 300_000 + route.options.gcTime ?? router().options.defaultGcTime ?? 30 * 60 * 1000 return ( <div class={cx(styles().ageTicker(age > staleTime))}> diff --git a/packages/router-devtools-core/src/BaseTanStackRouterDevtoolsPanel.tsx b/packages/router-devtools-core/src/BaseTanStackRouterDevtoolsPanel.tsx index 7efcaffca2..4ba50cf1cd 100644 --- a/packages/router-devtools-core/src/BaseTanStackRouterDevtoolsPanel.tsx +++ b/packages/router-devtools-core/src/BaseTanStackRouterDevtoolsPanel.tsx @@ -1,12 +1,6 @@ import { clsx as cx } from 'clsx' -import { - getRouteSegments, - hasKeys, - hasMissingPathParams, - interpolatePath, - rootRouteId, - trimPath, -} from '@tanstack/router-core' +import { default as invariant } from 'tiny-invariant' +import { interpolatePath, rootRouteId, trimPath } from '@tanstack/router-core' import { For, Match, @@ -181,19 +175,19 @@ function RouteComp({ // flatten all params in the router state, into a single object const allParams = Object.assign({}, ...matches().map((m) => m.params)) - const segments = getRouteSegments(route) - const pathname = segments - ? interpolatePath( - route.fullPath, - segments, - allParams, - router().pathParamsDecoder, - ) - : route.fullPath + // 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, + decoder: router().pathParamsDecoder, + }) - return segments && hasMissingPathParams(segments, allParams) - ? undefined - : pathname + // 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 ( @@ -270,6 +264,11 @@ export const BaseTanStackRouterDevtoolsPanel = const styles = useStyles() const { className, style, ...otherPanelProps } = panelProps + invariant( + router, + 'No router was found for the TanStack Router Devtools. Please place the devtools in the <RouterProvider> component tree or pass the router instance to the devtools manually.', + ) + // useStore(router.stores.__store) const [currentTab, setCurrentTab] = useLocalStorage< @@ -284,40 +283,48 @@ export const BaseTanStackRouterDevtoolsPanel = const [history, setHistory] = createSignal<Array<AnyRouteMatch>>([]) const [hasHistoryOverflowed, setHasHistoryOverflowed] = createSignal(false) - const pendingMatches = () => { - const matches = routerState().matches - return matches.some((match: AnyRouteMatch) => match.status === 'pending') - ? matches - : [] + let pendingMatches: Accessor<Array<AnyRouteMatch>> + let cachedMatches: Accessor<Array<AnyRouteMatch>> + // subscribable implementation + if ('subscribe' in router().stores.pendingMatchesSnapshot) { + const [_pendingMatches, setPendingMatches] = createSignal< + Array<AnyRouteMatch> + >([]) + pendingMatches = _pendingMatches + + const [_cachedMatches, setCachedMatches] = createSignal< + Array<AnyRouteMatch> + >([]) + cachedMatches = _cachedMatches + + type Subscribe = (fn: () => void) => { unsubscribe: () => void } + createEffect(() => { + const pendingMatchesStore = router().stores.pendingMatchesSnapshot + setPendingMatches(pendingMatchesStore.state) + const subscription = ( + (pendingMatchesStore as any).subscribe as Subscribe + )(() => { + setPendingMatches(pendingMatchesStore.state) + }) + onCleanup(() => subscription.unsubscribe()) + }) + + createEffect(() => { + const cachedMatchesStore = router().stores.cachedMatchesSnapshot + setCachedMatches(cachedMatchesStore.state) + const subscription = ( + (cachedMatchesStore as any).subscribe as Subscribe + )(() => { + setCachedMatches(cachedMatchesStore.state) + }) + onCleanup(() => subscription.unsubscribe()) + }) + } + // signal implementation + else { + pendingMatches = () => router().stores.pendingMatchesSnapshot.state + cachedMatches = () => router().stores.cachedMatchesSnapshot.state } - 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 @@ -357,7 +364,9 @@ export const BaseTanStackRouterDevtoolsPanel = ) }) - const hasSearch = createMemo(() => hasKeys(routerState().location.search)) + const hasSearch = createMemo( + () => Object.keys(routerState().location.search).length, + ) const explorerState = createMemo(() => { return { @@ -387,8 +396,11 @@ export const BaseTanStackRouterDevtoolsPanel = ![ 'stores', 'basepath', + 'injectedHtml', 'subscribers', - '_scroll', + 'latestLoadPromise', + 'navigateTimeout', + 'resetNextScroll', 'tempLocationKey', 'latestLocation', 'routeTree', @@ -714,9 +726,7 @@ export const BaseTanStackRouterDevtoolsPanel = <div class={styles().matchDetailsInfoLabel}> <div>State:</div> <div class={styles().matchDetailsInfo}> - {pendingMatches().find( - (d: AnyRouteMatch) => d.id === activeMatch()?.id, - ) + {pendingMatches().find((d) => d.id === activeMatch()?.id) ? 'Pending' : routerState().matches.find( (d: any) => d.id === activeMatch()?.id, diff --git a/packages/router-devtools-core/src/Explorer.tsx b/packages/router-devtools-core/src/Explorer.tsx index 1862ecbd16..a43cb9c95c 100644 --- a/packages/router-devtools-core/src/Explorer.tsx +++ b/packages/router-devtools-core/src/Explorer.tsx @@ -3,12 +3,7 @@ import { clsx as cx } from 'clsx' import * as goober from 'goober' import { createMemo, createSignal, useContext } from 'solid-js' import { tokens } from './tokens' -import { - displayValue, - getServerComponentSlotUsageSummary, - getServerComponentSlots, - getServerComponentType, -} from './utils' +import { displayValue } from './utils' import { ShadowDomTargetContext } from './context' import type { Accessor, JSX } from 'solid-js' @@ -17,7 +12,7 @@ type ExpanderProps = { style?: JSX.CSSProperties } -export const Expander = ({ expanded, style: _style = {} }: ExpanderProps) => { +export const Expander = ({ expanded, style = {} }: ExpanderProps) => { const styles = useStyles() return ( <span class={styles().expander}> @@ -95,12 +90,6 @@ function isIterable(x: any): x is Iterable<unknown> { return Symbol.iterator in x } -function isPlainObject(value: unknown): value is Record<string, unknown> { - if (!value || typeof value !== 'object') return false - const proto = Object.getPrototypeOf(value) - return proto === Object.prototype || proto === null -} - export function Explorer({ value, defaultExpanded, @@ -127,22 +116,7 @@ export function Explorer({ } } - if ( - Array.isArray(value()) && - (value() as Array<any>).length === 2 && - (value() as Array<any>)[0] === 'React element' && - isPlainObject((value() as Array<any>)[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<string, unknown>] - entries = [ - makeProperty({ label: '0', value: v[0] }), - ...Object.entries(v[1]).map(([key, val]) => - makeProperty({ label: key, value: val }), - ), - ] - } else if (Array.isArray(value())) { + if (Array.isArray(value())) { // any[] entries = (value() as Array<any>).map((d, i) => makeProperty({ @@ -195,72 +169,9 @@ 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 ( <div class={styles().entry}> - {serverComponentType() !== null ? ( - isCompositeWithSlots() ? ( - <> - <button - class={styles().expandButton} - onClick={() => toggleExpanded()} - > - <Expander expanded={expanded() ?? false} /> - <span>{rest.label}:</span> - <span class={styles().compositeComponent}> - {displayValue(value())} - </span> - </button> - {(expanded() ?? false) ? ( - <div class={styles().rscMetaRow}> - <span class={styles().rscMetaLabel}>slots</span> - <div class={styles().subEntries}> - {serverComponentSlots().map((name) => { - const usage = serverComponentSlotUsageSummary()[name] - if (!usage) return null - return ( - <Explorer - label={`${name}:`} - value={() => - usage.invocations.map((args) => - args.length === 1 ? args[0] : args, - ) - } - /> - ) - })} - </div> - </div> - ) : null} - </> - ) : ( - <> - <span>{rest.label}:</span>{' '} - <span - class={ - serverComponentType() === 'compositeSource' - ? styles().compositeComponent - : styles().renderableComponent - } - > - {displayValue(value())} - </span> - </> - ) - ) : subEntryPages().length ? ( + {subEntryPages().length ? ( <> <button class={styles().expandButton} @@ -339,7 +250,7 @@ export function Explorer({ } const stylesFactory = (shadowDOMTarget?: ShadowRoot) => { - const { colors, font, size, border } = tokens + const { colors, font, size, alpha, shadow, border } = tokens const { fontFamily, lineHeight, size: fontSize } = font const css = shadowDOMTarget ? goober.css.bind({ target: shadowDOMTarget }) @@ -398,67 +309,6 @@ const stylesFactory = (shadowDOMTarget?: ShadowRoot) => { value: css` color: ${colors.purple[400]}; `, - compositeComponent: css` - display: inline-flex; - align-items: center; - padding: 1px ${size[1]}; - border-radius: ${border.radius.full}; - border: 1px solid ${colors.darkGray[500]}; - background: ${colors.darkGray[700]}; - color: ${colors.cyan[300]}; - font-style: normal; - font-weight: ${font.weight.medium}; - `, - renderableComponent: css` - display: inline-flex; - align-items: center; - padding: 1px ${size[1]}; - border-radius: ${border.radius.full}; - border: 1px solid ${colors.darkGray[500]}; - background: ${colors.darkGray[700]}; - color: ${colors.teal[300]}; - font-style: normal; - font-weight: ${font.weight.medium}; - `, - rscMetaRow: css` - display: flex; - gap: ${size[1]}; - align-items: flex-start; - margin-left: calc(${size[3]} + ${size[1]}); - margin-top: ${size[0.5]}; - flex-wrap: wrap; - `, - rscMetaLabel: css` - color: ${colors.gray[500]}; - font-size: ${fontSize['2xs']}; - text-transform: uppercase; - letter-spacing: 0.06em; - padding-top: 2px; - `, - rscChipRow: css` - display: flex; - gap: ${size[1]}; - flex-wrap: wrap; - `, - rscChip: css` - display: inline-flex; - align-items: center; - gap: ${size[0.5]}; - padding: 1px ${size[1]}; - border-radius: ${border.radius.full}; - border: 1px solid ${colors.darkGray[500]}; - background: ${colors.darkGray[800]}; - color: ${colors.gray[200]}; - font-size: ${fontSize['2xs']}; - line-height: ${lineHeight.xs}; - `, - rscChipName: css` - color: ${colors.gray[100]}; - `, - rscChipMeta: css` - color: ${colors.gray[400]}; - font-size: ${fontSize['2xs']}; - `, subEntries: css` margin-left: ${size[2]}; padding-left: ${size[2]}; diff --git a/packages/router-devtools-core/src/tokens.ts b/packages/router-devtools-core/src/tokens.ts index 97ed9e4cd9..9d247cf184 100644 --- a/packages/router-devtools-core/src/tokens.ts +++ b/packages/router-devtools-core/src/tokens.ts @@ -161,37 +161,37 @@ export const tokens = { }, font: { size: { - '2xs': 'calc(var(--tsrd-font-size, 1rem) * 0.625)', - xs: 'calc(var(--tsrd-font-size, 1rem) * 0.75)', - sm: 'calc(var(--tsrd-font-size, 1rem) * 0.875)', - md: 'var(--tsrd-font-size, 1rem)', - lg: 'calc(var(--tsrd-font-size, 1rem) * 1.125)', - xl: 'calc(var(--tsrd-font-size, 1rem) * 1.25)', - '2xl': 'calc(var(--tsrd-font-size, 1rem) * 1.5)', - '3xl': 'calc(var(--tsrd-font-size, 1rem) * 1.875)', - '4xl': 'calc(var(--tsrd-font-size, 1rem) * 2.25)', - '5xl': 'calc(var(--tsrd-font-size, 1rem) * 3)', - '6xl': 'calc(var(--tsrd-font-size, 1rem) * 3.75)', - '7xl': 'calc(var(--tsrd-font-size, 1rem) * 4.5)', - '8xl': 'calc(var(--tsrd-font-size, 1rem) * 6)', - '9xl': 'calc(var(--tsrd-font-size, 1rem) * 8)', + '2xs': 'calc(var(--tsrd-font-size) * 0.625)', + xs: 'calc(var(--tsrd-font-size) * 0.75)', + sm: 'calc(var(--tsrd-font-size) * 0.875)', + md: 'var(--tsrd-font-size)', + lg: 'calc(var(--tsrd-font-size) * 1.125)', + xl: 'calc(var(--tsrd-font-size) * 1.25)', + '2xl': 'calc(var(--tsrd-font-size) * 1.5)', + '3xl': 'calc(var(--tsrd-font-size) * 1.875)', + '4xl': 'calc(var(--tsrd-font-size) * 2.25)', + '5xl': 'calc(var(--tsrd-font-size) * 3)', + '6xl': 'calc(var(--tsrd-font-size) * 3.75)', + '7xl': 'calc(var(--tsrd-font-size) * 4.5)', + '8xl': 'calc(var(--tsrd-font-size) * 6)', + '9xl': 'calc(var(--tsrd-font-size) * 8)', }, lineHeight: { - '3xs': 'calc(var(--tsrd-font-size, 1rem) * 0.75)', - '2xs': 'calc(var(--tsrd-font-size, 1rem) * 0.875)', - xs: 'calc(var(--tsrd-font-size, 1rem) * 1)', - sm: 'calc(var(--tsrd-font-size, 1rem) * 1.25)', - md: 'calc(var(--tsrd-font-size, 1rem) * 1.5)', - lg: 'calc(var(--tsrd-font-size, 1rem) * 1.75)', - xl: 'calc(var(--tsrd-font-size, 1rem) * 2)', - '2xl': 'calc(var(--tsrd-font-size, 1rem) * 2.25)', - '3xl': 'calc(var(--tsrd-font-size, 1rem) * 2.5)', - '4xl': 'calc(var(--tsrd-font-size, 1rem) * 2.75)', - '5xl': 'calc(var(--tsrd-font-size, 1rem) * 3)', - '6xl': 'calc(var(--tsrd-font-size, 1rem) * 3.25)', - '7xl': 'calc(var(--tsrd-font-size, 1rem) * 3.5)', - '8xl': 'calc(var(--tsrd-font-size, 1rem) * 3.75)', - '9xl': 'calc(var(--tsrd-font-size, 1rem) * 4)', + '3xs': 'calc(var(--tsrd-font-size) * 0.75)', + '2xs': 'calc(var(--tsrd-font-size) * 0.875)', + xs: 'calc(var(--tsrd-font-size) * 1)', + sm: 'calc(var(--tsrd-font-size) * 1.25)', + md: 'calc(var(--tsrd-font-size) * 1.5)', + lg: 'calc(var(--tsrd-font-size) * 1.75)', + xl: 'calc(var(--tsrd-font-size) * 2)', + '2xl': 'calc(var(--tsrd-font-size) * 2.25)', + '3xl': 'calc(var(--tsrd-font-size) * 2.5)', + '4xl': 'calc(var(--tsrd-font-size) * 2.75)', + '5xl': 'calc(var(--tsrd-font-size) * 3)', + '6xl': 'calc(var(--tsrd-font-size) * 3.25)', + '7xl': 'calc(var(--tsrd-font-size) * 3.5)', + '8xl': 'calc(var(--tsrd-font-size) * 3.75)', + '9xl': 'calc(var(--tsrd-font-size) * 4)', }, weight: { thin: '100', @@ -220,55 +220,55 @@ export const tokens = { border: { radius: { none: '0px', - xs: 'calc(var(--tsrd-font-size, 1rem) * 0.125)', - sm: 'calc(var(--tsrd-font-size, 1rem) * 0.25)', - md: 'calc(var(--tsrd-font-size, 1rem) * 0.375)', - lg: 'calc(var(--tsrd-font-size, 1rem) * 0.5)', - xl: 'calc(var(--tsrd-font-size, 1rem) * 0.75)', - '2xl': 'calc(var(--tsrd-font-size, 1rem) * 1)', - '3xl': 'calc(var(--tsrd-font-size, 1rem) * 1.5)', + xs: 'calc(var(--tsrd-font-size) * 0.125)', + sm: 'calc(var(--tsrd-font-size) * 0.25)', + md: 'calc(var(--tsrd-font-size) * 0.375)', + lg: 'calc(var(--tsrd-font-size) * 0.5)', + xl: 'calc(var(--tsrd-font-size) * 0.75)', + '2xl': 'calc(var(--tsrd-font-size) * 1)', + '3xl': 'calc(var(--tsrd-font-size) * 1.5)', full: '9999px', }, }, size: { 0: '0px', - 0.25: 'calc(var(--tsrd-font-size, 1rem) * 0.0625)', - 0.5: 'calc(var(--tsrd-font-size, 1rem) * 0.125)', - 1: 'calc(var(--tsrd-font-size, 1rem) * 0.25)', - 1.5: 'calc(var(--tsrd-font-size, 1rem) * 0.375)', - 2: 'calc(var(--tsrd-font-size, 1rem) * 0.5)', - 2.5: 'calc(var(--tsrd-font-size, 1rem) * 0.625)', - 3: 'calc(var(--tsrd-font-size, 1rem) * 0.75)', - 3.5: 'calc(var(--tsrd-font-size, 1rem) * 0.875)', - 4: 'calc(var(--tsrd-font-size, 1rem) * 1)', - 4.5: 'calc(var(--tsrd-font-size, 1rem) * 1.125)', - 5: 'calc(var(--tsrd-font-size, 1rem) * 1.25)', - 5.5: 'calc(var(--tsrd-font-size, 1rem) * 1.375)', - 6: 'calc(var(--tsrd-font-size, 1rem) * 1.5)', - 6.5: 'calc(var(--tsrd-font-size, 1rem) * 1.625)', - 7: 'calc(var(--tsrd-font-size, 1rem) * 1.75)', - 8: 'calc(var(--tsrd-font-size, 1rem) * 2)', - 9: 'calc(var(--tsrd-font-size, 1rem) * 2.25)', - 10: 'calc(var(--tsrd-font-size, 1rem) * 2.5)', - 11: 'calc(var(--tsrd-font-size, 1rem) * 2.75)', - 12: 'calc(var(--tsrd-font-size, 1rem) * 3)', - 14: 'calc(var(--tsrd-font-size, 1rem) * 3.5)', - 16: 'calc(var(--tsrd-font-size, 1rem) * 4)', - 20: 'calc(var(--tsrd-font-size, 1rem) * 5)', - 24: 'calc(var(--tsrd-font-size, 1rem) * 6)', - 28: 'calc(var(--tsrd-font-size, 1rem) * 7)', - 32: 'calc(var(--tsrd-font-size, 1rem) * 8)', - 36: 'calc(var(--tsrd-font-size, 1rem) * 9)', - 40: 'calc(var(--tsrd-font-size, 1rem) * 10)', - 44: 'calc(var(--tsrd-font-size, 1rem) * 11)', - 48: 'calc(var(--tsrd-font-size, 1rem) * 12)', - 52: 'calc(var(--tsrd-font-size, 1rem) * 13)', - 56: 'calc(var(--tsrd-font-size, 1rem) * 14)', - 60: 'calc(var(--tsrd-font-size, 1rem) * 15)', - 64: 'calc(var(--tsrd-font-size, 1rem) * 16)', - 72: 'calc(var(--tsrd-font-size, 1rem) * 18)', - 80: 'calc(var(--tsrd-font-size, 1rem) * 20)', - 96: 'calc(var(--tsrd-font-size, 1rem) * 24)', + 0.25: 'calc(var(--tsrd-font-size) * 0.0625)', + 0.5: 'calc(var(--tsrd-font-size) * 0.125)', + 1: 'calc(var(--tsrd-font-size) * 0.25)', + 1.5: 'calc(var(--tsrd-font-size) * 0.375)', + 2: 'calc(var(--tsrd-font-size) * 0.5)', + 2.5: 'calc(var(--tsrd-font-size) * 0.625)', + 3: 'calc(var(--tsrd-font-size) * 0.75)', + 3.5: 'calc(var(--tsrd-font-size) * 0.875)', + 4: 'calc(var(--tsrd-font-size) * 1)', + 4.5: 'calc(var(--tsrd-font-size) * 1.125)', + 5: 'calc(var(--tsrd-font-size) * 1.25)', + 5.5: 'calc(var(--tsrd-font-size) * 1.375)', + 6: 'calc(var(--tsrd-font-size) * 1.5)', + 6.5: 'calc(var(--tsrd-font-size) * 1.625)', + 7: 'calc(var(--tsrd-font-size) * 1.75)', + 8: 'calc(var(--tsrd-font-size) * 2)', + 9: 'calc(var(--tsrd-font-size) * 2.25)', + 10: 'calc(var(--tsrd-font-size) * 2.5)', + 11: 'calc(var(--tsrd-font-size) * 2.75)', + 12: 'calc(var(--tsrd-font-size) * 3)', + 14: 'calc(var(--tsrd-font-size) * 3.5)', + 16: 'calc(var(--tsrd-font-size) * 4)', + 20: 'calc(var(--tsrd-font-size) * 5)', + 24: 'calc(var(--tsrd-font-size) * 6)', + 28: 'calc(var(--tsrd-font-size) * 7)', + 32: 'calc(var(--tsrd-font-size) * 8)', + 36: 'calc(var(--tsrd-font-size) * 9)', + 40: 'calc(var(--tsrd-font-size) * 10)', + 44: 'calc(var(--tsrd-font-size) * 11)', + 48: 'calc(var(--tsrd-font-size) * 12)', + 52: 'calc(var(--tsrd-font-size) * 13)', + 56: 'calc(var(--tsrd-font-size) * 14)', + 60: 'calc(var(--tsrd-font-size) * 15)', + 64: 'calc(var(--tsrd-font-size) * 16)', + 72: 'calc(var(--tsrd-font-size) * 18)', + 80: 'calc(var(--tsrd-font-size) * 20)', + 96: 'calc(var(--tsrd-font-size) * 24)', }, shadow: { xs: (_: string = 'rgb(0 0 0 / 0.1)') => diff --git a/packages/router-devtools-core/src/useStyles.tsx b/packages/router-devtools-core/src/useStyles.tsx index 32908c524d..5524ed0ae8 100644 --- a/packages/router-devtools-core/src/useStyles.tsx +++ b/packages/router-devtools-core/src/useStyles.tsx @@ -428,7 +428,7 @@ const stylesFactory = (shadowDOMTarget?: ShadowRoot) => { line-height: ${tokens.font.lineHeight.sm}; `, matchStatus: ( - status: 'pending' | 'success' | 'error' | 'notFound', + status: 'pending' | 'success' | 'error' | 'notFound' | 'redirected', isFetching: false | 'beforeLoad' | 'loader', ) => { const colorMap = { @@ -436,6 +436,7 @@ const stylesFactory = (shadowDOMTarget?: ShadowRoot) => { success: 'green', error: 'red', notFound: 'purple', + redirected: 'gray', } as const const color = diff --git a/packages/router-devtools-core/src/utils.tsx b/packages/router-devtools-core/src/utils.tsx index 962cdaf0f3..8e497a09e9 100644 --- a/packages/router-devtools-core/src/utils.tsx +++ b/packages/router-devtools-core/src/utils.tsx @@ -25,6 +25,7 @@ export function getStatusColor(match: AnyRouteMatch) { success: 'green', error: 'red', notFound: 'purple', + redirected: 'gray', } as const return match.isFetching && match.status === 'success' @@ -103,144 +104,16 @@ export function useIsMounted() { return isMounted } -// Symbols for RSC detection -const SERVER_COMPONENT_STREAM = Symbol.for('tanstack.rsc.stream') -const RENDERABLE_RSC = Symbol.for('tanstack.rsc.renderable') -const RSC_SLOT_USAGES = Symbol.for('tanstack.rsc.slotUsages') - -export type RscSlotUsageEvent = { - slot: string - args?: Array<any> -} - -function trimTrailingUndefined<T>(arr: Array<T>): Array<T> { - let end = arr.length - while (end > 0 && arr[end - 1] === undefined) end-- - if (end === 0) return arr - return end === arr.length ? arr : arr.slice(0, end) -} - -export type ServerComponentType = - | 'compositeSource' // createCompositeComponent result (render via <CompositeComponent src={...} />) - | 'renderableValue' // renderServerComponent result (inline renderable value) - | null // not a server component - -/** - * Checks if a value is any kind of server component - */ -export const isServerComponent = (value: unknown): boolean => { - return ( - (typeof value === 'object' || typeof value === 'function') && - value !== null && - SERVER_COMPONENT_STREAM in value - ) -} - -/** - * Gets the type of server component. - * - RENDERABLE_RSC === true → renderable (from renderServerComponent) - * - RENDERABLE_RSC === false or not present → composite (from createCompositeComponent) - */ -export const getServerComponentType = (value: unknown): ServerComponentType => { - if (!isServerComponent(value)) { - return null - } - const v = value as Record<symbol, unknown> - if (RENDERABLE_RSC in v && v[RENDERABLE_RSC] === true) { - return 'renderableValue' - } - // RENDERABLE_RSC is false or not present → composite - return 'compositeSource' -} - -/** - * Gets the slot names from a composite server component (dev only) - */ -export const getServerComponentSlots = (value: unknown): Array<string> => { - if (!isServerComponent(value)) { - return [] - } - - const v = value as Record<symbol, unknown> - const out: Array<string> = [] - // Include any slot names observed via dev-only slot usage events - if (RSC_SLOT_USAGES in v) { - const usages = v[RSC_SLOT_USAGES] - if (Array.isArray(usages)) { - for (const evt of usages) { - const name = evt?.slot - if (typeof name === 'string' && !out.includes(name)) { - out.push(name) - } - } - } - } - - return out -} - -export const getServerComponentSlotUsages = ( - value: unknown, -): Array<RscSlotUsageEvent> => { - if (!isServerComponent(value)) { - return [] - } - - const v = value as Record<symbol, unknown> - if (!(RSC_SLOT_USAGES in v)) return [] - const usages = v[RSC_SLOT_USAGES] - if (!Array.isArray(usages)) return [] - - return usages.filter((d): d is RscSlotUsageEvent => { - return ( - d && - typeof d === 'object' && - typeof d.slot === 'string' && - (d.args === undefined || Array.isArray(d.args)) - ) - }) -} - -export const getServerComponentSlotUsageSummary = ( - value: unknown, -): Record<string, { count: number; invocations: Array<Array<any>> }> => { - const usages = getServerComponentSlotUsages(value) - const out: Record<string, { count: number; invocations: Array<Array<any>> }> = - {} - for (const evt of usages) { - const args = trimTrailingUndefined(evt.args ?? []) - const prev = - out[evt.slot] ?? (out[evt.slot] = { count: 0, invocations: [] }) - prev.count++ - prev.invocations.push(args) - } - return out -} - /** * Displays a string regardless the type of the data * @param {unknown} value Value to be stringified */ export const displayValue = (value: unknown) => { - if (value === 'React element') return 'React element' - const componentType = getServerComponentType(value) - if (componentType === 'compositeSource') { - const slots = getServerComponentSlots(value) - if (slots.length > 0) { - return `RSC composite source (${slots.length} ${ - slots.length === 1 ? 'slot' : 'slots' - })` - } - return 'RSC composite source' - } - if (componentType === 'renderableValue') { - return 'RSC renderable value' - } const name = Object.getOwnPropertyNames(Object(value)) const newValue = typeof value === 'bigint' ? `${value.toString()}n` : value try { return JSON.stringify(newValue, name) - } catch { + } catch (e) { return `unable to stringify` } } diff --git a/packages/router-devtools-core/tests/cache-replacement.test.ts b/packages/router-devtools-core/tests/cache-replacement.test.ts deleted file mode 100644 index e44e1cce53..0000000000 --- a/packages/router-devtools-core/tests/cache-replacement.test.ts +++ /dev/null @@ -1,105 +0,0 @@ -import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest' -import { TanStackRouterDevtoolsPanelCore } from '../src/TanStackRouterDevtoolsPanelCore' -import type { AnyRouteMatch, AnyRouter } from '@tanstack/router-core' - -function createCachedMatch(loaderData: string): AnyRouteMatch { - return { - id: 'cached-match', - routeId: '/cached', - pathname: '/cached', - params: {}, - search: {}, - status: 'success', - isFetching: false, - updatedAt: Date.now(), - loaderData, - } as AnyRouteMatch -} - -describe('cached matches', () => { - let panel: TanStackRouterDevtoolsPanelCore | undefined - - // Warm Vite's lazy transform of the panel chunk outside any test so its - // cost never counts against a test's timeout budget on slow CI runners. - beforeAll(async () => { - await import('../src/BaseTanStackRouterDevtoolsPanel') - }, 30_000) - - afterEach(() => { - panel?.unmount() - panel = undefined - document.body.innerHTML = '' - try { - window.localStorage.clear() - } catch {} - vi.useRealTimers() - }) - - it('uses the default gc time and refreshes replaced cache entries', async () => { - vi.useFakeTimers() - - const route = { - id: '/cached', - path: 'cached', - fullPath: '/cached', - rank: 0, - children: [], - options: { loader: () => undefined }, - } - const routeTree = { - id: '__root__', - path: '/', - fullPath: '/', - rank: 0, - children: [route], - options: {}, - } - const cache = new Map([['cached-match', createCachedMatch('old data')]]) - const router = { - _cache: cache, - routeTree, - routesById: { - __root__: routeTree, - '/cached': route, - }, - options: {}, - navigate: vi.fn(), - } as unknown as AnyRouter - const routerState = { - location: { - href: '/', - pathname: '/', - search: {}, - searchStr: '', - hash: '', - }, - matches: [], - } - const container = document.createElement('div') - document.body.append(container) - - panel = new TanStackRouterDevtoolsPanelCore({ router, routerState }) - panel.mount(container) - - await vi.waitFor(() => { - expect( - container.querySelector( - '[aria-label="Open match details for cached-match"]', - ), - ).not.toBeNull() - }) - expect(container.textContent).toContain('5min') - - const cachedMatch = container.querySelector( - '[aria-label="Open match details for cached-match"]', - ) as HTMLElement - cachedMatch.click() - expect(container.textContent).toContain('old data') - - cache.set('cached-match', createCachedMatch('new data')) - await vi.advanceTimersByTimeAsync(500) - - expect(container.textContent).toContain('new data') - expect(container.textContent).not.toContain('old data') - }, 10_000) -}) diff --git a/packages/router-devtools-core/tests/interpolation-navigation.test.ts b/packages/router-devtools-core/tests/interpolation-navigation.test.ts deleted file mode 100644 index d756d1d5a2..0000000000 --- a/packages/router-devtools-core/tests/interpolation-navigation.test.ts +++ /dev/null @@ -1,90 +0,0 @@ -import { beforeAll, expect, test, vi } from 'vitest' -import { - BaseRootRoute, - BaseRoute, - RouterCore, - createNonReactiveMutableStore, - createNonReactiveReadonlyStore, -} from '@tanstack/router-core' -import { TanStackRouterDevtoolsPanelCore } from '../src/TanStackRouterDevtoolsPanelCore' - -beforeAll(async () => { - await import('../src/BaseTanStackRouterDevtoolsPanel') -}, 30_000) - -test('offers navigation only when required and splat params are available', async () => { - const root = new BaseRootRoute({}) - const routeTree = root.addChildren( - ['/users/$id', '/posts/{-$category}', '/files/$'].map( - (path) => new BaseRoute({ getParentRoute: () => root, path }), - ), - ) - const router = new RouterCore({ routeTree, isServer: false }, () => ({ - createMutableStore: createNonReactiveMutableStore, - createReadonlyStore: createNonReactiveReadonlyStore, - batch: (fn) => fn(), - })) - const navigate = vi.spyOn(router, 'navigate').mockResolvedValue() - const initialState = router.state - const panel = new TanStackRouterDevtoolsPanelCore({ - router, - routerState: initialState, - }) - const container = document.createElement('div') - document.body.append(container) - panel.mount(container) - - try { - await vi.waitFor(() => { - expect( - container.querySelector('[title="Navigate to /posts"]'), - ).not.toBeNull() - }) - expect(container.querySelector('[title^="Navigate to /users/"]')).toBeNull() - expect(container.querySelector('[title^="Navigate to /files"]')).toBeNull() - - panel.setRouterState({ - ...initialState, - matches: router.matchRoutes('/users/item%20one', {}), - }) - await vi.waitFor(() => { - expect( - container.querySelector('[title="Navigate to /users/item%20one"]'), - ).not.toBeNull() - }) - container - .querySelector<HTMLButtonElement>( - '[title="Navigate to /users/item%20one"]', - )! - .click() - expect(navigate).toHaveBeenCalledWith({ - to: '/users/item%20one', - params: undefined, - search: undefined, - }) - - panel.setRouterState({ - ...initialState, - matches: router.matchRoutes('/files/docs/guide', {}), - }) - await vi.waitFor(() => { - expect( - container.querySelector('[title="Navigate to /files/docs/guide"]'), - ).not.toBeNull() - }) - expect(container.querySelector('[title^="Navigate to /users/"]')).toBeNull() - - panel.setRouterState(initialState) - await vi.waitFor(() => { - expect( - container.querySelector('[title^="Navigate to /files"]'), - ).toBeNull() - }) - } finally { - panel.unmount() - router.history.destroy() - navigate.mockRestore() - container.remove() - window.localStorage.clear() - } -}, 30_000) diff --git a/packages/router-devtools-core/tsconfig.build.json b/packages/router-devtools-core/tsconfig.build.json deleted file mode 100644 index 92be18587f..0000000000 --- a/packages/router-devtools-core/tsconfig.build.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "rootDir": "./src" - }, - "include": ["src"] -} diff --git a/packages/router-devtools-core/tsconfig.json b/packages/router-devtools-core/tsconfig.json index e24672b5de..1b802b64d1 100644 --- a/packages/router-devtools-core/tsconfig.json +++ b/packages/router-devtools-core/tsconfig.json @@ -4,5 +4,5 @@ "jsx": "preserve", "jsxImportSource": "solid-js" }, - "include": ["src", "tests", "vite.config.ts"] + "include": ["src", "vite.config.ts"] } diff --git a/packages/router-devtools-core/vite.config.ts b/packages/router-devtools-core/vite.config.ts index b14dd2bdf5..2aef1437ed 100644 --- a/packages/router-devtools-core/vite.config.ts +++ b/packages/router-devtools-core/vite.config.ts @@ -1,29 +1,14 @@ import { defineConfig, mergeConfig } from 'vitest/config' import { tanstackViteConfig } from '@tanstack/vite-config' import solid from 'vite-plugin-solid' -import packageJson from './package.json' const config = defineConfig({ plugins: [solid()], - test: { - name: packageJson.name, - dir: './tests', - watch: false, - environment: 'jsdom', - typecheck: { enabled: true }, - setupFiles: [], - server: { - deps: { - inline: [/solid-js/], - }, - }, - }, }) const merged = mergeConfig( config, tanstackViteConfig({ - tsconfigPath: './tsconfig.build.json', entry: './src/index.tsx', srcDir: './src', bundledDeps: ['solid-js', 'solid-js/web'], diff --git a/packages/router-devtools/CHANGELOG.md b/packages/router-devtools/CHANGELOG.md index 201d972d6c..f62d3935a5 100644 --- a/packages/router-devtools/CHANGELOG.md +++ b/packages/router-devtools/CHANGELOG.md @@ -1,64 +1,5 @@ # @tanstack/router-devtools -## 1.167.3 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/react-router-devtools@1.167.3 - -## 1.167.2 - -### 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), [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734), [`e9396c9`](https://github.com/TanStack/router/commit/e9396c928945d1dd6fd3f3bd8052143794f688b5)]: - - @tanstack/react-router@1.170.36 - - @tanstack/react-router-devtools@1.167.2 - -## 1.167.1 - -### Patch Changes - -- Updated dependencies [[`45c4ad8`](https://github.com/TanStack/router/commit/45c4ad8d629e291fab70c37900525449e415ffcd)]: - - @tanstack/react-router@1.170.19 - - @tanstack/react-router-devtools@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 [[`201e150`](https://github.com/TanStack/router/commit/201e150bd1412bae2faa9ce53f0fefcb7574ac14)]: - - @tanstack/react-router@1.170.0 - - @tanstack/react-router-devtools@1.167.0 - -## 1.166.13 - -### Patch Changes - -- Updated dependencies [[`6355bb7`](https://github.com/TanStack/router/commit/6355bb75f7637ba77f06a923c18fdaf37720bb48)]: - - @tanstack/react-router@1.168.15 - - @tanstack/react-router-devtools@1.166.13 - -## 1.166.12 - -### Patch Changes - -- Updated dependencies [[`459057c`](https://github.com/TanStack/router/commit/459057cd2d90cff20d20e51d4964b0a8c950555e)]: - - @tanstack/react-router@1.168.14 - - @tanstack/react-router-devtools@1.166.12 - -## 1.166.11 - -### Patch Changes - -- Updated dependencies [[`c9e1855`](https://github.com/TanStack/router/commit/c9e18555f3a5531e96de8f574cfca9edcdb18e5c)]: - - @tanstack/react-router@1.168.2 - - @tanstack/react-router-devtools@1.166.11 - ## 1.166.10 ### Patch Changes diff --git a/packages/router-devtools/package.json b/packages/router-devtools/package.json index 4158b280d7..c0122c026d 100644 --- a/packages/router-devtools/package.json +++ b/packages/router-devtools/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/router-devtools", - "version": "1.167.3", + "version": "1.166.10", "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": "node ../../node_modules/typescript59/lib/tsc.js", - "test:types:ts60": "tsc6", - "test:types:ts70": "tsc", + "test:types:ts59": "tsc", "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", "build": "vite build" }, @@ -62,22 +62,15 @@ "node": ">=20.19" }, "dependencies": { - "@tanstack/react-router-devtools": "workspace:*" + "@tanstack/react-router-devtools": "workspace:*", + "clsx": "^2.1.1", + "goober": "^2.1.16" }, "devDependencies": { - "@vitejs/plugin-react": "catalog:", - "react": "catalog:", - "react-dom": "catalog:", - "vite": "catalog:", - "@tanstack/vite-config": "catalog:", - "vitest": "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:" + "@vitejs/plugin-react": "^4.3.4", + "react": "^19.0.0", + "react-dom": "^19.0.0", + "vite": "*" }, "peerDependencies": { "@tanstack/react-router": "workspace:^", diff --git a/packages/router-devtools/tsconfig.build.json b/packages/router-devtools/tsconfig.build.json deleted file mode 100644 index 92be18587f..0000000000 --- a/packages/router-devtools/tsconfig.build.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "rootDir": "./src" - }, - "include": ["src"] -} diff --git a/packages/router-devtools/vite.config.ts b/packages/router-devtools/vite.config.ts index 8b7ba6475c..c1ef71fc07 100644 --- a/packages/router-devtools/vite.config.ts +++ b/packages/router-devtools/vite.config.ts @@ -9,7 +9,6 @@ const config = defineConfig({ export default mergeConfig( config, tanstackViteConfig({ - tsconfigPath: './tsconfig.build.json', entry: './src/index.tsx', srcDir: './src', }), diff --git a/packages/router-generator/AGENTS.md b/packages/router-generator/AGENTS.md deleted file mode 100644 index 1cc70bf370..0000000000 --- a/packages/router-generator/AGENTS.md +++ /dev/null @@ -1,6 +0,0 @@ -# Route generator - -- Preserve the existing `safeFileWrite` path: temporary-file rename, modification-time conflict retry, and post-rename stat. Keep unchanged-write suppression and main/shadow cache rotation; these protect concurrent edits, avoid watcher loops, and discard deleted routes. -- Run the complete `test:unit` target after generator changes. Its runtime phase generates fixture route trees before typechecking their consumers; `test:types` excludes the generator fixtures. -- Add generation cases under `tests/generator/<case>/`. Read [`tests/generator.test.ts`](tests/generator.test.ts) for per-case configuration and preprocessing. Change route inputs/configuration or templates, then regenerate route trees and expected snapshots through the test harness. -- `preprocess()` recreates selected route files for `file-modification*` and `custom-scaffolding`. Edit their templates/configuration/preprocessing when changing those inputs; edits to recreated files are overwritten. diff --git a/packages/router-generator/CHANGELOG.md b/packages/router-generator/CHANGELOG.md index a37550d255..3c96fc4fe6 100644 --- a/packages/router-generator/CHANGELOG.md +++ b/packages/router-generator/CHANGELOG.md @@ -1,549 +1,5 @@ # @tanstack/router-generator -## 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 - -- [#8857](https://github.com/TanStack/router/pull/8857) [`ad5b3b7`](https://github.com/TanStack/router/commit/ad5b3b7a0990eed7351d672ea6695d341108e0d6) - A pathless layout inside a route group (`routes/(group)/_layout.tsx`) or a route group's own layout (`routes/(group)/route.tsx`) is typed with the full path `'/'` in `FileRoutesByPath`, like the router gives it at runtime, instead of `''`. When no index route claims `/`, the layout also appears under `'/'` in `FileRoutesByFullPath` and `FileRoutesByTo`, as a pathless layout outside a group already does. - -- Updated dependencies [[`446ce1b`](https://github.com/TanStack/router/commit/446ce1b30650d85f1fc78f2d1ee42712e40b75c6), [`ff157f0`](https://github.com/TanStack/router/commit/ff157f0079982e90d62be7fdeecfb77e4fdcec69)]: - - @tanstack/router-utils@1.163.0 - -## 1.167.46 - -### Patch Changes - -- Updated dependencies [[`32a3360`](https://github.com/TanStack/router/commit/32a3360cba0e0f884b3215813a48c63467f5a53c)]: - - @tanstack/router-core@1.171.39 - -## 1.167.45 - -### Patch Changes - -- Updated dependencies [[`18154b1`](https://github.com/TanStack/router/commit/18154b1c45454a70aa77e9d6d27c8a6e0733d031)]: - - @tanstack/router-core@1.171.38 - -## 1.167.44 - -### Patch Changes - -- Updated dependencies [[`923d98b`](https://github.com/TanStack/router/commit/923d98b18b6cd90b6219591e20e86115dc61048e)]: - - @tanstack/router-utils@1.162.4 - -## 1.167.43 - -### Patch Changes - -- Updated dependencies [[`d6ba115`](https://github.com/TanStack/router/commit/d6ba115d5751c75e20943f0062577cf17b446d82)]: - - @tanstack/router-core@1.171.37 - -## 1.167.42 - -### Patch Changes - -- [#8664](https://github.com/TanStack/router/pull/8664) [`57bd1a9`](https://github.com/TanStack/router/commit/57bd1a92f9839af5bf773c3b36d039569fb1a41e) - Avoid overwriting a route file with the scaffold template when an in-place save finishes while the generator is reading the file. - -- Updated dependencies [[`94d6d8e`](https://github.com/TanStack/router/commit/94d6d8e49694e225cb07e2a6777633d08aeeb3c5)]: - - @tanstack/router-core@1.171.36 - -## 1.167.41 - -### 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 - -## 1.167.40 - -### Patch Changes - -- Updated dependencies [[`d521abd`](https://github.com/TanStack/router/commit/d521abd71c69f1ff010bb3def4d417cb5fa058cb)]: - - @tanstack/router-core@1.171.34 - -## 1.167.39 - -### Patch Changes - -- 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.167.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.167.37 - -### 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), [`1ca361b`](https://github.com/TanStack/router/commit/1ca361ba52a627d2f76ab33323bd83d1d0aa65a3)]: - - @tanstack/router-core@1.171.31 - -## 1.167.36 - -### 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 - -## 1.167.35 - -### Patch Changes - -- [#8300](https://github.com/TanStack/router/pull/8300) [`49bcd4d`](https://github.com/TanStack/router/commit/49bcd4db743dba4a783d5533a42a0f97a5721292) - Refresh compatible build and runtime dependencies. - -- 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-utils@1.162.3 - -## 1.167.34 - -### 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 - -## 1.167.33 - -### 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 - -## 1.167.32 - -### Patch Changes - -- Updated dependencies [[`3e016ac`](https://github.com/TanStack/router/commit/3e016ac84ffec8119f0c25cfdd1fb17e5292bd34)]: - - @tanstack/router-core@1.171.26 - -## 1.167.31 - -### 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 - -## 1.167.30 - -### 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 - -## 1.167.29 - -### Patch Changes - -- Updated dependencies [[`31882c7`](https://github.com/TanStack/router/commit/31882c7fa87debef236228831655cb112c20ce90)]: - - @tanstack/router-core@1.171.23 - -## 1.167.28 - -### Patch Changes - -- Updated dependencies [[`7e93431`](https://github.com/TanStack/router/commit/7e93431ae9ff58c91c3c5ca10ffcb8414c1d0b13)]: - - @tanstack/router-core@1.171.22 - -## 1.167.27 - -### Patch Changes - -- Updated dependencies [[`51138a8`](https://github.com/TanStack/router/commit/51138a824cea053738f125c4c95073bd6286ff05)]: - - @tanstack/router-core@1.171.21 - -## 1.167.26 - -### 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.167.25 - -### Patch Changes - -- Updated dependencies [[`ea3a665`](https://github.com/TanStack/router/commit/ea3a665d81cbb5074c2d77ec953255ab534e7db9)]: - - @tanstack/router-core@1.171.19 - -## 1.167.24 - -### 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 - -## 1.167.23 - -### Patch Changes - -- Updated dependencies [[`b2908c6`](https://github.com/TanStack/router/commit/b2908c642ac09aa08e6d965d2a820d7186e42fd5)]: - - @tanstack/router-core@1.171.17 - -## 1.167.22 - -### Patch Changes - -- Updated dependencies [[`45c4ad8`](https://github.com/TanStack/router/commit/45c4ad8d629e291fab70c37900525449e415ffcd)]: - - @tanstack/router-core@1.171.16 - -## 1.167.21 - -### Patch Changes - -- [#7845](https://github.com/TanStack/router/pull/7845) [`78dd1a6`](https://github.com/TanStack/router/commit/78dd1a645dc1a9e9f4f649d9aff12005044d4fcc) - Preserve dots in explicit virtual route paths and pathless layout IDs instead - of treating them as flat-file route separators. - -## 1.167.20 - -### Patch Changes - -- [#7751](https://github.com/TanStack/router/pull/7751) [`e56a677`](https://github.com/TanStack/router/commit/e56a67742da9021b009b8db0cdc8bfe99878c25b) - Make `buildRouteTree` route ordering deterministic. Its final sort tiebreaker compared whole route-node objects (`(d) => d`), which coerce to `"[object Object]"` and so never order — an inconsistent comparator that left routes tying on segment-count/index-token in an engine- and input-dependent order, producing non-deterministic `routeTree.gen.ts` diffs across machines. The tiebreaker now compares `routePath`, mirroring the pre-sort and giving a stable total order. - -## 1.167.19 - -### Patch Changes - -- Updated dependencies [[`e2dd204`](https://github.com/TanStack/router/commit/e2dd2049cb42eb219d3b447b8605066d19d9c1fa)]: - - @tanstack/router-core@1.171.15 - -## 1.167.18 - -### Patch Changes - -- Updated dependencies [[`9809a06`](https://github.com/TanStack/router/commit/9809a0619d4ed3fe8c2a393af5b9eca4b6c7695b)]: - - @tanstack/router-core@1.171.14 - -## 1.167.17 - -### Patch Changes - -- Updated dependencies [[`776d8ef`](https://github.com/TanStack/router/commit/776d8ef283e5bd9ffe97d43bc3a7f58064cd7e03)]: - - @tanstack/router-core@1.171.13 - -## 1.167.16 - -### Patch Changes - -- Updated dependencies [[`df1076c`](https://github.com/TanStack/router/commit/df1076c03ae5a51ab384bebd4d6afda20fb6f107)]: - - @tanstack/router-core@1.171.12 - -## 1.167.15 - -### Patch Changes - -- Updated dependencies [[`ac10815`](https://github.com/TanStack/router/commit/ac10815f387d25b15163ff711b4049e8f8482d01)]: - - @tanstack/router-core@1.171.11 - -## 1.167.14 - -### 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/router-utils@1.162.2 - - @tanstack/router-core@1.171.10 - -## 1.167.13 - -### Patch Changes - -- Updated dependencies [[`b4cd5af`](https://github.com/TanStack/router/commit/b4cd5af8d0f9d4aaa2d29095e6a261b9181bc778)]: - - @tanstack/router-core@1.171.9 - -## 1.167.12 - -### Patch Changes - -- Updated dependencies [[`2f53749`](https://github.com/TanStack/router/commit/2f5374945e2138559a51464f45a5152eae67e1dd)]: - - @tanstack/router-core@1.171.8 - -## 1.167.11 - -### Patch Changes - -- Updated dependencies [[`d1997b6`](https://github.com/TanStack/router/commit/d1997b66d7c24c1d64772bb8bab5caf9c6d9cc48)]: - - @tanstack/router-core@1.171.7 - -## 1.167.10 - -### Patch Changes - -- Updated dependencies [[`51a97a1`](https://github.com/TanStack/router/commit/51a97a167fb3ef1b8ca70fbb63db635158f43509)]: - - @tanstack/router-core@1.171.6 - -## 1.167.9 - -### Patch Changes - -- Updated dependencies [[`5268ba4`](https://github.com/TanStack/router/commit/5268ba4566233ea58880df85f167ad0401a93a46)]: - - @tanstack/router-core@1.171.5 - -## 1.167.8 - -### Patch Changes - -- Preserve escaped underscore segments when generating index routes across physical and virtual route trees, including pathless layouts, `physical()` prefixes, and `__virtual.ts` subtrees. ([#7453](https://github.com/TanStack/router/pull/7453)) - -## 1.167.7 - -### 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 - -## 1.167.6 - -### Patch Changes - -- Updated dependencies [[`5fa9e55`](https://github.com/TanStack/router/commit/5fa9e555f3a2edb5e45586623e6bcbfa7f7c7a6b)]: - - @tanstack/router-core@1.171.3 - - @tanstack/router-utils@1.162.1 - -## 1.167.5 - -### 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)) - -- Updated dependencies [[`b60eb36`](https://github.com/TanStack/router/commit/b60eb36e59e8a468ee0742cbcf7f47aca1ff1c67)]: - - @tanstack/router-core@1.171.2 - -## 1.167.4 - -### Patch Changes - -- Updated dependencies [[`d9cf933`](https://github.com/TanStack/router/commit/d9cf9331b83fcbd2abfee75d839d862f9bb18e6b)]: - - @tanstack/router-core@1.171.1 - -## 1.167.3 - -### Patch Changes - -- Updated dependencies [[`d533f87`](https://github.com/TanStack/router/commit/d533f87976704098a40b48f160b37c28c8182806)]: - - @tanstack/router-core@1.171.0 - -## 1.167.2 - -### Patch Changes - -- Fix literal underscore route paths when they are nested under pathless layouts. Virtual `route()` paths now treat leading and trailing underscores as literal URL path characters, while physical file routes continue to use bracket escapes for literal underscore segments. ([#7408](https://github.com/TanStack/router/pull/7408)) - -## 1.167.1 - -### Patch Changes - -- Updated dependencies [[`2387a2e`](https://github.com/TanStack/router/commit/2387a2eea0683004cc400b9f71bed5944eb60110)]: - - @tanstack/router-core@1.170.1 - -## 1.167.0 - -### Minor Changes - -- Clean minor bump, fresh start ([#7395](https://github.com/TanStack/router/pull/7395)) - -### Patch Changes - -- Resolve tsconfig path aliases when loading virtual route config files. ([#7382](https://github.com/TanStack/router/pull/7382)) - -- 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/router-utils@1.162.0 - - @tanstack/virtual-file-routes@1.162.0 - -## 1.166.42 - -### Patch Changes - -- Bump jiti dependency to 2.7.0. ([#7355](https://github.com/TanStack/router/pull/7355)) - -## 1.166.41 - -### Patch Changes - -- Updated dependencies [[`35e88f0`](https://github.com/TanStack/router/commit/35e88f04996d71019a1868b7b06ecb4ddbc9df9e)]: - - @tanstack/router-core@1.169.2 - -## 1.166.40 - -### 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-utils@1.161.8 - -## 1.166.39 - -### Patch Changes - -- Updated dependencies [[`4a1e63f`](https://github.com/TanStack/router/commit/4a1e63f1d1230b1ed8234609acad4639d8982c13)]: - - @tanstack/router-core@1.169.1 - -## 1.166.38 - -### Patch Changes - -- Updated dependencies [[`c992495`](https://github.com/TanStack/router/commit/c992495bf4010ff4c3597bb1f3b1ba02594e857e)]: - - @tanstack/router-core@1.169.0 - -## 1.166.37 - -### Patch Changes - -- Updated dependencies [[`b5c4183`](https://github.com/TanStack/router/commit/b5c4183ab8b44be8a75647b7f7b588ad7c146ece)]: - - @tanstack/router-core@1.168.18 - -## 1.166.36 - -### Patch Changes - -- Updated dependencies [[`493148b`](https://github.com/TanStack/router/commit/493148bc5378b7f9de1544d87f6aaa425c12eb34)]: - - @tanstack/router-core@1.168.17 - -## 1.166.35 - -### Patch Changes - -- Use jiti instead of tsx to load virtual route config files. ([#7261](https://github.com/TanStack/router/pull/7261)) - -## 1.166.34 - -### Patch Changes - -- Updated dependencies [[`4d864ee`](https://github.com/TanStack/router/commit/4d864eebbd184265eabb563d326ab409c93feb17)]: - - @tanstack/router-core@1.168.16 - -## 1.166.33 - -### Patch Changes - -- Updated dependencies [[`91a7089`](https://github.com/TanStack/router/commit/91a708989d00537a21911e74ff60bbfec8266295)]: - - @tanstack/router-utils@1.161.7 - -## 1.166.32 - -### Patch Changes - -- Updated dependencies [[`16f6892`](https://github.com/TanStack/router/commit/16f6892d6b7ceadf606677c5a40e743f29163aa6)]: - - @tanstack/router-core@1.168.15 - -## 1.166.31 - -### Patch Changes - -- Fix malformed generated paths when a `physical()` mount points at a subtree rooted by `__virtual.ts`, including nested virtual layouts that mount additional physical routes. ([#7169](https://github.com/TanStack/router/pull/7169)) - -## 1.166.30 - -### 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.166.29 - -### Patch Changes - -- Updated dependencies [[`0e2c900`](https://github.com/TanStack/router/commit/0e2c9003c18ae07c09969189c028f277ea562a7a)]: - - @tanstack/router-core@1.168.14 - -## 1.166.28 - -### Patch Changes - -- Updated dependencies [[`812792f`](https://github.com/TanStack/router/commit/812792fbda3caf97b300770855cf5641252f413b)]: - - @tanstack/router-core@1.168.13 - -## 1.166.27 - -### Patch Changes - -- Updated dependencies [[`8ec9ca9`](https://github.com/TanStack/router/commit/8ec9ca97b472779de878c2a6510f21deb24d386c)]: - - @tanstack/router-core@1.168.12 - -## 1.166.26 - -### Patch Changes - -- Updated dependencies [[`6355bb7`](https://github.com/TanStack/router/commit/6355bb75f7637ba77f06a923c18fdaf37720bb48)]: - - @tanstack/router-core@1.168.11 - -## 1.166.25 - -### Patch Changes - -- Updated dependencies [[`459057c`](https://github.com/TanStack/router/commit/459057cd2d90cff20d20e51d4964b0a8c950555e)]: - - @tanstack/router-core@1.168.10 - -## 1.166.24 - -### Patch Changes - -- Updated dependencies [[`796406d`](https://github.com/TanStack/router/commit/796406da66cfb12b518bb3ca326c9d541368fb06)]: - - @tanstack/router-core@1.168.9 - -## 1.166.23 - -### Patch Changes - -- Updated dependencies [[`2d1ec86`](https://github.com/TanStack/router/commit/2d1ec865a446926f7db6e29dbbde82d265de6d36)]: - - @tanstack/router-core@1.168.8 - -## 1.166.22 - -### Patch Changes - -- Updated dependencies [[`6ee0e79`](https://github.com/TanStack/router/commit/6ee0e795b085651beb2f1ac6503cdbd7eaffedd1)]: - - @tanstack/router-core@1.168.7 - -## 1.166.21 - -### Patch Changes - -- Updated dependencies [[`42c3f3b`](https://github.com/TanStack/router/commit/42c3f3b3a3a478fd6d6894310ef94b2d23794b8e)]: - - @tanstack/router-core@1.168.6 - -## 1.166.20 - -### Patch Changes - -- Fix file-based route generation when custom `routeToken` or `indexToken` values start with regex metacharacters like `+`. ([#7048](https://github.com/TanStack/router/pull/7048)) - -## 1.166.19 - -### Patch Changes - -- Updated dependencies [[`cf5f554`](https://github.com/TanStack/router/commit/cf5f5542476137a81515099ad740747e84512f9a)]: - - @tanstack/router-core@1.168.5 - -## 1.166.18 - -### Patch Changes - -- Updated dependencies [[`71a8b68`](https://github.com/TanStack/router/commit/71a8b684c87c37fd4a033d99f5ba4a05c7a179f5)]: - - @tanstack/router-core@1.168.4 - -## 1.166.17 - -### Patch Changes - -- Updated dependencies [[`d81d21a`](https://github.com/TanStack/router/commit/d81d21ad05c9401bf54b24acd29401e1e4fd624c)]: - - @tanstack/router-core@1.168.3 - -## 1.166.16 - -### Patch Changes - -- Updated dependencies [[`c9e1855`](https://github.com/TanStack/router/commit/c9e18555f3a5531e96de8f574cfca9edcdb18e5c)]: - - @tanstack/router-core@1.168.2 - ## 1.166.15 ### Patch Changes diff --git a/packages/router-generator/package.json b/packages/router-generator/package.json index e62e105068..109336f1a7 100644 --- a/packages/router-generator/package.json +++ b/packages/router-generator/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/router-generator", - "version": "1.168.0", + "version": "1.166.15", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", @@ -28,12 +28,12 @@ "clean:snapshots": "rimraf **/*snapshot* --glob", "test:eslint": "eslint ./src", "test:types": "pnpm run \"/^test:types:ts[0-9]{2}$/\"", + "test:types:ts54": "exit 0; 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": "node ../../node_modules/typescript59/lib/tsc.js -p tsconfig.legacy.json", - "test:types:ts60": "tsc6 -p tsconfig.legacy.json", - "test:types:ts70": "tsc -p tsconfig.legacy.json", + "test:types:ts59": "tsc -p tsconfig.legacy.json", "test:unit": "vitest --typecheck false && vitest run --typecheck.only", "test:unit:dev": "pnpm run test:unit --watch --hideSkippedTests", "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", @@ -62,39 +62,20 @@ "src" ], "engines": { - "node": "^20.19.0 || >=22.12.0" + "node": ">=20.19" }, "dependencies": { - "@babel/types": "catalog:", "@tanstack/router-core": "workspace:*", "@tanstack/router-utils": "workspace:*", "@tanstack/virtual-file-routes": "workspace:*", - "jiti": "^2.7.0", - "magic-string": "^0.30.21", - "prettier": "^3.9.6", - "zod": "catalog:" + "prettier": "^3.5.0", + "recast": "^0.23.11", + "source-map": "^0.7.4", + "tsx": "^4.19.2", + "zod": "^3.24.2" }, "devDependencies": { "@tanstack/react-router": "workspace:*", - "@types/node": ">=20", - "@types/react": "catalog:", - "react": "catalog:", - "vite": "catalog:", - "@tanstack/vite-config": "catalog:", - "vitest": "catalog:", - "@arethetypeswrong/cli": "catalog:", - "publint": "catalog:", - "rimraf": "catalog:" - }, - "nx": { - "targets": { - "test:unit": { - "outputs": [ - "...", - "{projectRoot}/tests/generator/*/routeTree.gen.{ts,js}", - "{projectRoot}/tests/generator/file-modification/routes/*/*.tsx" - ] - } - } + "vite": "*" } } diff --git a/packages/router-generator/src/config.ts b/packages/router-generator/src/config.ts index 5c719183db..f9680d9d36 100644 --- a/packages/router-generator/src/config.ts +++ b/packages/router-generator/src/config.ts @@ -49,6 +49,7 @@ export type BaseConfig = z.infer<typeof baseConfigSchema> export const configSchema = baseConfigSchema.extend({ generatedRouteTree: z.string().optional().default('./src/routeTree.gen.ts'), disableTypes: z.boolean().optional().default(false), + verboseFileRoutes: z.boolean().optional(), addExtensions: z .union([z.boolean(), z.string()]) .optional() @@ -60,7 +61,7 @@ export const configSchema = baseConfigSchema.extend({ routeTreeFileFooter: z .union([ z.array(z.string()).optional().default([]), - z.custom<() => Array<string>>((value) => typeof value === 'function'), + z.function().returns(z.array(z.string())), ]) .optional(), autoCodeSplitting: z.boolean().optional(), diff --git a/packages/router-generator/src/filesystem/physical/getRouteNodes.ts b/packages/router-generator/src/filesystem/physical/getRouteNodes.ts index 09e7fc6c25..172e5bbf50 100644 --- a/packages/router-generator/src/filesystem/physical/getRouteNodes.ts +++ b/packages/router-generator/src/filesystem/physical/getRouteNodes.ts @@ -1,12 +1,8 @@ import path from 'node:path' import * as fsp from 'node:fs/promises' import { - cleanPath, - createRoutePathSegmentMetadata, determineInitialRoutePath, - escapeRegExp, hasEscapedLeadingUnderscore, - joinRoutePathSegmentMetadata, removeExt, replaceBackslash, routePathToVariable, @@ -124,31 +120,16 @@ export async function getRouteNodes( ) allPhysicalDirectories.push(...physicalDirectories) virtualRouteNodes.forEach((node) => { - const normalizedDir = dir === './' ? '' : dir - const filePath = replaceBackslash( - path.join(normalizedDir, node.filePath), - ) - const { routePath: prefixPath, originalRoutePath: originalPrefixPath } = - normalizedDir - ? determineInitialRoutePath(normalizedDir) - : { routePath: '', originalRoutePath: '' } - const routePath = cleanPath(`${prefixPath}${node.routePath}`) + const filePath = replaceBackslash(path.join(dir, node.filePath)) + const routePath = `/${dir}${node.routePath}` node.variableName = routePathToVariable( - cleanPath(`${prefixPath}/${removeExt(node.filePath)}`), - ) - node._routePathSegmentMetadata = joinRoutePathSegmentMetadata( - routePath, - prefixPath, - createRoutePathSegmentMetadata(prefixPath, originalPrefixPath), - node._routePathSegmentMetadata, + `${dir}/${removeExt(node.filePath)}`, ) node.routePath = routePath // Keep originalRoutePath aligned with routePath for escape detection if (node.originalRoutePath) { - node.originalRoutePath = cleanPath( - `${originalPrefixPath}${node.originalRoutePath}`, - ) + node.originalRoutePath = `/${dir}${node.originalRoutePath}` } node.filePath = filePath // Virtual subtree nodes (from __virtual.ts) are embedded in a @@ -284,12 +265,9 @@ export async function getRouteNodes( if (suffixToStrip || shouldStripRouteToken) { const stripSegment = suffixToStrip ?? lastRouteSegment - routePath = routePath.replace( - new RegExp(`/${escapeRegExp(stripSegment)}$`), - '', - ) + routePath = routePath.replace(new RegExp(`/${stripSegment}$`), '') originalRoutePath = originalRoutePath.replace( - new RegExp(`/${escapeRegExp(stripSegment)}$`), + new RegExp(`/${stripSegment}$`), '', ) } @@ -316,6 +294,10 @@ export async function getRouteNodes( routePath = '/' } + if (lastOriginalSegment === updatedLastRouteSegment) { + originalRoutePath = '/' + } + // For layout routes, don't use '/' fallback - an empty path means // "layout for the parent path" which is important for physical() mounts // where route.tsx at root should have empty path, not '/' @@ -323,13 +305,13 @@ export async function getRouteNodes( routePath = routePath.replace( - new RegExp(`/${escapeRegExp(updatedLastRouteSegment)}$`), + new RegExp(`/${updatedLastRouteSegment}$`), '/', ) || (isLayoutRoute ? '' : '/') originalRoutePath = originalRoutePath.replace( - new RegExp(`/${escapeRegExp(indexTokenCandidate)}$`), + new RegExp(`/${indexTokenCandidate}$`), '/', ) || (isLayoutRoute ? '' : '/') } @@ -342,10 +324,6 @@ export async function getRouteNodes( variableName, _fsRouteType: routeType, originalRoutePath, - _routePathSegmentMetadata: createRoutePathSegmentMetadata( - routePath, - originalRoutePath, - ), }) } }), diff --git a/packages/router-generator/src/filesystem/virtual/getRouteNodes.ts b/packages/router-generator/src/filesystem/virtual/getRouteNodes.ts index 5d3cd610be..3a603d5769 100644 --- a/packages/router-generator/src/filesystem/virtual/getRouteNodes.ts +++ b/packages/router-generator/src/filesystem/virtual/getRouteNodes.ts @@ -1,10 +1,6 @@ import path, { join, resolve } from 'node:path' import { - cleanPath, - createLiteralRoutePathSegmentMetadata, - createRoutePathSegmentMetadata, - determineInitialRoutePathFromExplicitPath, - joinRoutePathSegmentMetadata, + determineInitialRoutePath, removeExt, removeLeadingSlash, removeTrailingSlash, @@ -152,14 +148,6 @@ export async function getRouteNodesRecursive( const children = await Promise.all( nodes.map(async (node) => { if (node.type === 'physical') { - const { - routePath: routePathPrefix, - originalRoutePath: originalRoutePathPrefix, - } = node.pathPrefix - ? determineInitialRoutePathFromExplicitPath( - removeLeadingSlash(node.pathPrefix), - ) - : { routePath: '', originalRoutePath: '' } const { routeNodes, physicalDirectories } = await getRouteNodesPhysical( { ...tsrConfig, @@ -173,30 +161,13 @@ export async function getRouteNodesRecursive( ...physicalDirectories, ) routeNodes.forEach((subtreeNode) => { - const pathPrefix = cleanPath( - `${parent?.routePath ?? ''}${routePathPrefix}`, - ) - const originalPathPrefix = cleanPath( - `${parent?.originalRoutePath ?? parent?.routePath ?? ''}${originalRoutePathPrefix}`, - ) - const literalPathPrefixSegments = - createLiteralRoutePathSegmentMetadata(pathPrefix, parent, true) - const routePath = cleanPath(`${pathPrefix}${subtreeNode.routePath}`) subtreeNode.variableName = routePathToVariable( - `${routePathPrefix}/${removeExt(subtreeNode.filePath)}`, + `${node.pathPrefix}/${removeExt(subtreeNode.filePath)}`, ) - subtreeNode._routePathSegmentMetadata = joinRoutePathSegmentMetadata( - routePath, - pathPrefix, - literalPathPrefixSegments, - subtreeNode._routePathSegmentMetadata, - ) - subtreeNode.routePath = routePath + subtreeNode.routePath = `${parent?.routePath ?? ''}${node.pathPrefix}${subtreeNode.routePath}` // Keep originalRoutePath aligned with routePath for escape detection if (subtreeNode.originalRoutePath) { - subtreeNode.originalRoutePath = cleanPath( - `${originalPathPrefix}${subtreeNode.originalRoutePath}`, - ) + subtreeNode.originalRoutePath = `${parent?.routePath ?? ''}${node.pathPrefix}${subtreeNode.originalRoutePath}` } subtreeNode.filePath = `${node.directory}/${subtreeNode.filePath}` }) @@ -210,25 +181,17 @@ export async function getRouteNodesRecursive( return { filePath, variableName, fullPath } } const parentRoutePath = removeTrailingSlash(parent?.routePath ?? '/') - const parentOriginalRoutePath = removeTrailingSlash( - parent?.originalRoutePath ?? parent?.routePath ?? '/', - ) const virtualParentRoutePath = parent?.routePath ?? `/${rootPathId}` switch (node.type) { case 'index': { const { filePath, variableName, fullPath } = getFile(node.file) const routePath = `${parentRoutePath}/` - const originalRoutePath = `${parentOriginalRoutePath}/` return { filePath, fullPath, variableName, routePath, - originalRoutePath, - _routePathSegmentMetadata: parent?._routePathSegmentMetadata - ? [...parent._routePathSegmentMetadata] - : undefined, _fsRouteType: 'static', _virtualParentRoutePath: virtualParentRoutePath, } satisfies RouteNode @@ -242,13 +205,10 @@ export async function getRouteNodesRecursive( const { routePath: escapedSegment, originalRoutePath: originalSegment, - } = determineInitialRoutePathFromExplicitPath( - removeLeadingSlash(lastSegment), - ) + } = determineInitialRoutePath(removeLeadingSlash(lastSegment)) const routePath = `${parentRoutePath}${escapedSegment}` - const originalRoutePath = `${parentOriginalRoutePath}${originalSegment}` - const routePathSegmentMetadata = - createLiteralRoutePathSegmentMetadata(routePath, parent, true) + // Store the original path with brackets for escape detection + const originalRoutePath = `${parentRoutePath}${originalSegment}` if (node.file) { const { filePath, variableName, fullPath } = getFile(node.file) @@ -258,7 +218,6 @@ export async function getRouteNodesRecursive( variableName, routePath, originalRoutePath, - _routePathSegmentMetadata: routePathSegmentMetadata, _fsRouteType: 'static', _virtualParentRoutePath: virtualParentRoutePath, } @@ -269,7 +228,6 @@ export async function getRouteNodesRecursive( variableName: routePathToVariable(routePath), routePath, originalRoutePath, - _routePathSegmentMetadata: routePathSegmentMetadata, isVirtual: true, _fsRouteType: 'static', _virtualParentRoutePath: virtualParentRoutePath, @@ -309,18 +267,10 @@ export async function getRouteNodesRecursive( const { routePath: escapedSegment, originalRoutePath: originalSegment, - } = determineInitialRoutePathFromExplicitPath( - removeLeadingSlash(lastSegment), - ) + } = determineInitialRoutePath(removeLeadingSlash(lastSegment)) const routePath = `${parentRoutePath}${escapedSegment}` // Store the original path with brackets for escape detection - const originalRoutePath = `${parentOriginalRoutePath}${originalSegment}` - const routePathSegmentMetadata = joinRoutePathSegmentMetadata( - routePath, - parentRoutePath, - parent?._routePathSegmentMetadata, - createRoutePathSegmentMetadata(escapedSegment, originalSegment), - ) + const originalRoutePath = `${parentRoutePath}${originalSegment}` const routeNode: RouteNode = { fullPath, @@ -328,7 +278,6 @@ export async function getRouteNodesRecursive( variableName, routePath, originalRoutePath, - _routePathSegmentMetadata: routePathSegmentMetadata, _fsRouteType: 'pathless_layout', _virtualParentRoutePath: virtualParentRoutePath, } diff --git a/packages/router-generator/src/filesystem/virtual/loadConfigFile.ts b/packages/router-generator/src/filesystem/virtual/loadConfigFile.ts index a4606e4e19..f49a79c492 100644 --- a/packages/router-generator/src/filesystem/virtual/loadConfigFile.ts +++ b/packages/router-generator/src/filesystem/virtual/loadConfigFile.ts @@ -1,10 +1,8 @@ -import { createJiti } from 'jiti' +import { pathToFileURL } from 'node:url' +import { tsImport } from 'tsx/esm/api' export async function loadConfigFile(filePath: string) { - const jiti = createJiti(filePath, { - interopDefault: false, - tsconfigPaths: true, - }) - const loaded = await jiti.import<any>(filePath) + const fileURL = pathToFileURL(filePath).href + const loaded = await tsImport(fileURL, './') return loaded } diff --git a/packages/router-generator/src/generator.ts b/packages/router-generator/src/generator.ts index 91f87dadda..9de0c2b023 100644 --- a/packages/router-generator/src/generator.ts +++ b/packages/router-generator/src/generator.ts @@ -17,8 +17,6 @@ import { buildRouteTreeConfig, checkFileExists, checkRouteFullPathUniqueness, - countRoutePathSegments, - countSlashSeparatedParts, createRouteNodesByFullPath, createRouteNodesById, createRouteNodesByTo, @@ -27,18 +25,20 @@ import { findParent, format, getImportForRouteNode, + getImportPath, getResolvedRouteNodeVariableName, hasParentRoute, + isRouteNodeValidForAugmentation, isSegmentPathless, mergeImportDeclarations, multiSortBy, removeExt, removeGroups, removeLastSegmentFromPath, - removeLayoutSegmentsAndUnderscoresWithEscape, + removeLayoutSegmentsWithEscape, removeTrailingSlash, + removeUnderscoresWithEscape, replaceBackslash, - sortRouteNodes, trimPathLeft, } from './utils' import { fillTemplate, getTargetTemplate } from './template' @@ -53,7 +53,6 @@ import type { HandleNodeAccumulator, ImportDeclaration, RouteNode, - RoutePathSegmentMetadata, } from './types' import type { Config } from './config' import type { Logger } from './logger' @@ -73,32 +72,6 @@ interface fs { chown: (filePath: string, uid: number, gid: number) => Promise<void> } -function getRoutePathSegmentMetadataForPath( - node: RouteNode, - routePath: string, - parentRoutePath?: string, -): Array<RoutePathSegmentMetadata | undefined> | undefined { - if (!node._routePathSegmentMetadata) return undefined - - const segments = routePath.split('/') - const result = new Array<RoutePathSegmentMetadata | undefined>( - segments.length, - ) - const parentSegmentCount = countRoutePathSegments(parentRoutePath) - let hasMetadata = false - let segmentCount = 0 - - for (let i = 0; i < segments.length; i++) { - if (!segments[i]) continue - const sourceIndex = parentSegmentCount + segmentCount + 1 - result[i] = node._routePathSegmentMetadata[sourceIndex] - hasMetadata ||= !!result[i] - segmentCount++ - } - - return hasMetadata ? result : undefined -} - const DefaultFileSystem: fs = { stat: async (filePath) => { const res = await fsp.stat(filePath, { bigint: true }) @@ -299,7 +272,7 @@ export class Generator { return new Map( [...this.routeNodeCache.entries()].map(([filePath, cacheEntry]) => [ filePath, - { routeId: cacheEntry.routeId }, + { routePath: cacheEntry.routeId }, ]), ) } @@ -421,10 +394,7 @@ export class Generator { const preRouteNodes = multiSortBy(beforeRouteNodes, [ (d) => (d.routePath === '/' ? -1 : 1), - (d) => - d.routePath === undefined - ? undefined - : countSlashSeparatedParts(d.routePath), + (d) => d.routePath?.split('/').length, (d) => (d.filePath.match(this.indexTokenFilenameRegex) ? 1 : -1), (d) => (d.filePath.match(Generator.componentPieceRegex) ? 1 : -1), (d) => (d.filePath.match(this.routeTokenFilenameRegex) ? -1 : 1), @@ -617,10 +587,16 @@ export class Generator { ? this.indexTokenSegmentRegex : createTokenRegex(config.indexToken, { type: 'segment' }) - const sortedRouteNodes = sortRouteNodes( - acc.routeNodes, - indexTokenSegmentRegex, - ) + const sortedRouteNodes = multiSortBy(acc.routeNodes, [ + (d) => (d.routePath?.includes(`/${rootPathId}`) ? -1 : 1), + (d) => d.routePath?.split('/').length, + (d) => { + const segments = d.routePath?.split('/').filter(Boolean) ?? [] + const last = segments[segments.length - 1] ?? '' + return indexTokenSegmentRegex.test(last) ? -1 : 1 + }, + (d) => d, + ]) const routeImports: Array<ImportDeclaration> = [] const virtualRouteNodes: Array<string> = [] @@ -682,6 +658,38 @@ export class Generator { } imports.push(runtimeImport) } + if (config.verboseFileRoutes === false) { + const typeImport: ImportDeclaration = { + specifiers: [], + source: this.targetTemplate.fullPkg, + importKind: 'type', + } + let needsCreateFileRoute = false + let needsCreateLazyFileRoute = false + for (const node of sortedRouteNodes) { + if (isRouteNodeValidForAugmentation(node)) { + if (node._fsRouteType !== 'lazy') { + needsCreateFileRoute = true + } + if (acc.routePiecesByPath[node.routePath!]?.lazy) { + needsCreateLazyFileRoute = true + } + } + if (needsCreateFileRoute && needsCreateLazyFileRoute) break + } + if (needsCreateFileRoute) { + typeImport.specifiers.push({ imported: 'CreateFileRoute' }) + } + if (needsCreateLazyFileRoute) { + typeImport.specifiers.push({ imported: 'CreateLazyFileRoute' }) + } + + if (typeImport.specifiers.length > 0) { + typeImport.specifiers.push({ imported: 'FileRoutesByPath' }) + imports.push(typeImport) + } + } + const routeTreeConfig = buildRouteTreeConfig( acc.routeTree, config.disableTypes, @@ -955,6 +963,36 @@ ${acc.routeTree.map((child) => `${child.variableName}Route: typeof ${getResolved const importStatements = mergedImports.map(buildImportString) + let moduleAugmentation = '' + if (config.verboseFileRoutes === false && !config.disableTypes) { + moduleAugmentation = opts.routeFileResult + .map((node) => { + const getModuleDeclaration = (routeNode?: RouteNode) => { + if (!isRouteNodeValidForAugmentation(routeNode)) { + return '' + } + let moduleAugmentation = '' + if (routeNode._fsRouteType === 'lazy') { + moduleAugmentation = `const createLazyFileRoute: CreateLazyFileRoute<FileRoutesByPath['${routeNode.routePath}']['preLoaderRoute']>` + } else { + moduleAugmentation = `const createFileRoute: CreateFileRoute<'${routeNode.routePath}', + FileRoutesByPath['${routeNode.routePath}']['parentRoute'], + FileRoutesByPath['${routeNode.routePath}']['id'], + FileRoutesByPath['${routeNode.routePath}']['path'], + FileRoutesByPath['${routeNode.routePath}']['fullPath'] + > + ` + } + + return `declare module './${getImportPath(routeNode, config, this.generatedRouteTreePath)}' { + ${moduleAugmentation} + }` + } + return getModuleDeclaration(node) + }) + .join('\n') + } + const rootRouteImport = getImportForRouteNode( rootRouteNode, config, @@ -982,6 +1020,7 @@ ${acc.routeTree.map((child) => `${child.variableName}Route: typeof ${getResolved createUpdateRoutes.join('\n'), fileRoutesByFullPath, fileRoutesByPathInterface, + moduleAugmentation, routeTreeConfig.join('\n'), routeTree, ...footer, @@ -1095,11 +1134,11 @@ ${acc.routeTree.map((child) => `${child.variableName}Route: typeof ${getResolved // transform the file const transformResult = await transform({ source: updatedCacheEntry.fileContent, - filename: node.fullPath, ctx: { target: this.config.target, routeId: escapedRoutePath, lazy: node._fsRouteType === 'lazy', + verboseFileRoutes: !(this.config.verboseFileRoutes === false), }, node, }) @@ -1146,7 +1185,6 @@ ${acc.routeTree.map((child) => `${child.variableName}Route: typeof ${getResolved strategy: { type: 'mtime', expectedMtimeMs: updatedCacheEntry.mtimeMs, - expectedContent: existingRouteFile.fileContent, }, }) updatedCacheEntry.mtimeMs = stats.mtimeMs @@ -1207,9 +1245,6 @@ ${acc.routeTree.map((child) => `${child.variableName}Route: typeof ${getResolved | { type: 'mtime' expectedMtimeMs: bigint - // An in-place save can truncate and rewrite a file within one mtime - // tick, so user-authored files also compare the content. - expectedContent?: string } | { type: 'new-file' @@ -1219,8 +1254,13 @@ ${acc.routeTree.map((child) => `${child.variableName}Route: typeof ${getResolved await this.fs.writeFile(tmpPath, opts.newContent) if (opts.strategy.type === 'mtime') { - const { expectedMtimeMs, expectedContent } = opts.strategy const beforeStat = await this.fs.stat(opts.filePath) + if (beforeStat.mtimeMs !== opts.strategy.expectedMtimeMs) { + throw rerun({ + msg: `File ${opts.filePath} was modified by another process during processing.`, + event: { type: 'update', path: opts.filePath }, + }) + } const newFileState = await this.fs.stat(tmpPath) if (newFileState.mode !== beforeStat.mode) { await this.fs.chmod(tmpPath, beforeStat.mode) @@ -1246,25 +1286,6 @@ ${acc.routeTree.map((child) => `${child.variableName}Route: typeof ${getResolved } } } - // Check right before the rename so that changes made while the - // temporary file was prepared are not overwritten. - let changed: boolean - if (expectedContent === undefined) { - const current = await this.fs.stat(opts.filePath) - changed = current.mtimeMs !== expectedMtimeMs - } else { - const current = await this.fs.readFile(opts.filePath) - changed = - current === 'file-not-existing' || - current.stat.mtimeMs !== expectedMtimeMs || - current.fileContent !== expectedContent - } - if (changed) { - throw rerun({ - msg: `File ${opts.filePath} was modified by another process during processing.`, - event: { type: 'update', path: opts.filePath }, - }) - } } else { if (await checkFileExists(opts.filePath)) { throw rerun({ @@ -1388,7 +1409,6 @@ ${acc.routeTree.map((child) => `${child.variableName}Route: typeof ${getResolved strategy: { type: 'mtime', expectedMtimeMs: rootNodeFile.stat.mtimeMs, - expectedContent: rootNodeFile.fileContent, }, }) updatedCacheEntry.fileContent = rootRouteContent @@ -1475,39 +1495,29 @@ ${acc.routeTree.map((child) => `${child.variableName}Route: typeof ${getResolved node.path = determineNodePath(node) const trimmedPath = trimPathLeft(node.path ?? '') - const originalPath = - node.originalRoutePath && node.parent?.originalRoutePath - ? node.originalRoutePath.replace(node.parent.originalRoutePath, '') || - '/' - : node.originalRoutePath - const routePathSegmentMetadata = getRoutePathSegmentMetadataForPath( - node, - node.path ?? '/', - node.parent?.routePath, + const trimmedOriginalPath = trimPathLeft( + node.originalRoutePath?.replace( + node.parent?.originalRoutePath ?? '', + '', + ) ?? '', ) - const trimmedOriginalPath = trimPathLeft(originalPath ?? '') const split = trimmedPath.split('/') - const pathSplit = (node.path ?? '').split('/') const originalSplit = trimmedOriginalPath.split('/') const lastRouteSegment = split[split.length - 1] ?? trimmedPath const lastOriginalSegment = originalSplit[originalSplit.length - 1] ?? trimmedOriginalPath - const lastRouteSegmentMetadata = - routePathSegmentMetadata?.[pathSplit.length - 1] // A segment is non-path if it starts with underscore AND the underscore is not escaped node.isNonPath = - (!lastRouteSegmentMetadata?.literalLeadingUnderscore && - isSegmentPathless(lastRouteSegment, lastOriginalSegment)) || + isSegmentPathless(lastRouteSegment, lastOriginalSegment) || split.every((part) => this.routeGroupPatternRegex.test(part)) - // Use a single pass so layout removal does not desync escaped underscore checks. + // Use escape-aware functions to compute cleanedPath node.cleanedPath = removeGroups( - removeLayoutSegmentsAndUnderscoresWithEscape( - node.path, - originalPath, - routePathSegmentMetadata, + removeUnderscoresWithEscape( + removeLayoutSegmentsWithEscape(node.path, node.originalRoutePath), + node.originalRoutePath, ), ) @@ -1585,17 +1595,13 @@ ${acc.routeTree.map((child) => `${child.variableName}Route: typeof ${getResolved candidate.originalRoutePath ?? '', '', ) || '/' - const routePathSegmentMetadataRelativeToParent = - getRoutePathSegmentMetadataForPath( - node, - pathRelativeToParent, - candidate.routePath, - ) node.cleanedPath = removeGroups( - removeLayoutSegmentsAndUnderscoresWithEscape( - pathRelativeToParent, + removeUnderscoresWithEscape( + removeLayoutSegmentsWithEscape( + pathRelativeToParent, + originalPathRelativeToParent, + ), originalPathRelativeToParent, - routePathSegmentMetadataRelativeToParent, ), ) break diff --git a/packages/router-generator/src/index.ts b/packages/router-generator/src/index.ts index 9a4f8a17ff..de3df56d77 100644 --- a/packages/router-generator/src/index.ts +++ b/packages/router-generator/src/index.ts @@ -45,4 +45,10 @@ export { getRouteNodes as virtualGetRouteNodes } from './filesystem/virtual/getR export { rootPathId } from './filesystem/physical/rootPathId' -export type { TransformContext, TransformOptions } from './transform/types' +export { ensureStringArgument } from './transform/utils' + +export type { + TransformImportsConfig, + TransformContext, + TransformOptions, +} from './transform/types' diff --git a/packages/router-generator/src/template.ts b/packages/router-generator/src/template.ts index 11ca968933..69031f689c 100644 --- a/packages/router-generator/src/template.ts +++ b/packages/router-generator/src/template.ts @@ -44,10 +44,6 @@ export type TargetTemplate = { } } -function serializeRoutePath(routePath: string) { - return JSON.stringify(routePath) -} - export function getTargetTemplate(config: Config): TargetTemplate { const target = config.target switch (target) { @@ -81,9 +77,13 @@ export function getTargetTemplate(config: Config): TargetTemplate { ].join(''), imports: { tsrImports: () => - "import { createFileRoute } from '@tanstack/react-router';", + config.verboseFileRoutes === false + ? '' + : "import { createFileRoute } from '@tanstack/react-router';", tsrExportStart: (routePath) => - `export const Route = createFileRoute(${serializeRoutePath(routePath)})(`, + config.verboseFileRoutes === false + ? 'export const Route = createFileRoute(' + : `export const Route = createFileRoute('${routePath}')(`, tsrExportEnd: () => ');', }, }, @@ -97,9 +97,13 @@ export function getTargetTemplate(config: Config): TargetTemplate { ].join(''), imports: { tsrImports: () => - "import { createLazyFileRoute } from '@tanstack/react-router';", + config.verboseFileRoutes === false + ? '' + : "import { createLazyFileRoute } from '@tanstack/react-router';", tsrExportStart: (routePath) => - `export const Route = createLazyFileRoute(${serializeRoutePath(routePath)})(`, + config.verboseFileRoutes === false + ? 'export const Route = createLazyFileRoute(' + : `export const Route = createLazyFileRoute('${routePath}')(`, tsrExportEnd: () => ');', }, }, @@ -134,9 +138,13 @@ export function getTargetTemplate(config: Config): TargetTemplate { ].join(''), imports: { tsrImports: () => - "import { createFileRoute } from '@tanstack/solid-router';", + config.verboseFileRoutes === false + ? '' + : "import { createFileRoute } from '@tanstack/solid-router';", tsrExportStart: (routePath) => - `export const Route = createFileRoute(${serializeRoutePath(routePath)})(`, + config.verboseFileRoutes === false + ? 'export const Route = createFileRoute(' + : `export const Route = createFileRoute('${routePath}')(`, tsrExportEnd: () => ');', }, }, @@ -150,10 +158,14 @@ export function getTargetTemplate(config: Config): TargetTemplate { ].join(''), imports: { tsrImports: () => - "import { createLazyFileRoute } from '@tanstack/solid-router';", + config.verboseFileRoutes === false + ? '' + : "import { createLazyFileRoute } from '@tanstack/solid-router';", tsrExportStart: (routePath) => - `export const Route = createLazyFileRoute(${serializeRoutePath(routePath)})(`, + config.verboseFileRoutes === false + ? 'export const Route = createLazyFileRoute(' + : `export const Route = createLazyFileRoute('${routePath}')(`, tsrExportEnd: () => ');', }, @@ -190,9 +202,13 @@ export function getTargetTemplate(config: Config): TargetTemplate { ].join(''), imports: { tsrImports: () => - "import { createFileRoute } from '@tanstack/vue-router';", + config.verboseFileRoutes === false + ? '' + : "import { createFileRoute } from '@tanstack/vue-router';", tsrExportStart: (routePath) => - `export const Route = createFileRoute(${serializeRoutePath(routePath)})(`, + config.verboseFileRoutes === false + ? 'export const Route = createFileRoute(' + : `export const Route = createFileRoute('${routePath}')(`, tsrExportEnd: () => ');', }, }, @@ -207,10 +223,14 @@ export function getTargetTemplate(config: Config): TargetTemplate { ].join(''), imports: { tsrImports: () => - "import { createLazyFileRoute } from '@tanstack/vue-router';", + config.verboseFileRoutes === false + ? '' + : "import { createLazyFileRoute } from '@tanstack/vue-router';", tsrExportStart: (routePath) => - `export const Route = createLazyFileRoute(${serializeRoutePath(routePath)})(`, + config.verboseFileRoutes === false + ? 'export const Route = createLazyFileRoute(' + : `export const Route = createLazyFileRoute('${routePath}')(`, tsrExportEnd: () => ');', }, diff --git a/packages/router-generator/src/transform/transform.ts b/packages/router-generator/src/transform/transform.ts index 9fcad87948..7b3fddb9f2 100644 --- a/packages/router-generator/src/transform/transform.ts +++ b/packages/router-generator/src/transform/transform.ts @@ -1,717 +1,529 @@ -import MagicString from 'magic-string' -import * as t from '@babel/types' import { parseAst } from '@tanstack/router-utils' +import { parse, print, types, visit } from 'recast' +import { SourceMapConsumer } from 'source-map' +import { mergeImportDeclarations } from '../utils' +import { ensureStringArgument } from './utils' +import type { ImportDeclaration } from '../types' +import type { RawSourceMap } from 'source-map' import type { TransformOptions, TransformResult } from './types' -const routeConstructors = ['createFileRoute', 'createLazyFileRoute'] as const +const b = types.builders -type RouteConstructorName = (typeof routeConstructors)[number] -type SupportedRouteId = t.StringLiteral | t.TemplateLiteral -type NamedImport = { - imported: string - local: string - importKind?: 'type' | 'typeof' | 'value' -} - -type ParsedImportDeclaration = { - declaration: t.ImportDeclaration - defaultImport?: string - namespace?: string - named: Array<NamedImport> - moduleName: string - quote: '"' | "'" - semicolon: boolean -} - -type RouteImportAnalysis = - | { kind: 'ok' } - | { - kind: 'rename' - imported: t.Identifier - local: t.Identifier - next: RouteConstructorName - } - | { kind: 'normalize' } - -type RouteCall = { - callee: t.Identifier & { name: RouteConstructorName } - routeIdArg: SupportedRouteId - optionsArg: t.CallExpression['arguments'][number] | undefined -} - -type RouteCallAnalysis = { - calls: Array<RouteCall> - hasUnsupportedRouteId: boolean - hasMalformedRouteCall: boolean -} - -export function transform({ +export async function transform({ ctx, source, - filename, node, -}: TransformOptions): TransformResult { - let ast: ReturnType<typeof parseAst> - +}: TransformOptions): Promise<TransformResult> { + let appliedChanges = false as boolean + let ast: types.namedTypes.File try { - ast = parseAst({ code: source, filename }) - } catch (error) { - return { - result: 'error', - error, - } - } - - const exportedRouteNames = getExportedRouteNames(ast.program.body) - - if (exportedRouteNames.size === 0) { - return { result: 'no-route-export' } - } - - const { - calls: routeCalls, - hasUnsupportedRouteId, - hasMalformedRouteCall, - } = findExportedRouteCalls(ast.program.body, exportedRouteNames) - - if (routeCalls.length === 0 && hasMalformedRouteCall) { - return { - result: 'error', - error: new Error( - `expected Route export in ${ctx.routeId} to use createFileRoute('/path')({...}) or createLazyFileRoute('/path')({...})`, - ), - } - } - - if (routeCalls.length === 0 && hasUnsupportedRouteId) { - return { - result: 'error', - error: new Error( - `expected route id to be a string literal or plain template literal in ${ctx.routeId}`, - ), - } - } - - if (routeCalls.length === 0) { - return { result: 'not-modified' } - } - - if (routeCalls.length > 1) { - return { - result: 'error', - error: new Error( - `expected exactly one createFileRoute/createLazyFileRoute call in ${ctx.routeId}`, - ), - } - } - - const routeCall = routeCalls[0]! - const routeIdQuote = getRouteIdQuote(source, routeCall.routeIdArg) - - const createFileRouteProps = getCreateFileRouteProps(routeCall.optionsArg) - if (createFileRouteProps) { - node.createFileRouteProps = createFileRouteProps - } - - const expectedCallee = getExpectedRouteConstructor(ctx.lazy) - const expectedRouteId = `${routeIdQuote}${ctx.routeId}${routeIdQuote}` - const currentRouteId = source.slice( - routeCall.routeIdArg.start!, - routeCall.routeIdArg.end!, - ) - const targetModule = `@tanstack/${ctx.target}-router` - const imports = parseTargetImports(ast.program.body, source, targetModule) - - const s = new MagicString(source) - let modified = false - - if (routeCall.callee.name !== expectedCallee) { - s.update(routeCall.callee.start!, routeCall.callee.end!, expectedCallee) - modified = true - } - - if (currentRouteId !== expectedRouteId) { - s.update( - routeCall.routeIdArg.start!, - routeCall.routeIdArg.end!, - expectedRouteId, - ) - modified = true - } - - if ( - updateRouteImports({ - imports, - source, - s, - targetModule, - required: expectedCallee, - lineEnding: getLineEnding(source), + ast = parse(source, { + sourceFileName: 'output.ts', + parser: { + parse(code: string) { + return parseAst({ + code, + // we need to instruct babel to produce tokens, + // otherwise recast will try to generate the tokens via its own parser and will fail + tokens: true, + }) + }, + }, }) - ) { - modified = true + } catch (e) { + console.error('Error parsing code', ctx.routeId, source, e) + return { + result: 'error', + error: e, + } } - if (!modified) { - return { result: 'not-modified' } + const preferredQuote = detectPreferredQuoteStyle(ast) + + let routeExportHandled = false as boolean + function onExportFound(decl: types.namedTypes.VariableDeclarator) { + if (decl.init?.type === 'CallExpression') { + const callExpression = decl.init + const firstArgument = callExpression.arguments[0] + if (firstArgument) { + if (firstArgument.type === 'ObjectExpression') { + const staticProperties = firstArgument.properties.flatMap((p) => { + if (p.type === 'ObjectProperty' && p.key.type === 'Identifier') { + return p.key.name + } + return [] + }) + node.createFileRouteProps = new Set(staticProperties) + } + } + let identifier: types.namedTypes.Identifier | undefined + // `const Route = createFileRoute({ ... })` + if (callExpression.callee.type === 'Identifier') { + identifier = callExpression.callee + if (ctx.verboseFileRoutes) { + // we need to add the string literal via another CallExpression + callExpression.callee = b.callExpression(identifier, [ + b.stringLiteral(ctx.routeId), + ]) + appliedChanges = true + } + } + // `const Route = createFileRoute('/path')({ ... })` + else if ( + callExpression.callee.type === 'CallExpression' && + callExpression.callee.callee.type === 'Identifier' + ) { + identifier = callExpression.callee.callee + if (!ctx.verboseFileRoutes) { + // we need to remove the route id + callExpression.callee = identifier + appliedChanges = true + } else { + // check if the route id is correct + appliedChanges = ensureStringArgument( + callExpression.callee, + ctx.routeId, + ctx.preferredQuote, + ) + } + } + if (identifier === undefined) { + throw new Error( + `expected identifier to be present in ${ctx.routeId} for export "Route"`, + ) + } + if (identifier.name === 'createFileRoute' && ctx.lazy) { + identifier.name = 'createLazyFileRoute' + appliedChanges = true + } else if (identifier.name === 'createLazyFileRoute' && !ctx.lazy) { + identifier.name = 'createFileRoute' + appliedChanges = true + } + } else { + throw new Error( + `expected "Route" export to be initialized by a CallExpression`, + ) + } + routeExportHandled = true } + const program: types.namedTypes.Program = ast.program + // first pass: find Route export + for (const n of program.body) { + if (n.type === 'ExportNamedDeclaration') { + // direct export of a variable declaration, e.g. `export const Route = createFileRoute('/path')` + if (n.declaration?.type === 'VariableDeclaration') { + const decl = n.declaration.declarations[0] + if ( + decl && + decl.type === 'VariableDeclarator' && + decl.id.type === 'Identifier' + ) { + if (decl.id.name === 'Route') { + onExportFound(decl) + } + } + } + // this is an export without a declaration, e.g. `export { Route }` + else if (n.declaration === null && n.specifiers) { + for (const spec of n.specifiers) { + if (typeof spec.exported.name === 'string') { + if (spec.exported.name === 'Route') { + const variableName = spec.local?.name || spec.exported.name + // find the matching variable declaration by iterating over the top-level declarations + for (const decl of program.body) { + if ( + decl.type === 'VariableDeclaration' && + decl.declarations[0] + ) { + const variable = decl.declarations[0] + if ( + variable.type === 'VariableDeclarator' && + variable.id.type === 'Identifier' && + variable.id.name === variableName + ) { + onExportFound(variable) + break + } + } + } + } + } + } + } + } + if (routeExportHandled) { + break + } + } + + if (!routeExportHandled) { + return { + result: 'no-route-export', + } + } + + const imports: { + required: Array<ImportDeclaration> + banned: Array<ImportDeclaration> + } = { + required: [], + banned: [], + } + + const targetModule = `@tanstack/${ctx.target}-router` + if (ctx.verboseFileRoutes === false) { + imports.banned = [ + { + source: targetModule, + specifiers: [ + { imported: 'createLazyFileRoute' }, + { imported: 'createFileRoute' }, + ], + }, + ] + } else { + if (ctx.lazy) { + imports.required = [ + { + source: targetModule, + specifiers: [{ imported: 'createLazyFileRoute' }], + }, + ] + imports.banned = [ + { + source: targetModule, + specifiers: [{ imported: 'createFileRoute' }], + }, + ] + } else { + imports.required = [ + { + source: targetModule, + specifiers: [{ imported: 'createFileRoute' }], + }, + ] + imports.banned = [ + { + source: targetModule, + specifiers: [{ imported: 'createLazyFileRoute' }], + }, + ] + } + } + + imports.required = mergeImportDeclarations(imports.required) + imports.banned = mergeImportDeclarations(imports.banned) + + const importStatementCandidates: Array<types.namedTypes.ImportDeclaration> = + [] + const importDeclarationsToRemove: Array<types.namedTypes.ImportDeclaration> = + [] + + // second pass: apply import rules, but only if a matching export for the plugin was found + for (const n of program.body) { + const findImport = + (opts: { source: string; importKind?: 'type' | 'value' | 'typeof' }) => + (i: ImportDeclaration) => { + if (i.source === opts.source) { + const importKind = i.importKind || 'value' + const expectedImportKind = opts.importKind || 'value' + return expectedImportKind === importKind + } + return false + } + if (n.type === 'ImportDeclaration' && typeof n.source.value === 'string') { + const filterImport = findImport({ + source: n.source.value, + importKind: n.importKind, + }) + let requiredImports = imports.required.filter(filterImport)[0] + + const bannedImports = imports.banned.filter(filterImport)[0] + if (!requiredImports && !bannedImports) { + continue + } + const importSpecifiersToRemove: types.namedTypes.ImportDeclaration['specifiers'] = + [] + if (n.specifiers) { + for (const spec of n.specifiers) { + if (!requiredImports && !bannedImports) { + break + } + if ( + spec.type === 'ImportSpecifier' && + typeof spec.imported.name === 'string' + ) { + if (requiredImports) { + const requiredImportIndex = requiredImports.specifiers.findIndex( + (imp) => imp.imported === spec.imported.name, + ) + if (requiredImportIndex !== -1) { + // import is already present, remove it from requiredImports + requiredImports.specifiers.splice(requiredImportIndex, 1) + if (requiredImports.specifiers.length === 0) { + imports.required = imports.required.splice( + imports.required.indexOf(requiredImports), + 1, + ) + requiredImports = undefined + } + } else { + // add the import statement to the candidates + importStatementCandidates.push(n) + } + } + if (bannedImports) { + const bannedImportIndex = bannedImports.specifiers.findIndex( + (imp) => imp.imported === spec.imported.name, + ) + if (bannedImportIndex !== -1) { + importSpecifiersToRemove.push(spec) + } + } + } + } + if (importSpecifiersToRemove.length > 0) { + appliedChanges = true + n.specifiers = n.specifiers.filter( + (spec) => !importSpecifiersToRemove.includes(spec), + ) + + // mark the import statement as to be deleted if it is now empty + if (n.specifiers.length === 0) { + importDeclarationsToRemove.push(n) + } + } + } + } + } + imports.required.forEach((requiredImport) => { + if (requiredImport.specifiers.length > 0) { + appliedChanges = true + if (importStatementCandidates.length > 0) { + // find the first import statement that matches both the module and the import kind + const importStatement = importStatementCandidates.find( + (importStatement) => { + if (importStatement.source.value === requiredImport.source) { + const importKind = importStatement.importKind || 'value' + const requiredImportKind = requiredImport.importKind || 'value' + return importKind === requiredImportKind + } + return false + }, + ) + if (importStatement) { + if (importStatement.specifiers === undefined) { + importStatement.specifiers = [] + } + const importSpecifiersToAdd = requiredImport.specifiers.map((spec) => + b.importSpecifier( + b.identifier(spec.imported), + b.identifier(spec.imported), + ), + ) + importStatement.specifiers = [ + ...importStatement.specifiers, + ...importSpecifiersToAdd, + ] + return + } + } + const importStatement = b.importDeclaration( + requiredImport.specifiers.map((spec) => + b.importSpecifier( + b.identifier(spec.imported), + spec.local ? b.identifier(spec.local) : null, + ), + ), + b.stringLiteral(requiredImport.source), + ) + program.body.unshift(importStatement) + } + }) + if (importDeclarationsToRemove.length > 0) { + appliedChanges = true + for (const importDeclaration of importDeclarationsToRemove) { + // check if the import declaration is still empty + if (importDeclaration.specifiers?.length === 0) { + const index = program.body.indexOf(importDeclaration) + if (index !== -1) { + program.body.splice(index, 1) + } + } + } + } + + if (!appliedChanges) { + return { + result: 'not-modified', + } + } + + const printResult = print(ast, { + reuseWhitespace: true, + sourceMapName: 'output.map', + }) + let transformedCode = printResult.code + if (printResult.map) { + const fixedOutput = await fixTransformedOutputText({ + originalCode: source, + transformedCode, + sourceMap: printResult.map as RawSourceMap, + preferredQuote, + }) + transformedCode = fixedOutput + } return { result: 'modified', - output: s.toString(), + output: transformedCode, } } -function getExportedRouteNames(body: Array<t.Statement>) { - const exportedRouteNames = new Set<string>() - - for (const statement of body) { - if (!t.isExportNamedDeclaration(statement) || statement.source) { - continue - } - - if (t.isVariableDeclaration(statement.declaration)) { - for (const declarator of statement.declaration.declarations) { - if (t.isIdentifier(declarator.id) && declarator.id.name === 'Route') { - exportedRouteNames.add('Route') - } - } - } - - for (const specifier of statement.specifiers) { - if ( - !t.isExportSpecifier(specifier) || - getExportedName(specifier.exported) !== 'Route' - ) { - continue - } - - const localName = getLocalBindingName(specifier.local) - if (localName) { - exportedRouteNames.add(localName) - } - } - } - - return exportedRouteNames -} - -function findExportedRouteCalls( - body: Array<t.Statement>, - exportedRouteNames: Set<string>, -): RouteCallAnalysis { - const calls: Array<RouteCall> = [] - let hasUnsupportedRouteId = false - let hasMalformedRouteCall = false - - for (const statement of body) { - const declaration = getVariableDeclaration(statement) - if (!declaration) { - continue - } - - for (const declarator of declaration.declarations) { - if ( - !t.isIdentifier(declarator.id) || - !exportedRouteNames.has(declarator.id.name) - ) { - continue - } - - const init = getRouteConstructorInit(declarator.init) - if (!init) { - if (isDirectRouteConstructorCall(declarator.init)) { - hasMalformedRouteCall = true - } - continue - } - - const routeIdArg = init.innerCall.arguments[0] - if (isSupportedRouteId(routeIdArg)) { - calls.push({ - callee: init.callee, - routeIdArg, - optionsArg: init.outerCall.arguments[0], - }) - } else { - hasUnsupportedRouteId = true - } - } - } - - return { calls, hasUnsupportedRouteId, hasMalformedRouteCall } -} - -function getVariableDeclaration(statement: t.Statement) { - const declaration = t.isExportNamedDeclaration(statement) - ? statement.declaration - : statement - - return t.isVariableDeclaration(declaration) ? declaration : null -} - -function getExportedName(node: t.Identifier | t.StringLiteral) { - return t.isIdentifier(node) ? node.name : node.value -} - -function getLocalBindingName(node: t.Identifier | t.StringLiteral) { - return t.isIdentifier(node) ? node.name : null -} - -function getRouteConstructorInit(expression: t.Expression | null | undefined) { - if (!expression || !t.isCallExpression(expression)) { - return null - } - - if (!t.isCallExpression(expression.callee)) { - return null - } - - const innerCall = expression.callee - - if ( - !t.isIdentifier(innerCall.callee) || - !isRouteConstructor(innerCall.callee) - ) { - return null - } - - return { - callee: innerCall.callee, - outerCall: expression, - innerCall, - } -} - -function isDirectRouteConstructorCall( - expression: t.Expression | null | undefined, -) { - return ( - !!expression && - t.isCallExpression(expression) && - t.isIdentifier(expression.callee) && - isRouteConstructor(expression.callee) - ) -} - -function isRouteConstructor(callee: t.Identifier): callee is t.Identifier & { - name: RouteConstructorName -} { - return routeConstructors.includes(callee.name as RouteConstructorName) -} - -function isSupportedRouteId( - arg: t.CallExpression['arguments'][number] | undefined, -): arg is SupportedRouteId { - return ( - !!arg && - (t.isStringLiteral(arg) || - (t.isTemplateLiteral(arg) && arg.expressions.length === 0)) - ) -} - -function getRouteIdQuote( - source: string, - arg: SupportedRouteId, -): '"' | "'" | '`' { - const raw = source.slice(arg.start!, arg.end!) - - if (raw.startsWith("'")) return "'" - if (raw.startsWith('"')) return '"' - return '`' -} - -function getCreateFileRouteProps( - arg: t.CallExpression['arguments'][number] | undefined, -) { - if (!arg || !t.isObjectExpression(arg)) { - return undefined - } - - const props = new Set<string>() - - for (const property of arg.properties) { - if (!t.isObjectProperty(property) || property.computed) { - continue - } - - if (t.isIdentifier(property.key)) { - props.add(property.key.name) - continue - } - - if (t.isStringLiteral(property.key)) { - props.add(property.key.value) - } - } - - return props -} - -function parseTargetImports( - body: Array<t.Statement>, - source: string, - targetModule: string, -) { - const imports: Array<ParsedImportDeclaration> = [] - - for (const statement of body) { - if ( - !t.isImportDeclaration(statement) || - statement.importKind === 'type' || - statement.source.value !== targetModule - ) { - continue - } - - const rawSource = source.slice( - statement.source.start!, - statement.source.end!, - ) - const importStatement = source.slice(statement.start!, statement.end!) - - imports.push({ - declaration: statement, - defaultImport: statement.specifiers.find((specifier) => - t.isImportDefaultSpecifier(specifier), - )?.local.name, - namespace: statement.specifiers.find((specifier) => - t.isImportNamespaceSpecifier(specifier), - )?.local.name, - named: statement.specifiers - .filter((specifier): specifier is t.ImportSpecifier => - t.isImportSpecifier(specifier), - ) - .map((specifier) => ({ - imported: t.isIdentifier(specifier.imported) - ? specifier.imported.name - : specifier.imported.value, - local: specifier.local.name, - importKind: specifier.importKind ?? undefined, - })), - moduleName: statement.source.value, - quote: rawSource[0] as '"' | "'", - semicolon: importStatement.trimEnd().endsWith(';'), - }) - } - - return imports -} - -function updateRouteImports({ - imports, - source, - s, - targetModule, - required, - lineEnding, +async function fixTransformedOutputText({ + originalCode, + transformedCode, + sourceMap, + preferredQuote, }: { - imports: Array<ParsedImportDeclaration> - source: string - s: MagicString - targetModule: string - required: RouteConstructorName - lineEnding: '\r\n' | '\n' | '\r' + originalCode: string + transformedCode: string + sourceMap: RawSourceMap + preferredQuote: '"' | "'" }) { - const analysis = analyzeRouteImports(imports, required) + const originalLines = originalCode.split('\n') + const transformedLines = transformedCode.split('\n') - if (analysis.kind === 'ok') { - return false - } + const defaultUsesSemicolons = detectSemicolonUsage(originalCode) - if (analysis.kind === 'rename') { - s.update(analysis.imported.start!, analysis.imported.end!, analysis.next) - s.update(analysis.local.start!, analysis.local.end!, analysis.next) - return true - } + const consumer = await new SourceMapConsumer(sourceMap) - return normalizeRouteImports({ - imports, - source, - s, - targetModule, - required, - lineEnding, + const fixedLines = transformedLines.map((line, i) => { + const transformedLineNum = i + 1 + + let origLineText: string | undefined = undefined + + for (let col = 0; col < line.length; col++) { + const mapped = consumer.originalPositionFor({ + line: transformedLineNum, + column: col, + }) + if (mapped.line != null && mapped.line > 0) { + origLineText = originalLines[mapped.line - 1] + break + } + } + + if (origLineText !== undefined) { + if (origLineText === line) { + return origLineText + } + return fixLine(line, { + originalLine: origLineText, + useOriginalSemicolon: true, + useOriginalQuotes: true, + fallbackQuote: preferredQuote, + }) + } else { + return fixLine(line, { + originalLine: null, + useOriginalSemicolon: false, + useOriginalQuotes: false, + fallbackQuote: preferredQuote, + fallbackSemicolon: defaultUsesSemicolons, + }) + } }) + + return fixedLines.join('\n') } -function analyzeRouteImports( - imports: Array<ParsedImportDeclaration>, - required: RouteConstructorName, -): RouteImportAnalysis { - const opposite = getOtherRouteConstructor(required) - let requiredCount = 0 - let oppositeCount = 0 - let renameCandidate: - | { - imported: t.Identifier - local: t.Identifier - next: RouteConstructorName - } - | undefined - - for (const declaration of imports) { - for (const specifier of declaration.declaration.specifiers) { - if (!t.isImportSpecifier(specifier)) { - continue - } - - const imported = specifier.imported - if (!t.isIdentifier(imported)) { - return { kind: 'normalize' } - } - - if (!isRouteConstructorName(imported.name)) { - continue - } - - if (specifier.local.name !== imported.name) { - return { kind: 'normalize' } - } - - if (imported.name === required) { - requiredCount++ - continue - } - - if (imported.name === opposite) { - oppositeCount++ - renameCandidate = { - imported, - local: specifier.local, - next: required, - } - } - } - } - - if (requiredCount === 1 && oppositeCount === 0) { - return { kind: 'ok' } - } - - if (requiredCount === 0 && oppositeCount === 1 && renameCandidate) { - return { - kind: 'rename', - ...renameCandidate, - } - } - - return { kind: 'normalize' } -} - -function normalizeRouteImports({ - imports, - source, - s, - targetModule, - required, - lineEnding, -}: { - imports: Array<ParsedImportDeclaration> - source: string - s: MagicString - targetModule: string - required: RouteConstructorName - lineEnding: '\r\n' | '\n' | '\r' -}) { - const owner = - imports.find((declaration) => - hasNamedImport(declaration.named, required), - ) ?? imports.find((declaration) => !declaration.namespace) - - let modified = false - - for (const declaration of imports) { - const named = normalizeNamedImports({ - named: declaration.named, - required, - isOwner: declaration === owner, - }) - - if (sameNamedImports(declaration.named, named)) { - continue - } - - const replacement = renderImportDeclaration({ - ...declaration, - named, - }) - - if (replacement === null) { - s.remove( - declaration.declaration.start!, - getRemovalEnd(source, declaration.declaration.end!), - ) - modified = true - continue - } - - s.update( - declaration.declaration.start!, - declaration.declaration.end!, - replacement, - ) - modified = true - } - - if (!owner) { - const quote = imports[0]?.quote ?? "'" - const semicolon = imports[0]?.semicolon ?? false - s.prepend( - `import { ${required} } from ${quote}${targetModule}${quote}${semicolon ? ';' : ''}${lineEnding}`, - ) - modified = true - } - - return modified -} - -function normalizeNamedImports({ - named, - required, - isOwner, -}: { - named: Array<NamedImport> - required: RouteConstructorName - isOwner: boolean -}) { - const banned = getOtherRouteConstructor(required) - const nextNamed: Array<NamedImport> = [] - const seen = new Set<string>() - - for (const specifier of named) { - if (specifier.imported === banned) { - continue - } - - if ( - specifier.local === required && - (specifier.imported !== required || !isOwner) - ) { - continue - } - - const key = `${specifier.importKind ?? 'value'}:${specifier.imported}:${specifier.local}` - if (seen.has(key)) { - continue - } - - seen.add(key) - nextNamed.push(specifier) - } - - if (isOwner && !hasNamedImport(nextNamed, required)) { - nextNamed.push({ imported: required, local: required }) - } - - return nextNamed -} - -function getExpectedRouteConstructor(lazy: boolean): RouteConstructorName { - return lazy ? 'createLazyFileRoute' : 'createFileRoute' -} - -function getOtherRouteConstructor( - constructor: RouteConstructorName, -): RouteConstructorName { - return constructor === 'createFileRoute' - ? 'createLazyFileRoute' - : 'createFileRoute' -} - -function hasNamedImport( - named: Array<NamedImport>, - required: RouteConstructorName, +function fixLine( + line: string, + { + originalLine, + useOriginalSemicolon, + useOriginalQuotes, + fallbackQuote, + fallbackSemicolon = true, + }: { + originalLine: string | null + useOriginalSemicolon: boolean + useOriginalQuotes: boolean + fallbackQuote: string + fallbackSemicolon?: boolean + }, ) { - return named.some( - (specifier) => - specifier.imported === required && - specifier.local === required && - specifier.importKind !== 'type', + let result = line + + if (useOriginalQuotes && originalLine) { + result = fixQuotes(result, originalLine, fallbackQuote) + } else if (!useOriginalQuotes && fallbackQuote) { + result = fixQuotesToPreferred(result, fallbackQuote) + } + + if (useOriginalSemicolon && originalLine) { + const hadSemicolon = originalLine.trimEnd().endsWith(';') + const hasSemicolon = result.trimEnd().endsWith(';') + if (hadSemicolon && !hasSemicolon) result += ';' + if (!hadSemicolon && hasSemicolon) result = result.replace(/;\s*$/, '') + } else if (!useOriginalSemicolon) { + const hasSemicolon = result.trimEnd().endsWith(';') + if (!fallbackSemicolon && hasSemicolon) result = result.replace(/;\s*$/, '') + if (fallbackSemicolon && !hasSemicolon && result.trim()) result += ';' + } + + return result +} + +function fixQuotes(line: string, originalLine: string, fallbackQuote: string) { + let originalQuote = detectQuoteFromLine(originalLine) + if (!originalQuote) { + originalQuote = fallbackQuote + } + return fixQuotesToPreferred(line, originalQuote) +} + +function fixQuotesToPreferred(line: string, quote: string) { + // Replace existing quotes with preferred quote + return line.replace( + /(['"`])([^'"`\\]*(?:\\.[^'"`\\]*)*)\1/g, + (_, q, content) => { + const escaped = content.replaceAll(quote, `\\${quote}`) + return `${quote}${escaped}${quote}` + }, ) } -function sameNamedImports(left: Array<NamedImport>, right: Array<NamedImport>) { - return ( - left.length === right.length && - left.every( - (specifier, index) => - specifier.imported === right[index]!.imported && - specifier.local === right[index]!.local && - specifier.importKind === right[index]!.importKind, - ) - ) +function detectQuoteFromLine(line: string) { + const match = line.match(/(['"`])(?:\\.|[^\\])*?\1/) + return match ? match[1] : null } -function isRouteConstructorName(value: string): value is RouteConstructorName { - return routeConstructors.includes(value as RouteConstructorName) +function detectSemicolonUsage(code: string) { + const lines = code.split('\n').map((l) => l.trim()) + const total = lines.length + const withSemis = lines.filter((l) => l.endsWith(';')).length + return withSemis > total / 2 } -function renderImportDeclaration(importDeclaration: { - defaultImport?: string - namespace?: string - named: Array<NamedImport> - moduleName: string - quote: '"' | "'" - semicolon: boolean -}) { - const parts: Array<string> = [] +export function detectPreferredQuoteStyle(ast: types.ASTNode): "'" | '"' { + let single = 0 + let double = 0 - if (importDeclaration.defaultImport) { - parts.push(importDeclaration.defaultImport) + visit(ast, { + visitStringLiteral(path) { + if (path.parent.node.type !== 'JSXAttribute') { + const raw = path.node.extra?.raw + if (raw?.startsWith("'")) single++ + else if (raw?.startsWith('"')) double++ + } + return false + }, + }) + + if (single >= double) { + return "'" } - - if (importDeclaration.namespace) { - parts.push(`* as ${importDeclaration.namespace}`) - } - - if (importDeclaration.named.length > 0) { - parts.push( - `{ ${importDeclaration.named - .map( - (specifier) => - `${specifier.importKind === 'type' ? 'type ' : ''}${specifier.imported === specifier.local ? specifier.imported : `${specifier.imported} as ${specifier.local}`}`, - ) - .join(', ')} }`, - ) - } - - if (parts.length === 0) { - return null - } - - return `import ${parts.join(', ')} from ${importDeclaration.quote}${importDeclaration.moduleName}${importDeclaration.quote}${importDeclaration.semicolon ? ';' : ''}` -} - -function getLineEnding(source: string): '\r\n' | '\n' | '\r' { - if (source.includes('\r\n')) { - return '\r\n' - } - - if (source.includes('\n')) { - return '\n' - } - - if (source.includes('\r')) { - return '\r' - } - - return '\n' -} - -function getRemovalEnd(source: string, end: number) { - let pos = end - while (pos < source.length && (source[pos] === ' ' || source[pos] === '\t')) { - pos++ - } - - if (source[pos] === '\r' && source[pos + 1] === '\n') { - return pos + 2 - } - - if (source[pos] === '\n' || source[pos] === '\r') { - return pos + 1 - } - - return end + return '"' } diff --git a/packages/router-generator/src/transform/types.ts b/packages/router-generator/src/transform/types.ts index 4a8fecaada..f8b75f6003 100644 --- a/packages/router-generator/src/transform/types.ts +++ b/packages/router-generator/src/transform/types.ts @@ -1,9 +1,8 @@ -import type { RouteNode } from '../types' +import type { ImportDeclaration, RouteNode } from '../types' import type { Config } from '../config' export interface TransformOptions { source: string - filename?: string ctx: TransformContext node: RouteNode } @@ -24,8 +23,15 @@ export type TransformResult = error?: any } +export interface TransformImportsConfig { + banned?: Array<ImportDeclaration> + required?: Array<ImportDeclaration> +} + export interface TransformContext { target: Config['target'] routeId: string lazy: boolean + verboseFileRoutes: boolean + preferredQuote?: '"' | "'" } diff --git a/packages/router-generator/src/transform/utils.ts b/packages/router-generator/src/transform/utils.ts new file mode 100644 index 0000000000..9fa9ac8fe2 --- /dev/null +++ b/packages/router-generator/src/transform/utils.ts @@ -0,0 +1,42 @@ +import { types } from 'recast' + +const b = types.builders + +export function ensureStringArgument( + callExpression: types.namedTypes.CallExpression, + value: string, + preferredQuote?: "'" | '"', +) { + const argument = callExpression.arguments[0] + if (!argument) { + let stringLiteral: types.namedTypes.StringLiteral + if (!preferredQuote) { + stringLiteral = b.stringLiteral.from({ value }) + } else { + stringLiteral = b.stringLiteral.from({ + value, + extra: { + rawValue: value, + raw: `${preferredQuote}${value}${preferredQuote}`, + }, + }) + } + callExpression.arguments.push(stringLiteral) + return true + } else if (argument.type === 'StringLiteral') { + if (argument.value !== value) { + argument.value = value + return true + } + } else if (argument.type === 'TemplateLiteral') { + if ( + argument.quasis.length === 1 && + argument.quasis[0] && + argument.quasis[0].value.raw !== value + ) { + argument.quasis[0].value.raw = value + return true + } + } + return false +} diff --git a/packages/router-generator/src/types.ts b/packages/router-generator/src/types.ts index ec0aa226ce..2161e62c00 100644 --- a/packages/router-generator/src/types.ts +++ b/packages/router-generator/src/types.ts @@ -1,8 +1,3 @@ -export type RoutePathSegmentMetadata = { - literalLeadingUnderscore?: boolean - literalTrailingUnderscore?: boolean -} - export type RouteNode = { filePath: string fullPath: string @@ -25,8 +20,6 @@ export type RouteNode = { * (e.g., when the parent is a virtual file-less route that gets filtered out). */ _virtualParentRoutePath?: string - /** Internal routePath segment metadata for escaped or explicit literal syntax. */ - _routePathSegmentMetadata?: Array<RoutePathSegmentMetadata | undefined> } export interface GetRouteNodesResult { @@ -74,7 +67,7 @@ export type HandleNodeAccumulator = { routeNodesByPath: Map<string, RouteNode> } -export type GetRoutesByFileMapResultValue = { routeId: string } +export type GetRoutesByFileMapResultValue = { routePath: string } export type GetRoutesByFileMapResult = Map< string, GetRoutesByFileMapResultValue diff --git a/packages/router-generator/src/utils.ts b/packages/router-generator/src/utils.ts index a3bb4b746c..7dc74d7f8e 100644 --- a/packages/router-generator/src/utils.ts +++ b/packages/router-generator/src/utils.ts @@ -4,11 +4,7 @@ import path from 'node:path' import * as prettier from 'prettier' import { rootPathId } from './filesystem/physical/rootPathId' import type { Config, TokenMatcher } from './config' -import type { - ImportDeclaration, - RouteNode, - RoutePathSegmentMetadata, -} from './types' +import type { ImportDeclaration, RouteNode } from './types' /** * Prefix map for O(1) parent route lookups. @@ -17,6 +13,7 @@ import type { */ export class RoutePrefixMap { private prefixToRoute: Map<string, RouteNode> = new Map() + private layoutRoutes: Array<RouteNode> = [] constructor(routes: Array<RouteNode>) { for (const route of routes) { @@ -37,7 +34,20 @@ export class RoutePrefixMap { // Index by exact path for direct lookups this.prefixToRoute.set(route.routePath, route) + + if ( + route._fsRouteType === 'pathless_layout' || + route._fsRouteType === 'layout' || + route._fsRouteType === '__root' + ) { + this.layoutRoutes.push(route) + } } + + // Sort by path length descending for longest-match-first + this.layoutRoutes.sort( + (a, b) => (b.routePath?.length ?? 0) - (a.routePath?.length ?? 0), + ) } /** @@ -123,30 +133,6 @@ export function multiSortBy<T>( return result } -/** - * Sorts route nodes by root, path depth, index status, and finally `routePath`. - * The `routePath` comparison keeps the output consistent when the earlier - * values are the same. - */ -export function sortRouteNodes( - routeNodes: Array<RouteNode>, - indexTokenSegmentRegex: RegExp, -): Array<RouteNode> { - return multiSortBy(routeNodes, [ - (d) => (d.routePath?.includes(`/${rootPathId}`) ? -1 : 1), - (d) => - d.routePath === undefined - ? undefined - : countSlashSeparatedParts(d.routePath), - (d) => { - const segments = d.routePath?.split('/').filter(Boolean) ?? [] - const last = segments[segments.length - 1] ?? '' - return indexTokenSegmentRegex.test(last) ? -1 : 1 - }, - (d) => d.routePath, - ]) -} - export function cleanPath(path: string) { // remove double slashes return path.replace(/\/{2,}/g, '/') @@ -186,12 +172,13 @@ const DISALLOWED_ESCAPE_CHARS = new Set([ '%', ]) -function determineInitialRoutePathFromParts( - routePath: string, - parts: Array<string>, -) { +export function determineInitialRoutePath(routePath: string) { const originalRoutePath = - cleanPath(`/${cleanPath(parts.join('/')) || ''}`) || '' + cleanPath( + `/${(cleanPath(routePath) || '').split(SPLIT_REGEX).join('/')}`, + ) || '' + + const parts = routePath.split(SPLIT_REGEX) // Escape any characters that in square brackets // we keep the original path untouched @@ -230,21 +217,6 @@ function determineInitialRoutePathFromParts( } } -export function determineInitialRoutePath(routePath: string) { - return determineInitialRoutePathFromParts( - routePath, - routePath.split(SPLIT_REGEX), - ) -} - -/** - * Resolves bracket escapes in an explicit route path or ID without applying - * the dot-delimited flat-file route convention. - */ -export function determineInitialRoutePathFromExplicitPath(routePath: string) { - return determineInitialRoutePathFromParts(routePath, [routePath]) -} - /** * Checks if a segment is fully escaped (entirely wrapped in brackets with no nested brackets). * E.g., "[index]" -> true, "[_layout]" -> true, "foo[.]bar" -> false, "index" -> false @@ -286,169 +258,6 @@ export function hasEscapedTrailingUnderscore(originalSegment: string): boolean { ) } -export function countRoutePathSegments(routePath?: string): number { - const path = routePath ?? '' - let count = 0 - let inSegment = false - - for (let i = 0; i < path.length; i++) { - if (path[i] === '/') { - inSegment = false - continue - } - - if (!inSegment) { - count++ - inSegment = true - } - } - - return count -} - -export function countSlashSeparatedParts(path: string): number { - let count = 1 - - for (let i = 0; i < path.length; i++) { - if (path[i] === '/') count++ - } - - return count -} - -export function hasRoutePathSegmentMetadata( - metadata: RoutePathSegmentMetadata | undefined, -): metadata is RoutePathSegmentMetadata { - return !!( - metadata?.literalLeadingUnderscore || metadata?.literalTrailingUnderscore - ) -} - -function mergeRoutePathSegmentMetadata( - current: RoutePathSegmentMetadata | undefined, - incoming: RoutePathSegmentMetadata | undefined, -): RoutePathSegmentMetadata | undefined { - const hasCurrent = hasRoutePathSegmentMetadata(current) - const hasIncoming = hasRoutePathSegmentMetadata(incoming) - - if (!hasCurrent) return hasIncoming ? incoming : undefined - if (!hasIncoming) return current - - return { - literalLeadingUnderscore: - current.literalLeadingUnderscore || incoming.literalLeadingUnderscore, - literalTrailingUnderscore: - current.literalTrailingUnderscore || incoming.literalTrailingUnderscore, - } -} - -export function createRoutePathSegmentMetadata( - routePath: string = '/', - originalPath?: string, -): Array<RoutePathSegmentMetadata | undefined> | undefined { - if (!originalPath) return undefined - - const routeSegments = routePath.split('/') - const originalSegments = originalPath.split('/') - const metadata = new Array<RoutePathSegmentMetadata | undefined>( - routeSegments.length, - ) - let hasMetadata = false - - for (let i = 0; i < routeSegments.length; i++) { - const segment = routeSegments[i]! - const originalSegment = originalSegments[i] || '' - const literalLeadingUnderscore = - segment.startsWith('_') && hasEscapedLeadingUnderscore(originalSegment) - const literalTrailingUnderscore = - segment.endsWith('_') && hasEscapedTrailingUnderscore(originalSegment) - - if (!literalLeadingUnderscore && !literalTrailingUnderscore) continue - - hasMetadata = true - metadata[i] = { - literalLeadingUnderscore: literalLeadingUnderscore || undefined, - literalTrailingUnderscore: literalTrailingUnderscore || undefined, - } - } - - return hasMetadata ? metadata : undefined -} - -export function createLiteralRoutePathSegmentMetadata( - routePath: string, - parent?: RouteNode, - literalNewSegments = false, -): Array<RoutePathSegmentMetadata | undefined> | undefined { - const routeSegments = routePath.split('/') - const metadata = new Array<RoutePathSegmentMetadata | undefined>( - routeSegments.length, - ) - const parentDepth = countRoutePathSegments(parent?.routePath) - let hasMetadata = false - let depth = 0 - - for (let i = 0; i < routeSegments.length; i++) { - const segment = routeSegments[i] - metadata[i] = parent?._routePathSegmentMetadata?.[i] - hasMetadata ||= hasRoutePathSegmentMetadata(metadata[i]) - - if (!segment) continue - - if (literalNewSegments && depth >= parentDepth) { - const literalLeadingUnderscore = segment.startsWith('_') - const literalTrailingUnderscore = segment.endsWith('_') - - if (literalLeadingUnderscore || literalTrailingUnderscore) { - metadata[i] = mergeRoutePathSegmentMetadata(metadata[i], { - literalLeadingUnderscore: literalLeadingUnderscore || undefined, - literalTrailingUnderscore: literalTrailingUnderscore || undefined, - }) - hasMetadata = true - } - } - - depth++ - } - - return hasMetadata ? metadata : undefined -} - -export function joinRoutePathSegmentMetadata( - routePath: string, - prefixPath: string, - prefixMetadata: Array<RoutePathSegmentMetadata | undefined> | undefined, - childMetadata: Array<RoutePathSegmentMetadata | undefined> | undefined, -): Array<RoutePathSegmentMetadata | undefined> | undefined { - const metadata = new Array<RoutePathSegmentMetadata | undefined>( - countSlashSeparatedParts(routePath), - ) - let hasMetadata = false - - if (prefixMetadata) { - for (let i = 0; i < prefixMetadata.length && i < metadata.length; i++) { - metadata[i] = prefixMetadata[i] - hasMetadata ||= hasRoutePathSegmentMetadata(metadata[i]) - } - } - - const offset = countRoutePathSegments(prefixPath) - if (childMetadata) { - for (let i = 1; i < childMetadata.length; i++) { - const targetIndex = offset + i - if (targetIndex >= metadata.length) break - - metadata[targetIndex] = mergeRoutePathSegmentMetadata( - metadata[targetIndex], - childMetadata[i], - ) - hasMetadata ||= hasRoutePathSegmentMetadata(metadata[targetIndex]) - } - } - - return hasMetadata ? metadata : undefined -} - const backslashRegex = /\\/g export function replaceBackslash(s: string) { @@ -519,23 +328,6 @@ export function removeUnderscores(s?: string) { .replace(underscoreSlashRegex, '/') } -function removeUnderscoresFromSegment( - segment: string, - metadata?: RoutePathSegmentMetadata, -): string { - let result = segment - - if (result.startsWith('_') && !metadata?.literalLeadingUnderscore) { - result = result.slice(1) - } - - if (result.endsWith('_') && !metadata?.literalTrailingUnderscore) { - result = result.slice(0, -1) - } - - return result -} - /** * Removes underscores from a path, but preserves underscores that were escaped * in the original path (indicated by [_] syntax). @@ -551,51 +343,31 @@ export function removeUnderscoresWithEscape( if (!routePath) return '' if (!originalPath) return removeUnderscores(routePath) ?? '' - const routeSegments = routePath.split('/') - const metadata = createRoutePathSegmentMetadata(routePath, originalPath) - const newSegments = new Array<string>(routeSegments.length) - - for (let i = 0; i < routeSegments.length; i++) { - newSegments[i] = removeUnderscoresFromSegment( - routeSegments[i]!, - metadata?.[i], - ) - } - - return newSegments.join('/') -} - -export function removeLayoutSegmentsAndUnderscoresWithEscape( - routePath: string = '/', - originalPath?: string, - routePathSegmentMetadata?: Array<RoutePathSegmentMetadata | undefined>, -): string { - if (!originalPath) { - return removeUnderscores(removeLayoutSegments(routePath)) ?? '' - } - - const metadata = - routePathSegmentMetadata ?? - createRoutePathSegmentMetadata(routePath, originalPath) - const routeSegments = routePath.split('/') const originalSegments = originalPath.split('/') - const newSegments: Array<string> = [] - for (let i = 0; i < routeSegments.length; i++) { - const segment = routeSegments[i]! + const newSegments = routeSegments.map((segment, i) => { const originalSegment = originalSegments[i] || '' - const segmentMetadata = metadata?.[i] - if ( - !segmentMetadata?.literalLeadingUnderscore && - isSegmentPathless(segment, originalSegment) - ) { - continue + // Check if leading underscore is escaped + const leadingEscaped = hasEscapedLeadingUnderscore(originalSegment) + // Check if trailing underscore is escaped + const trailingEscaped = hasEscapedTrailingUnderscore(originalSegment) + + let result = segment + + // Remove leading underscore only if not escaped + if (result.startsWith('_') && !leadingEscaped) { + result = result.slice(1) } - newSegments.push(removeUnderscoresFromSegment(segment, segmentMetadata)) - } + // Remove trailing underscore only if not escaped + if (result.endsWith('_') && !trailingEscaped) { + result = result.slice(0, -1) + } + + return result + }) return newSegments.join('/') } @@ -642,7 +414,7 @@ export function isSegmentPathless( return !hasEscapedLeadingUnderscore(originalSegment) } -export function escapeRegExp(s: string): string { +function escapeRegExp(s: string): string { return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') } @@ -710,7 +482,7 @@ export function createTokenRegex( } } -function isBracketWrappedSegment(segment: string): boolean { +export function isBracketWrappedSegment(segment: string): boolean { return segment.startsWith('[') && segment.endsWith(']') } @@ -913,10 +685,26 @@ export const getResolvedRouteNodeVariableName = ( : `${routeNode.variableName}Route` } +/** + * Checks if a given RouteNode is valid for augmenting it with typing based on conditions. + * Also asserts that the RouteNode is defined. + * + * @param routeNode - The RouteNode to check. + * @returns A boolean indicating whether the RouteNode is defined. + */ +export function isRouteNodeValidForAugmentation( + routeNode?: RouteNode, +): routeNode is RouteNode { + if (!routeNode || routeNode.isVirtual) { + return false + } + return true +} + /** * Infers the path for use by TS */ -const inferPath = (routeNode: RouteNode): string => { +export const inferPath = (routeNode: RouteNode): string => { if (routeNode.cleanedPath === '/') { return routeNode.cleanedPath ?? '' } @@ -924,15 +712,16 @@ const inferPath = (routeNode: RouteNode): string => { } /** - * The full path with groups and pathless segments removed. A route group's - * layout (e.g. `/(group)/_layout`) strips down to `''`. + * Infers the full path for use by TS */ -const stripFullPath = (routeNode: RouteNode): string => { +export const inferFullPath = (routeNode: RouteNode): string => { const fullPath = removeGroups( - removeLayoutSegmentsAndUnderscoresWithEscape( - routeNode.routePath, + removeUnderscoresWithEscape( + removeLayoutSegmentsWithEscape( + routeNode.routePath, + routeNode.originalRoutePath, + ), routeNode.originalRoutePath, - routeNode._routePathSegmentMetadata, ), ) @@ -950,13 +739,6 @@ const stripFullPath = (routeNode: RouteNode): string => { return fullPath.replace(/\/$/, '') } -/** - * Infers the full path for use by TS - */ -export const inferFullPath = (routeNode: RouteNode): string => - // A route group's layout has the router's full path `/` - stripFullPath(routeNode) || '/' - const shouldPreferIndexRoute = ( current: RouteNode, existing: RouteNode, @@ -964,46 +746,6 @@ const shouldPreferIndexRoute = ( return existing.cleanedPath === '/' && current.cleanedPath !== '/' } -const isIndexRouteNode = (routeNode: RouteNode): boolean => { - return routeNode.routePath?.endsWith('/') ?? false -} - -const isPathlessRouteNode = (routeNode: RouteNode): boolean => { - return routeNode._fsRouteType === 'pathless_layout' -} - -const shouldReplaceRouteNodeForTo = ( - current: RouteNode, - existing: RouteNode, -): boolean => { - const currentIsIndex = isIndexRouteNode(current) - const existingIsIndex = isIndexRouteNode(existing) - if (currentIsIndex !== existingIsIndex) { - return currentIsIndex - } - - const currentIsPathless = isPathlessRouteNode(current) - const existingIsPathless = isPathlessRouteNode(existing) - if (currentIsPathless !== existingIsPathless) { - return !currentIsPathless - } - - return true -} - -const shouldReplaceRouteNodeForFullPath = ( - current: RouteNode, - existing: RouteNode, -): boolean => { - const currentIsPathless = isPathlessRouteNode(current) - const existingIsPathless = isPathlessRouteNode(existing) - if (currentIsPathless !== existingIsPathless) { - return !currentIsPathless - } - - return true -} - /** * Creates a map from fullPath to routeNode */ @@ -1022,11 +764,6 @@ export const createRouteNodesByFullPath = ( } } - const existing = map.get(fullPath) - if (existing && !shouldReplaceRouteNodeForFullPath(routeNode, existing)) { - continue - } - map.set(fullPath, routeNode) } @@ -1044,9 +781,11 @@ export const createRouteNodesByTo = ( for (const routeNode of dedupeBranchesAndIndexRoutes(routeNodes)) { const to = inferTo(routeNode) - const existing = map.get(to) - if (existing && !shouldReplaceRouteNodeForTo(routeNode, existing)) { - continue + if (to === '/' && map.has('/')) { + const existing = map.get('/')! + if (shouldPreferIndexRoute(routeNode, existing)) { + continue + } } map.set(to, routeNode) @@ -1072,7 +811,7 @@ export const createRouteNodesById = ( /** * Infers to path */ -const inferTo = (routeNode: RouteNode): string => { +export const inferTo = (routeNode: RouteNode): string => { const fullPath = inferFullPath(routeNode) if (fullPath === '/') return fullPath @@ -1083,7 +822,7 @@ const inferTo = (routeNode: RouteNode): string => { /** * Dedupes branches and index routes */ -const dedupeBranchesAndIndexRoutes = ( +export const dedupeBranchesAndIndexRoutes = ( routes: Array<RouteNode>, ): Array<RouteNode> => { return routes.filter((route) => { @@ -1120,12 +859,8 @@ Conflicting files: \n ${emptyPathRoutes throw new Error(errorMessage) } - // A route group's layout keeps its stripped path `''` here, so one without - // child routes yet doesn't conflict with the index route. A childless - // `_auth.tsx` does: the route tree lists the index route first, and the - // router would then match `/` to the layout const routes = _routes.map((d) => { - const inferredFullPath = stripFullPath(d) + const inferredFullPath = inferFullPath(d) return { ...d, inferredFullPath } }) @@ -1209,6 +944,14 @@ export function buildImportString( : '' } +export function lowerCaseFirstChar(value: string) { + if (!value[0]) { + return value + } + + return value[0].toLowerCase() + value.slice(1) +} + export function mergeImportDeclarations( imports: Array<ImportDeclaration>, ): Array<ImportDeclaration> { @@ -1279,7 +1022,7 @@ export function buildFileRoutesByPathInterface(opts: { }` } -function getImportPath( +export function getImportPath( node: RouteNode, config: Config, generatedRouteTreePath: string, diff --git a/packages/router-generator/tests/childless-pathless-layout.test.ts b/packages/router-generator/tests/childless-pathless-layout.test.ts deleted file mode 100644 index caef9449bf..0000000000 --- a/packages/router-generator/tests/childless-pathless-layout.test.ts +++ /dev/null @@ -1,107 +0,0 @@ -import fs from 'node:fs/promises' -import os from 'node:os' -import path from 'node:path' -import { afterEach, describe, expect, it, test } from 'vitest' - -import { Generator, getConfig } from '../src' - -let tempDir: string | undefined - -afterEach(async () => { - if (tempDir) { - await fs.rm(tempDir, { recursive: true, force: true }) - tempDir = undefined - } -}) - -function routeSource(id: string) { - if (id === '__root__') { - return `import { createRootRoute } from '@tanstack/react-router' - -export const Route = createRootRoute() -` - } - return `import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('${id}')() -` -} - -async function generate(files: Record<string, string>) { - tempDir = await fs.mkdtemp( - path.join(os.tmpdir(), 'tsr-generator-childless-layout-'), - ) - const routesDirectory = path.join(tempDir, 'routes') - for (const [file, id] of Object.entries(files)) { - const filePath = path.join(routesDirectory, file) - await fs.mkdir(path.dirname(filePath), { recursive: true }) - await fs.writeFile(filePath, routeSource(id)) - } - const generatedRouteTree = path.join(tempDir, 'routeTree.gen.ts') - const generator = new Generator({ - config: getConfig( - { - disableLogging: true, - routesDirectory, - generatedRouteTree, - tmpDir: path.join(tempDir, 'tmp'), - }, - tempDir, - ), - root: tempDir, - }) - await generator.run() - return fs.readFile(generatedRouteTree, 'utf-8') -} - -// A route group's layout without child routes yet next to the index route -// generates, as before route-group layouts were typed with the full path `/`. -describe('a route-group layout without child routes yet next to the index route', () => { - it.each([ - { file: '(group)/_layout.tsx', id: '/(group)/_layout' }, - { file: '(marketing)/route.tsx', id: '/(marketing)' }, - ])('$file is added to the route tree', async ({ file, id }) => { - const routeTree = await generate({ - '__root.tsx': '__root__', - 'index.tsx': '/', - [file]: id, - }) - - expect(routeTree).toContain(`'${id}': typeof`) - }) -}) - -// The route tree lists the index route first, and the router then matches -// `/` to a pathless layout without child routes instead of the index route. -// The generator refuses that pair rather than hide the index route. -test('a pathless layout without child routes yet conflicts with the index route', async () => { - await expect( - generate({ - '__root.tsx': '__root__', - 'index.tsx': '/', - '_auth.tsx': '/_auth', - }), - ).rejects.toThrow( - 'Conflicting configuration paths were found for the following routes: "/", "/".', - ) -}) - -// A pathless layout whose parent directory has no route file of its own -// (`foo/_layout.tsx` without `foo.tsx`) carries that directory's path, so it -// matches `/foo` like any other route there. -describe('a layout without child routes yet that adds a path', () => { - it.each([ - { file: '(group)/foo.tsx', id: '/(group)/foo' }, - { file: 'foo_.tsx', id: '/foo_' }, - ])('conflicts with $file at the same full path', async ({ file, id }) => { - await expect( - generate({ - '__root.tsx': '__root__', - 'foo/_layout.tsx': '/foo/_layout', - [file]: id, - }), - ).rejects.toThrow( - 'Conflicting configuration paths were found for the following routes: "/foo", "/foo".', - ) - }) -}) diff --git a/packages/router-generator/tests/concurrent-write.test.ts b/packages/router-generator/tests/concurrent-write.test.ts deleted file mode 100644 index 6550ad562d..0000000000 --- a/packages/router-generator/tests/concurrent-write.test.ts +++ /dev/null @@ -1,148 +0,0 @@ -import fs from 'node:fs/promises' -import os from 'node:os' -import path from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' - -import { Generator, getConfig } from '../src' - -const rootRouteSource = `import { createRootRoute } from '@tanstack/react-router' - -export const Route = createRootRoute() -` - -const postsRouteSource = `import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/posts')({ - component: () => 'posts', -}) -` - -const savedPostsRouteSource = postsRouteSource.replace("'posts'", "'saved'") - -let tempDir: string | undefined - -afterEach(async () => { - if (tempDir) { - await fs.rm(tempDir, { recursive: true, force: true }) - tempDir = undefined - } -}) - -async function readFileWithStat(filePath: string) { - try { - const fileHandle = await fs.open(filePath, 'r') - const stat = await fileHandle.stat({ bigint: true }) - const fileContent = (await fileHandle.readFile()).toString() - await fileHandle.close() - return { stat, fileContent } - } catch (e: any) { - if (e?.code === 'ENOENT') { - return 'file-not-existing' as const - } - throw e - } -} - -describe('generator with concurrent in-place saves', () => { - it.each(['route file read', 'temporary file stat'] as const)( - 'does not scaffold over a route file whose in-place save completes during the %s', - async (completeSaveDuring) => { - tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'tsr-generator-race-')) - const routesDirectory = path.join(tempDir, 'routes') - const tmpDir = path.join(tempDir, 'tmp') - const postsRoutePath = path.join(routesDirectory, 'posts.tsx') - await fs.mkdir(routesDirectory) - await fs.writeFile( - path.join(routesDirectory, '__root.tsx'), - rootRouteSource, - ) - await fs.writeFile(postsRoutePath, postsRouteSource) - - let saveRacesNextRead = false - let completeSave: (() => Promise<void>) | undefined - - const generator = new Generator({ - config: getConfig( - { - disableLogging: true, - routesDirectory, - generatedRouteTree: path.join(tempDir, 'routeTree.gen.ts'), - tmpDir, - }, - tempDir, - ), - root: tempDir, - fs: { - rename: (oldPath, newPath) => fs.rename(oldPath, newPath), - writeFile: (filePath, content) => fs.writeFile(filePath, content), - readFile: async (filePath) => { - // The generator passes route paths with forward slashes, also on - // Windows. - if ( - !saveRacesNextRead || - path.resolve(filePath) !== postsRoutePath - ) { - return readFileWithStat(filePath) - } - saveRacesNextRead = false - - // An editor saving in place truncates the file before writing the - // new content, so the generator can observe an empty route file. - await fs.truncate(postsRoutePath) - const result = await readFileWithStat(postsRoutePath) - if (result === 'file-not-existing') { - throw new Error('expected the route file to exist') - } - - // The save then completes within the same timestamp tick, which is - // common for filesystems with coarse mtime granularity. - completeSave = async () => { - completeSave = undefined - await fs.writeFile(postsRoutePath, savedPostsRouteSource) - const truncatedAt = new Date(Number(result.stat.mtimeMs)) - await fs.utimes(postsRoutePath, truncatedAt, truncatedAt) - } - if (completeSaveDuring === 'route file read') { - await completeSave() - } - - return result - }, - stat: async (filePath) => { - if (completeSave && path.resolve(filePath).startsWith(tmpDir)) { - await completeSave() - } - const stat = await fs.stat(filePath, { bigint: true }) - return { - mtimeMs: stat.mtimeMs, - mode: Number(stat.mode), - uid: Number(stat.uid), - gid: Number(stat.gid), - } - }, - chmod: (filePath, mode) => fs.chmod(filePath, mode), - chown: (filePath, uid, gid) => fs.chown(filePath, uid, gid), - }, - }) - - await generator.run() - - // A first save makes the generator process the route file again, and the - // next save races with that read. - await fs.writeFile( - postsRoutePath, - postsRouteSource.replace("'posts'", "'edited'"), - ) - const editedAt = new Date(Date.now() + 10_000) - await fs.utimes(postsRoutePath, editedAt, editedAt) - saveRacesNextRead = true - await generator.run({ type: 'update', path: postsRoutePath }) - - expect(saveRacesNextRead).toBe(false) - expect(completeSave).toBeUndefined() - await expect(fs.readFile(postsRoutePath, 'utf8')).resolves.toBe( - savedPostsRouteSource, - ) - }, - ) -}) diff --git a/packages/router-generator/tests/generator.test.ts b/packages/router-generator/tests/generator.test.ts index 3e0831fe91..c3199c378a 100644 --- a/packages/router-generator/tests/generator.test.ts +++ b/packages/router-generator/tests/generator.test.ts @@ -137,6 +137,19 @@ function rewriteConfigByFolderName(folderName: string, config: Config) { ].join(''), } break + case 'file-modification-verboseFileRoutes-true': + config.verboseFileRoutes = true + break + case 'file-modification-verboseFileRoutes-false': + config.verboseFileRoutes = false + break + // these two folders contain type tests which are executed separately + case 'nested-verboseFileRoutes-true': + config.verboseFileRoutes = true + break + case 'nested-verboseFileRoutes-false': + config.verboseFileRoutes = false + break case 'routeFileIgnore': config.routeFileIgnorePattern = 'ignoredPattern' config.routeFileIgnorePrefix = 'imIgnored' @@ -166,26 +179,6 @@ function rewriteConfigByFolderName(folderName: string, config: Config) { config.virtualRouteConfig = virtualRouteConfig } break - case 'virtual-pathless-layout-dotted-filename': - { - const virtualRouteConfig = rootRoute('root.route.tsx', [ - index('index.route.tsx'), - layout('pathless.layout.tsx', [ - route('subpath', 'subpath.route.tsx'), - ]), - ]) - config.virtualRouteConfig = virtualRouteConfig - } - break - case 'virtual-explicit-dotted-paths': - { - const virtualRouteConfig = rootRoute('root.tsx', [ - route('direct.path', 'direct.tsx'), - physical('/mounted.path', 'physical-routes'), - ]) - config.virtualRouteConfig = virtualRouteConfig - } - break case 'virtual-root-sibling-routes': { // Test case for issue #5431: Virtual routes that are siblings at the root level @@ -247,49 +240,8 @@ async function preprocess(folderName: string) { await fs.copyFile(templatePath, makeRoutePath('foo.tsx')) await fs.copyFile(lazyTemplatePath, makeRoutePath('initiallyLazy.tsx')) await fs.copyFile(templatePath, makeRoutePath('bar.lazy.tsx')) - await fs.copyFile(templatePath, makeRoutePath('double-quotes.tsx')) - await fs.copyFile(templatePath, makeRoutePath('template-literal.tsx')) - await fs.copyFile(templatePath, makeRoutePath('duplicate-import.tsx')) await makeEmptyFile('initiallyEmpty.tsx') await makeEmptyFile('initiallyEmpty.lazy.tsx') - - await fs.writeFile( - makeRoutePath('double-quotes.tsx'), - (await fs.readFile(makeRoutePath('double-quotes.tsx'), 'utf-8')).replace( - "createFileRoute('/foo/bar')", - 'createFileRoute("/foo/bar")', - ), - ) - - await fs.writeFile( - makeRoutePath('template-literal.tsx'), - ( - await fs.readFile(makeRoutePath('template-literal.tsx'), 'utf-8') - ).replace("createFileRoute('/foo/bar')", 'createFileRoute(`/foo/bar`)'), - ) - - await fs.writeFile( - makeRoutePath('duplicate-import.tsx'), - [ - "import { createFileRoute } from '@tanstack/react-router'", - "import * as React from 'react'", - "import { Link, Outlet } from '@tanstack/react-router'", - '', - "export const Route = createFileRoute('/foo/bar')({", - ' component: PostsLayoutComponent,', - '})', - '', - 'function PostsLayoutComponent() {', - ' return (', - ' <>', - ' <Link to="/">Home</Link>', - ' <Outlet />', - ' </>', - ' )', - '}', - '', - ].join('\n'), - ) } else if (folderName === 'custom-scaffolding') { const makeEmptyFile = async (...file: Array<string>) => { const filePath = join(makeFolderDir(folderName), 'routes', ...file) @@ -308,7 +260,8 @@ async function preprocess(folderName: string) { async function postprocess(folderName: string) { switch (folderName) { - case 'file-modification': { + case 'file-modification-verboseFileRoutes-false': + case 'file-modification-verboseFileRoutes-true': { const routeFiles = await readDir(folderName, 'routes', '(test)') await Promise.all( routeFiles diff --git a/packages/router-generator/tests/generator/add-extensions-custom/routeTree.snapshot.ts b/packages/router-generator/tests/generator/add-extensions-custom/routeTree.snapshot.ts index 2e6aa9d355..7859b1f9ff 100644 --- a/packages/router-generator/tests/generator/add-extensions-custom/routeTree.snapshot.ts +++ b/packages/router-generator/tests/generator/add-extensions-custom/routeTree.snapshot.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.js' -import { Route as IndexRouteImport } from './routes/index.js' import { Route as PostsRouteImport } from './routes/posts.js' +import { Route as IndexRouteImport } from './routes/index.js' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const PostsRoute = PostsRouteImport.update({ id: '/posts', path: '/posts', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/posts': { id: '/posts' path: '/posts' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/packages/router-generator/tests/generator/custom-scaffolding/routeTree.snapshot.ts b/packages/router-generator/tests/generator/custom-scaffolding/routeTree.snapshot.ts index 8f0ed564f4..e80d1e7e73 100644 --- a/packages/router-generator/tests/generator/custom-scaffolding/routeTree.snapshot.ts +++ b/packages/router-generator/tests/generator/custom-scaffolding/routeTree.snapshot.ts @@ -16,16 +16,16 @@ import { Route as ApiBarRouteImport } from './routes/api/bar' const FooLazyRouteImport = createFileRoute('/foo')() -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const FooLazyRoute = FooLazyRouteImport.update({ id: '/foo', path: '/foo', getParentRoute: () => rootRouteImport, } as any).lazy(() => import('./routes/foo.lazy').then((d) => d.Route)) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const ApiBarRoute = ApiBarRouteImport.update({ id: '/api/bar', path: '/api/bar', @@ -64,13 +64,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/foo': { id: '/foo' path: '/foo' @@ -78,6 +71,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof FooLazyRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } '/api/bar': { id: '/api/bar' path: '/api/bar' diff --git a/packages/router-generator/tests/generator/custom-tokens/routeTree.snapshot.ts b/packages/router-generator/tests/generator/custom-tokens/routeTree.snapshot.ts index fc136dc277..f49d059f20 100644 --- a/packages/router-generator/tests/generator/custom-tokens/routeTree.snapshot.ts +++ b/packages/router-generator/tests/generator/custom-tokens/routeTree.snapshot.ts @@ -9,18 +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 R1nd3xRouteImport } from './routes/_1nd3x' -import { Route as BlogR0ut3RouteImport } from './routes/blog/_r0ut3_' import { Route as PostsR0ut3RouteImport } from './routes/posts/_r0ut3_' +import { Route as BlogR0ut3RouteImport } from './routes/blog/_r0ut3_' +import { Route as R1nd3xRouteImport } from './routes/_1nd3x' +import { Route as Posts1nd3xRouteImport } from './routes/posts/_1nd3x' import { Route as Blog1nd3xRouteImport } from './routes/blog/_1nd3x' import { Route as BlogSlugRouteImport } from './routes/blog/$slug' -import { Route as Posts1nd3xRouteImport } from './routes/posts/_1nd3x' import { Route as PostsPostId1nd3xRouteImport } from './routes/posts/$postId/_1nd3x' import { Route as PostsPostIdDeepRouteImport } from './routes/posts/$postId/deep' -const R1nd3xRoute = R1nd3xRouteImport.update({ - id: '/', - path: '/', +const PostsR0ut3Route = PostsR0ut3RouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) const BlogR0ut3Route = BlogR0ut3RouteImport.update({ @@ -28,11 +28,16 @@ const BlogR0ut3Route = BlogR0ut3RouteImport.update({ path: '/blog', getParentRoute: () => rootRouteImport, } as any) -const PostsR0ut3Route = PostsR0ut3RouteImport.update({ - id: '/posts', - path: '/posts', +const R1nd3xRoute = R1nd3xRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) +const Posts1nd3xRoute = Posts1nd3xRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PostsR0ut3Route, +} as any) const Blog1nd3xRoute = Blog1nd3xRouteImport.update({ id: '/', path: '/', @@ -43,11 +48,6 @@ const BlogSlugRoute = BlogSlugRouteImport.update({ path: '/$slug', getParentRoute: () => BlogR0ut3Route, } as any) -const Posts1nd3xRoute = Posts1nd3xRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => PostsR0ut3Route, -} as any) const PostsPostId1nd3xRoute = PostsPostId1nd3xRouteImport.update({ id: '/$postId/', path: '/$postId/', @@ -127,11 +127,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof R1nd3xRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsR0ut3RouteImport parentRoute: typeof rootRouteImport } '/blog': { @@ -141,13 +141,20 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof BlogR0ut3RouteImport parentRoute: typeof rootRouteImport } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsR0ut3RouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof R1nd3xRouteImport parentRoute: typeof rootRouteImport } + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof Posts1nd3xRouteImport + parentRoute: typeof PostsR0ut3Route + } '/blog/': { id: '/blog/' path: '/' @@ -162,13 +169,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof BlogSlugRouteImport parentRoute: typeof BlogR0ut3Route } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof Posts1nd3xRouteImport - parentRoute: typeof PostsR0ut3Route - } '/posts/$postId/': { id: '/posts/$postId/' path: '/$postId' diff --git a/packages/router-generator/tests/generator/dot-escaped/routeTree.snapshot.ts b/packages/router-generator/tests/generator/dot-escaped/routeTree.snapshot.ts index 815dba6590..2ccc3a0a38 100644 --- a/packages/router-generator/tests/generator/dot-escaped/routeTree.snapshot.ts +++ b/packages/router-generator/tests/generator/dot-escaped/routeTree.snapshot.ts @@ -9,20 +9,25 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as NestedDotjsRouteImport } from './routes/nested[.]js' import { Route as ScriptDotjsRouteImport } from './routes/script[.]js' -import { Route as NestedDotjsDoubleDotextDotjsRouteImport } from './routes/nested[.]js.double[.]ext[.]js' +import { Route as NestedDotjsRouteImport } from './routes/nested[.]js' import { Route as NestedDotjsScriptDotjsRouteImport } from './routes/nested[.]js.script[.]js' +import { Route as NestedDotjsDoubleDotextDotjsRouteImport } from './routes/nested[.]js.double[.]ext[.]js' +const ScriptDotjsRoute = ScriptDotjsRouteImport.update({ + id: '/script.js', + path: '/script.js', + getParentRoute: () => rootRouteImport, +} as any) const NestedDotjsRoute = NestedDotjsRouteImport.update({ id: '/nested.js', path: '/nested.js', getParentRoute: () => rootRouteImport, } as any) -const ScriptDotjsRoute = ScriptDotjsRouteImport.update({ +const NestedDotjsScriptDotjsRoute = NestedDotjsScriptDotjsRouteImport.update({ id: '/script.js', path: '/script.js', - getParentRoute: () => rootRouteImport, + getParentRoute: () => NestedDotjsRoute, } as any) const NestedDotjsDoubleDotextDotjsRoute = NestedDotjsDoubleDotextDotjsRouteImport.update({ @@ -30,11 +35,6 @@ const NestedDotjsDoubleDotextDotjsRoute = path: '/double.ext.js', getParentRoute: () => NestedDotjsRoute, } as any) -const NestedDotjsScriptDotjsRoute = NestedDotjsScriptDotjsRouteImport.update({ - id: '/script.js', - path: '/script.js', - getParentRoute: () => NestedDotjsRoute, -} as any) export interface FileRoutesByFullPath { '/nested.js': typeof NestedDotjsRouteWithChildren @@ -83,13 +83,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/nested.js': { - id: '/nested.js' - path: '/nested.js' - fullPath: '/nested.js' - preLoaderRoute: typeof NestedDotjsRouteImport - parentRoute: typeof rootRouteImport - } '/script.js': { id: '/script.js' path: '/script.js' @@ -97,12 +90,12 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ScriptDotjsRouteImport parentRoute: typeof rootRouteImport } - '/nested.js/double.ext.js': { - id: '/nested.js/double.ext.js' - path: '/double.ext.js' - fullPath: '/nested.js/double.ext.js' - preLoaderRoute: typeof NestedDotjsDoubleDotextDotjsRouteImport - parentRoute: typeof NestedDotjsRoute + '/nested.js': { + id: '/nested.js' + path: '/nested.js' + fullPath: '/nested.js' + preLoaderRoute: typeof NestedDotjsRouteImport + parentRoute: typeof rootRouteImport } '/nested.js/script.js': { id: '/nested.js/script.js' @@ -111,6 +104,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof NestedDotjsScriptDotjsRouteImport parentRoute: typeof NestedDotjsRoute } + '/nested.js/double.ext.js': { + id: '/nested.js/double.ext.js' + path: '/double.ext.js' + fullPath: '/nested.js/double.ext.js' + preLoaderRoute: typeof NestedDotjsDoubleDotextDotjsRouteImport + parentRoute: typeof NestedDotjsRoute + } } } diff --git a/packages/router-generator/tests/generator/escaped-custom-tokens/routeTree.snapshot.ts b/packages/router-generator/tests/generator/escaped-custom-tokens/routeTree.snapshot.ts index 69b6a09946..e8b7404df9 100644 --- a/packages/router-generator/tests/generator/escaped-custom-tokens/routeTree.snapshot.ts +++ b/packages/router-generator/tests/generator/escaped-custom-tokens/routeTree.snapshot.ts @@ -10,8 +10,8 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as Char91_1nd3xChar93RouteImport } from './routes/[_1nd3x]' -import { Route as R1nd3xRouteImport } from './routes/_1nd3x' import { Route as BlogR0ut3RouteImport } from './routes/blog._r0ut3_' +import { Route as R1nd3xRouteImport } from './routes/_1nd3x' import { Route as NestedChar91_1nd3xChar93RouteImport } from './routes/nested.[_1nd3x]' import { Route as PostsChar91_r0ut3_Char93RouteImport } from './routes/posts.[_r0ut3_]' @@ -20,16 +20,16 @@ const Char91_1nd3xChar93Route = Char91_1nd3xChar93RouteImport.update({ path: '/_1nd3x', getParentRoute: () => rootRouteImport, } as any) -const R1nd3xRoute = R1nd3xRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const BlogR0ut3Route = BlogR0ut3RouteImport.update({ id: '/blog', path: '/blog', getParentRoute: () => rootRouteImport, } as any) +const R1nd3xRoute = R1nd3xRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const NestedChar91_1nd3xChar93Route = NestedChar91_1nd3xChar93RouteImport.update({ id: '/nested/_1nd3x', @@ -71,7 +71,12 @@ export interface FileRouteTypes { fileRoutesByTo: FileRoutesByTo to: '/' | '/blog' | '/_1nd3x' | '/nested/_1nd3x' | '/posts/_r0ut3_' id: - '__root__' | '/' | '/blog' | '/_1nd3x' | '/nested/_1nd3x' | '/posts/_r0ut3_' + | '__root__' + | '/' + | '/blog' + | '/_1nd3x' + | '/nested/_1nd3x' + | '/posts/_r0ut3_' fileRoutesById: FileRoutesById } export interface RootRouteChildren { @@ -91,13 +96,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof Char91_1nd3xChar93RouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof R1nd3xRouteImport - parentRoute: typeof rootRouteImport - } '/blog': { id: '/blog' path: '/blog' @@ -105,6 +103,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof BlogR0ut3RouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof R1nd3xRouteImport + parentRoute: typeof rootRouteImport + } '/nested/_1nd3x': { id: '/nested/_1nd3x' path: '/nested/_1nd3x' diff --git a/packages/router-generator/tests/generator/escaped-special-strings/routeTree.snapshot.ts b/packages/router-generator/tests/generator/escaped-special-strings/routeTree.snapshot.ts index 2600d0296d..ea71d9c21b 100644 --- a/packages/router-generator/tests/generator/escaped-special-strings/routeTree.snapshot.ts +++ b/packages/router-generator/tests/generator/escaped-special-strings/routeTree.snapshot.ts @@ -10,15 +10,15 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as Char91indexChar93RouteImport } from './routes/[index]' -import { Route as IndexRouteImport } from './routes/index' -import { Route as AuthRouteRouteImport } from './routes/[_]auth.route' -import { Route as LayoutRouteImport } from './routes/[_]layout' -import { Route as Prefix_middle_suffixRouteImport } from './routes/[_]prefix[_]middle[_]suffix' -import { Route as Api_v2_usersRouteImport } from './routes/api[_]v2[_]users' -import { Route as BlogRouteImport } from './routes/blog[_]' -import { Route as Foo_barRouteImport } from './routes/foo[_]bar' -import { Route as Char91lazyChar93RouteImport } from './routes/[lazy]' import { Route as Char91routeChar93RouteImport } from './routes/[route]' +import { Route as Char91lazyChar93RouteImport } from './routes/[lazy]' +import { Route as Foo_barRouteImport } from './routes/foo[_]bar' +import { Route as BlogRouteImport } from './routes/blog[_]' +import { Route as Api_v2_usersRouteImport } from './routes/api[_]v2[_]users' +import { Route as Prefix_middle_suffixRouteImport } from './routes/[_]prefix[_]middle[_]suffix' +import { Route as LayoutRouteImport } from './routes/[_]layout' +import { Route as AuthRouteRouteImport } from './routes/[_]auth.route' +import { Route as IndexRouteImport } from './routes/index' import { Route as NestedChar91indexChar93RouteImport } from './routes/nested.[index]' const Char91indexChar93Route = Char91indexChar93RouteImport.update({ @@ -26,39 +26,9 @@ const Char91indexChar93Route = Char91indexChar93RouteImport.update({ path: '/index', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const AuthRouteRoute = AuthRouteRouteImport.update({ - id: '/_auth', - path: '/_auth', - getParentRoute: () => rootRouteImport, -} as any) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', - path: '/_layout', - getParentRoute: () => rootRouteImport, -} as any) -const Prefix_middle_suffixRoute = Prefix_middle_suffixRouteImport.update({ - id: '/_prefix_middle_suffix', - path: '/_prefix_middle_suffix', - getParentRoute: () => rootRouteImport, -} as any) -const Api_v2_usersRoute = Api_v2_usersRouteImport.update({ - id: '/api_v2_users', - path: '/api_v2_users', - getParentRoute: () => rootRouteImport, -} as any) -const BlogRoute = BlogRouteImport.update({ - id: '/blog_', - path: '/blog_', - getParentRoute: () => rootRouteImport, -} as any) -const Foo_barRoute = Foo_barRouteImport.update({ - id: '/foo_bar', - path: '/foo_bar', +const Char91routeChar93Route = Char91routeChar93RouteImport.update({ + id: '/route', + path: '/route', getParentRoute: () => rootRouteImport, } as any) const Char91lazyChar93Route = Char91lazyChar93RouteImport.update({ @@ -66,9 +36,39 @@ const Char91lazyChar93Route = Char91lazyChar93RouteImport.update({ path: '/lazy', getParentRoute: () => rootRouteImport, } as any) -const Char91routeChar93Route = Char91routeChar93RouteImport.update({ - id: '/route', - path: '/route', +const Foo_barRoute = Foo_barRouteImport.update({ + id: '/foo_bar', + path: '/foo_bar', + getParentRoute: () => rootRouteImport, +} as any) +const BlogRoute = BlogRouteImport.update({ + id: '/blog_', + path: '/blog_', + getParentRoute: () => rootRouteImport, +} as any) +const Api_v2_usersRoute = Api_v2_usersRouteImport.update({ + id: '/api_v2_users', + path: '/api_v2_users', + getParentRoute: () => rootRouteImport, +} as any) +const Prefix_middle_suffixRoute = Prefix_middle_suffixRouteImport.update({ + id: '/_prefix_middle_suffix', + path: '/_prefix_middle_suffix', + getParentRoute: () => rootRouteImport, +} as any) +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', + path: '/_layout', + getParentRoute: () => rootRouteImport, +} as any) +const AuthRouteRoute = AuthRouteRouteImport.update({ + id: '/_auth', + path: '/_auth', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const NestedChar91indexChar93Route = NestedChar91indexChar93RouteImport.update({ @@ -182,53 +182,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof Char91indexChar93RouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_auth': { - id: '/_auth' - path: '/_auth' - fullPath: '/_auth' - preLoaderRoute: typeof AuthRouteRouteImport - parentRoute: typeof rootRouteImport - } - '/_layout': { - id: '/_layout' - path: '/_layout' - fullPath: '/_layout' - preLoaderRoute: typeof LayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/_prefix_middle_suffix': { - id: '/_prefix_middle_suffix' - path: '/_prefix_middle_suffix' - fullPath: '/_prefix_middle_suffix' - preLoaderRoute: typeof Prefix_middle_suffixRouteImport - parentRoute: typeof rootRouteImport - } - '/api_v2_users': { - id: '/api_v2_users' - path: '/api_v2_users' - fullPath: '/api_v2_users' - preLoaderRoute: typeof Api_v2_usersRouteImport - parentRoute: typeof rootRouteImport - } - '/blog_': { - id: '/blog_' - path: '/blog_' - fullPath: '/blog_' - preLoaderRoute: typeof BlogRouteImport - parentRoute: typeof rootRouteImport - } - '/foo_bar': { - id: '/foo_bar' - path: '/foo_bar' - fullPath: '/foo_bar' - preLoaderRoute: typeof Foo_barRouteImport + '/route': { + id: '/route' + path: '/route' + fullPath: '/route' + preLoaderRoute: typeof Char91routeChar93RouteImport parentRoute: typeof rootRouteImport } '/lazy': { @@ -238,11 +196,53 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof Char91lazyChar93RouteImport parentRoute: typeof rootRouteImport } - '/route': { - id: '/route' - path: '/route' - fullPath: '/route' - preLoaderRoute: typeof Char91routeChar93RouteImport + '/foo_bar': { + id: '/foo_bar' + path: '/foo_bar' + fullPath: '/foo_bar' + preLoaderRoute: typeof Foo_barRouteImport + parentRoute: typeof rootRouteImport + } + '/blog_': { + id: '/blog_' + path: '/blog_' + fullPath: '/blog_' + preLoaderRoute: typeof BlogRouteImport + parentRoute: typeof rootRouteImport + } + '/api_v2_users': { + id: '/api_v2_users' + path: '/api_v2_users' + fullPath: '/api_v2_users' + preLoaderRoute: typeof Api_v2_usersRouteImport + parentRoute: typeof rootRouteImport + } + '/_prefix_middle_suffix': { + id: '/_prefix_middle_suffix' + path: '/_prefix_middle_suffix' + fullPath: '/_prefix_middle_suffix' + preLoaderRoute: typeof Prefix_middle_suffixRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout': { + id: '/_layout' + path: '/_layout' + fullPath: '/_layout' + preLoaderRoute: typeof LayoutRouteImport + parentRoute: typeof rootRouteImport + } + '/_auth': { + id: '/_auth' + path: '/_auth' + fullPath: '/_auth' + preLoaderRoute: typeof AuthRouteRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/nested/index': { diff --git a/packages/router-generator/tests/generator/export-variations/routeTree.snapshot.ts b/packages/router-generator/tests/generator/export-variations/routeTree.snapshot.ts index bb251cc516..6362489435 100644 --- a/packages/router-generator/tests/generator/export-variations/routeTree.snapshot.ts +++ b/packages/router-generator/tests/generator/export-variations/routeTree.snapshot.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 ExportSeparateFromDeclarationRouteImport } from './routes/export-separate-from-declaration' import { Route as ExportWithAsRouteImport } from './routes/export-with-as' +import { Route as ExportSeparateFromDeclarationRouteImport } from './routes/export-separate-from-declaration' +const ExportWithAsRoute = ExportWithAsRouteImport.update({ + id: '/export-with-as', + path: '/export-with-as', + getParentRoute: () => rootRouteImport, +} as any) const ExportSeparateFromDeclarationRoute = ExportSeparateFromDeclarationRouteImport.update({ id: '/export-separate-from-declaration', path: '/export-separate-from-declaration', getParentRoute: () => rootRouteImport, } as any) -const ExportWithAsRoute = ExportWithAsRouteImport.update({ - id: '/export-with-as', - path: '/export-with-as', - getParentRoute: () => rootRouteImport, -} as any) export interface FileRoutesByFullPath { '/export-separate-from-declaration': typeof ExportSeparateFromDeclarationRoute @@ -52,13 +52,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/export-separate-from-declaration': { - id: '/export-separate-from-declaration' - path: '/export-separate-from-declaration' - fullPath: '/export-separate-from-declaration' - preLoaderRoute: typeof ExportSeparateFromDeclarationRouteImport - parentRoute: typeof rootRouteImport - } '/export-with-as': { id: '/export-with-as' path: '/export-with-as' @@ -66,6 +59,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ExportWithAsRouteImport parentRoute: typeof rootRouteImport } + '/export-separate-from-declaration': { + id: '/export-separate-from-declaration' + path: '/export-separate-from-declaration' + fullPath: '/export-separate-from-declaration' + preLoaderRoute: typeof ExportSeparateFromDeclarationRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-false/routeTree.snapshot.ts b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-false/routeTree.snapshot.ts new file mode 100644 index 0000000000..6cd0f9c68e --- /dev/null +++ b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-false/routeTree.snapshot.ts @@ -0,0 +1,207 @@ +/* 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 { createFileRoute } from '@tanstack/react-router' +import type { + CreateFileRoute, + CreateLazyFileRoute, + FileRoutesByPath, +} from '@tanstack/react-router' + +import { Route as rootRouteImport } from './routes/__root' +import { Route as testInitiallyLazyRouteImport } from './routes/(test)/initiallyLazy' +import { Route as testInitiallyEmptyRouteImport } from './routes/(test)/initiallyEmpty' +import { Route as testFooRouteImport } from './routes/(test)/foo' +import { Route as testFooBarRouteImport } from './routes/(test)/foo.bar' + +const testBarLazyRouteImport = createFileRoute('/(test)/bar')() + +const testBarLazyRoute = testBarLazyRouteImport + .update({ + id: '/(test)/bar', + path: '/bar', + getParentRoute: () => rootRouteImport, + } as any) + .lazy(() => import('./routes/(test)/bar.lazy').then((d) => d.Route)) +const testInitiallyLazyRoute = testInitiallyLazyRouteImport.update({ + id: '/(test)/initiallyLazy', + path: '/initiallyLazy', + getParentRoute: () => rootRouteImport, +} as any) +const testInitiallyEmptyRoute = testInitiallyEmptyRouteImport + .update({ + id: '/(test)/initiallyEmpty', + path: '/initiallyEmpty', + getParentRoute: () => rootRouteImport, + } as any) + .lazy(() => + import('./routes/(test)/initiallyEmpty.lazy').then((d) => d.Route), + ) +const testFooRoute = testFooRouteImport.update({ + id: '/(test)/foo', + path: '/foo', + getParentRoute: () => rootRouteImport, +} as any) +const testFooBarRoute = testFooBarRouteImport.update({ + id: '/bar', + path: '/bar', + getParentRoute: () => testFooRoute, +} as any) + +export interface FileRoutesByFullPath { + '/foo': typeof testFooRouteWithChildren + '/initiallyEmpty': typeof testInitiallyEmptyRoute + '/initiallyLazy': typeof testInitiallyLazyRoute + '/bar': typeof testBarLazyRoute + '/foo/bar': typeof testFooBarRoute +} +export interface FileRoutesByTo { + '/foo': typeof testFooRouteWithChildren + '/initiallyEmpty': typeof testInitiallyEmptyRoute + '/initiallyLazy': typeof testInitiallyLazyRoute + '/bar': typeof testBarLazyRoute + '/foo/bar': typeof testFooBarRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/(test)/foo': typeof testFooRouteWithChildren + '/(test)/initiallyEmpty': typeof testInitiallyEmptyRoute + '/(test)/initiallyLazy': typeof testInitiallyLazyRoute + '/(test)/bar': typeof testBarLazyRoute + '/(test)/foo/bar': typeof testFooBarRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/foo' | '/initiallyEmpty' | '/initiallyLazy' | '/bar' | '/foo/bar' + fileRoutesByTo: FileRoutesByTo + to: '/foo' | '/initiallyEmpty' | '/initiallyLazy' | '/bar' | '/foo/bar' + id: + | '__root__' + | '/(test)/foo' + | '/(test)/initiallyEmpty' + | '/(test)/initiallyLazy' + | '/(test)/bar' + | '/(test)/foo/bar' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + testFooRoute: typeof testFooRouteWithChildren + testInitiallyEmptyRoute: typeof testInitiallyEmptyRoute + testInitiallyLazyRoute: typeof testInitiallyLazyRoute + testBarLazyRoute: typeof testBarLazyRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/(test)/bar': { + id: '/(test)/bar' + path: '/bar' + fullPath: '/bar' + preLoaderRoute: typeof testBarLazyRouteImport + parentRoute: typeof rootRouteImport + } + '/(test)/initiallyLazy': { + id: '/(test)/initiallyLazy' + path: '/initiallyLazy' + fullPath: '/initiallyLazy' + preLoaderRoute: typeof testInitiallyLazyRouteImport + parentRoute: typeof rootRouteImport + } + '/(test)/initiallyEmpty': { + id: '/(test)/initiallyEmpty' + path: '/initiallyEmpty' + fullPath: '/initiallyEmpty' + preLoaderRoute: typeof testInitiallyEmptyRouteImport + parentRoute: typeof rootRouteImport + } + '/(test)/foo': { + id: '/(test)/foo' + path: '/foo' + fullPath: '/foo' + preLoaderRoute: typeof testFooRouteImport + parentRoute: typeof rootRouteImport + } + '/(test)/foo/bar': { + id: '/(test)/foo/bar' + path: '/bar' + fullPath: '/foo/bar' + preLoaderRoute: typeof testFooBarRouteImport + parentRoute: typeof testFooRoute + } + } +} + +declare module './routes/(test)/foo' { + const createFileRoute: CreateFileRoute< + '/(test)/foo', + FileRoutesByPath['/(test)/foo']['parentRoute'], + FileRoutesByPath['/(test)/foo']['id'], + FileRoutesByPath['/(test)/foo']['path'], + FileRoutesByPath['/(test)/foo']['fullPath'] + > +} +declare module './routes/(test)/initiallyEmpty' { + const createFileRoute: CreateFileRoute< + '/(test)/initiallyEmpty', + FileRoutesByPath['/(test)/initiallyEmpty']['parentRoute'], + FileRoutesByPath['/(test)/initiallyEmpty']['id'], + FileRoutesByPath['/(test)/initiallyEmpty']['path'], + FileRoutesByPath['/(test)/initiallyEmpty']['fullPath'] + > +} +declare module './routes/(test)/initiallyLazy' { + const createFileRoute: CreateFileRoute< + '/(test)/initiallyLazy', + FileRoutesByPath['/(test)/initiallyLazy']['parentRoute'], + FileRoutesByPath['/(test)/initiallyLazy']['id'], + FileRoutesByPath['/(test)/initiallyLazy']['path'], + FileRoutesByPath['/(test)/initiallyLazy']['fullPath'] + > +} +declare module './routes/(test)/bar.lazy' { + const createLazyFileRoute: CreateLazyFileRoute< + FileRoutesByPath['/(test)/bar']['preLoaderRoute'] + > +} +declare module './routes/(test)/initiallyEmpty.lazy' { + const createLazyFileRoute: CreateLazyFileRoute< + FileRoutesByPath['/(test)/initiallyEmpty']['preLoaderRoute'] + > +} +declare module './routes/(test)/foo.bar' { + const createFileRoute: CreateFileRoute< + '/(test)/foo/bar', + FileRoutesByPath['/(test)/foo/bar']['parentRoute'], + FileRoutesByPath['/(test)/foo/bar']['id'], + FileRoutesByPath['/(test)/foo/bar']['path'], + FileRoutesByPath['/(test)/foo/bar']['fullPath'] + > +} + +interface testFooRouteChildren { + testFooBarRoute: typeof testFooBarRoute +} + +const testFooRouteChildren: testFooRouteChildren = { + testFooBarRoute: testFooBarRoute, +} + +const testFooRouteWithChildren = + testFooRoute._addFileChildren(testFooRouteChildren) + +const rootRouteChildren: RootRouteChildren = { + testFooRoute: testFooRouteWithChildren, + testInitiallyEmptyRoute: testInitiallyEmptyRoute, + testInitiallyLazyRoute: testInitiallyLazyRoute, + testBarLazyRoute: testBarLazyRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes<FileRouteTypes>() diff --git a/packages/router-generator/tests/generator/file-modification/routes/(test)/-keep-directory b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-false/routes/(test)/-keep-directory similarity index 100% rename from packages/router-generator/tests/generator/file-modification/routes/(test)/-keep-directory rename to packages/router-generator/tests/generator/file-modification-verboseFileRoutes-false/routes/(test)/-keep-directory diff --git a/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-false/routes/.gitignore b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-false/routes/.gitignore new file mode 100644 index 0000000000..e0c201406d --- /dev/null +++ b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-false/routes/.gitignore @@ -0,0 +1 @@ +(test)/*.tsx \ No newline at end of file diff --git a/packages/router-generator/tests/generator/file-modification/routes/__root.tsx b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-false/routes/__root.tsx similarity index 100% rename from packages/router-generator/tests/generator/file-modification/routes/__root.tsx rename to packages/router-generator/tests/generator/file-modification-verboseFileRoutes-false/routes/__root.tsx diff --git a/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-false/snapshots/bar.lazy.tsx b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-false/snapshots/bar.lazy.tsx new file mode 100644 index 0000000000..da8052b46c --- /dev/null +++ b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-false/snapshots/bar.lazy.tsx @@ -0,0 +1,47 @@ +// @ts-nocheck + +import * as React from 'react' +import { + ErrorComponent, + ErrorComponentProps, + Link, +} from '@tanstack/react-router' + +export const Route = createLazyFileRoute({ + loader: async ({ params: { postId } }) => ({ + postId, + title: 'title', + body: 'body', + id: 'id', + }), + errorComponent: PostErrorComponent as any, + notFoundComponent: () => { + return <p>Post not found</p> + }, + component: PostComponent, +}) + +export function PostErrorComponent({ error }: ErrorComponentProps) { + return <ErrorComponent error={error} /> +} + +function PostComponent() { + const post = Route.useLoaderData() + + return ( + <div className="space-y-2"> + <h4 className="text-xl font-bold underline">{post.title}</h4> + <div className="text-sm">{post.body}</div> + <Link + to="/posts/$postId/deep" + params={{ + postId: post.id, + }} + activeProps={{ className: 'text-black font-bold' }} + className="inline-block py-1 text-blue-800 hover:text-blue-600" + > + Deep View + </Link> + </div> + ) +} diff --git a/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-false/snapshots/foo.bar.tsx b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-false/snapshots/foo.bar.tsx new file mode 100644 index 0000000000..cf174606e1 --- /dev/null +++ b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-false/snapshots/foo.bar.tsx @@ -0,0 +1,47 @@ +// @ts-nocheck + +import * as React from 'react' +import { + ErrorComponent, + ErrorComponentProps, + Link, +} from '@tanstack/react-router' + +export const Route = createFileRoute({ + loader: async ({ params: { postId } }) => ({ + postId, + title: 'title', + body: 'body', + id: 'id', + }), + errorComponent: PostErrorComponent as any, + notFoundComponent: () => { + return <p>Post not found</p> + }, + component: PostComponent, +}) + +export function PostErrorComponent({ error }: ErrorComponentProps) { + return <ErrorComponent error={error} /> +} + +function PostComponent() { + const post = Route.useLoaderData() + + return ( + <div className="space-y-2"> + <h4 className="text-xl font-bold underline">{post.title}</h4> + <div className="text-sm">{post.body}</div> + <Link + to="/posts/$postId/deep" + params={{ + postId: post.id, + }} + activeProps={{ className: 'text-black font-bold' }} + className="inline-block py-1 text-blue-800 hover:text-blue-600" + > + Deep View + </Link> + </div> + ) +} diff --git a/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-false/snapshots/foo.tsx b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-false/snapshots/foo.tsx new file mode 100644 index 0000000000..cf174606e1 --- /dev/null +++ b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-false/snapshots/foo.tsx @@ -0,0 +1,47 @@ +// @ts-nocheck + +import * as React from 'react' +import { + ErrorComponent, + ErrorComponentProps, + Link, +} from '@tanstack/react-router' + +export const Route = createFileRoute({ + loader: async ({ params: { postId } }) => ({ + postId, + title: 'title', + body: 'body', + id: 'id', + }), + errorComponent: PostErrorComponent as any, + notFoundComponent: () => { + return <p>Post not found</p> + }, + component: PostComponent, +}) + +export function PostErrorComponent({ error }: ErrorComponentProps) { + return <ErrorComponent error={error} /> +} + +function PostComponent() { + const post = Route.useLoaderData() + + return ( + <div className="space-y-2"> + <h4 className="text-xl font-bold underline">{post.title}</h4> + <div className="text-sm">{post.body}</div> + <Link + to="/posts/$postId/deep" + params={{ + postId: post.id, + }} + activeProps={{ className: 'text-black font-bold' }} + className="inline-block py-1 text-blue-800 hover:text-blue-600" + > + Deep View + </Link> + </div> + ) +} diff --git a/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-false/snapshots/initiallyEmpty.lazy.tsx b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-false/snapshots/initiallyEmpty.lazy.tsx new file mode 100644 index 0000000000..f8ab9154f9 --- /dev/null +++ b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-false/snapshots/initiallyEmpty.lazy.tsx @@ -0,0 +1,7 @@ +export const Route = createLazyFileRoute({ + component: RouteComponent, +}) + +function RouteComponent() { + return <div>Hello "/(test)/initiallyEmpty"!</div> +} diff --git a/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-false/snapshots/initiallyEmpty.tsx b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-false/snapshots/initiallyEmpty.tsx new file mode 100644 index 0000000000..e8b24c1429 --- /dev/null +++ b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-false/snapshots/initiallyEmpty.tsx @@ -0,0 +1,7 @@ +export const Route = createFileRoute({ + component: RouteComponent, +}) + +function RouteComponent() { + return <div>Hello "/(test)/initiallyEmpty"!</div> +} diff --git a/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-false/snapshots/initiallyLazy.tsx b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-false/snapshots/initiallyLazy.tsx new file mode 100644 index 0000000000..0ce4dd43f7 --- /dev/null +++ b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-false/snapshots/initiallyLazy.tsx @@ -0,0 +1,26 @@ +// @ts-nocheck + +import { Link } from '@tanstack/react-router' + +export const Route = createFileRoute({ + component: () => { + const post = Route.useLoaderData() + + return ( + <div className="space-y-2"> + <h4 className="text-xl font-bold underline">{post.title}</h4> + <div className="text-sm">{post.body}</div> + <Link + to="/posts/$postId/deep" + params={{ + postId: post.id, + }} + activeProps={{ className: 'text-black font-bold' }} + className="block py-1 text-blue-800 hover:text-blue-600" + > + Deep View + </Link> + </div> + ) + }, +}) diff --git a/packages/router-generator/tests/generator/file-modification/template-verbose.tsx b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-false/template-verbose.tsx similarity index 100% rename from packages/router-generator/tests/generator/file-modification/template-verbose.tsx rename to packages/router-generator/tests/generator/file-modification-verboseFileRoutes-false/template-verbose.tsx diff --git a/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-false/template.lazy.tsx b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-false/template.lazy.tsx new file mode 100644 index 0000000000..45a3d5871f --- /dev/null +++ b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-false/template.lazy.tsx @@ -0,0 +1,26 @@ +// @ts-nocheck + +import { createLazyFileRoute, Link } from '@tanstack/react-router' + +export const Route = createLazyFileRoute({ + component: () => { + const post = Route.useLoaderData() + + return ( + <div className="space-y-2"> + <h4 className="text-xl font-bold underline">{post.title}</h4> + <div className="text-sm">{post.body}</div> + <Link + to="/posts/$postId/deep" + params={{ + postId: post.id, + }} + activeProps={{ className: 'text-black font-bold' }} + className="block py-1 text-blue-800 hover:text-blue-600" + > + Deep View + </Link> + </div> + ) + }, +}) diff --git a/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-false/template.tsx b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-false/template.tsx new file mode 100644 index 0000000000..cf174606e1 --- /dev/null +++ b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-false/template.tsx @@ -0,0 +1,47 @@ +// @ts-nocheck + +import * as React from 'react' +import { + ErrorComponent, + ErrorComponentProps, + Link, +} from '@tanstack/react-router' + +export const Route = createFileRoute({ + loader: async ({ params: { postId } }) => ({ + postId, + title: 'title', + body: 'body', + id: 'id', + }), + errorComponent: PostErrorComponent as any, + notFoundComponent: () => { + return <p>Post not found</p> + }, + component: PostComponent, +}) + +export function PostErrorComponent({ error }: ErrorComponentProps) { + return <ErrorComponent error={error} /> +} + +function PostComponent() { + const post = Route.useLoaderData() + + return ( + <div className="space-y-2"> + <h4 className="text-xl font-bold underline">{post.title}</h4> + <div className="text-sm">{post.body}</div> + <Link + to="/posts/$postId/deep" + params={{ + postId: post.id, + }} + activeProps={{ className: 'text-black font-bold' }} + className="inline-block py-1 text-blue-800 hover:text-blue-600" + > + Deep View + </Link> + </div> + ) +} diff --git a/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-true/routeTree.snapshot.ts b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-true/routeTree.snapshot.ts new file mode 100644 index 0000000000..816d3ddaa2 --- /dev/null +++ b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-true/routeTree.snapshot.ts @@ -0,0 +1,155 @@ +/* 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 { createFileRoute } from '@tanstack/react-router' + +import { Route as rootRouteImport } from './routes/__root' +import { Route as testInitiallyLazyRouteImport } from './routes/(test)/initiallyLazy' +import { Route as testInitiallyEmptyRouteImport } from './routes/(test)/initiallyEmpty' +import { Route as testFooRouteImport } from './routes/(test)/foo' +import { Route as testFooBarRouteImport } from './routes/(test)/foo.bar' + +const testBarLazyRouteImport = createFileRoute('/(test)/bar')() + +const testBarLazyRoute = testBarLazyRouteImport + .update({ + id: '/(test)/bar', + path: '/bar', + getParentRoute: () => rootRouteImport, + } as any) + .lazy(() => import('./routes/(test)/bar.lazy').then((d) => d.Route)) +const testInitiallyLazyRoute = testInitiallyLazyRouteImport.update({ + id: '/(test)/initiallyLazy', + path: '/initiallyLazy', + getParentRoute: () => rootRouteImport, +} as any) +const testInitiallyEmptyRoute = testInitiallyEmptyRouteImport + .update({ + id: '/(test)/initiallyEmpty', + path: '/initiallyEmpty', + getParentRoute: () => rootRouteImport, + } as any) + .lazy(() => + import('./routes/(test)/initiallyEmpty.lazy').then((d) => d.Route), + ) +const testFooRoute = testFooRouteImport.update({ + id: '/(test)/foo', + path: '/foo', + getParentRoute: () => rootRouteImport, +} as any) +const testFooBarRoute = testFooBarRouteImport.update({ + id: '/bar', + path: '/bar', + getParentRoute: () => testFooRoute, +} as any) + +export interface FileRoutesByFullPath { + '/foo': typeof testFooRouteWithChildren + '/initiallyEmpty': typeof testInitiallyEmptyRoute + '/initiallyLazy': typeof testInitiallyLazyRoute + '/bar': typeof testBarLazyRoute + '/foo/bar': typeof testFooBarRoute +} +export interface FileRoutesByTo { + '/foo': typeof testFooRouteWithChildren + '/initiallyEmpty': typeof testInitiallyEmptyRoute + '/initiallyLazy': typeof testInitiallyLazyRoute + '/bar': typeof testBarLazyRoute + '/foo/bar': typeof testFooBarRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/(test)/foo': typeof testFooRouteWithChildren + '/(test)/initiallyEmpty': typeof testInitiallyEmptyRoute + '/(test)/initiallyLazy': typeof testInitiallyLazyRoute + '/(test)/bar': typeof testBarLazyRoute + '/(test)/foo/bar': typeof testFooBarRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/foo' | '/initiallyEmpty' | '/initiallyLazy' | '/bar' | '/foo/bar' + fileRoutesByTo: FileRoutesByTo + to: '/foo' | '/initiallyEmpty' | '/initiallyLazy' | '/bar' | '/foo/bar' + id: + | '__root__' + | '/(test)/foo' + | '/(test)/initiallyEmpty' + | '/(test)/initiallyLazy' + | '/(test)/bar' + | '/(test)/foo/bar' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + testFooRoute: typeof testFooRouteWithChildren + testInitiallyEmptyRoute: typeof testInitiallyEmptyRoute + testInitiallyLazyRoute: typeof testInitiallyLazyRoute + testBarLazyRoute: typeof testBarLazyRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/(test)/bar': { + id: '/(test)/bar' + path: '/bar' + fullPath: '/bar' + preLoaderRoute: typeof testBarLazyRouteImport + parentRoute: typeof rootRouteImport + } + '/(test)/initiallyLazy': { + id: '/(test)/initiallyLazy' + path: '/initiallyLazy' + fullPath: '/initiallyLazy' + preLoaderRoute: typeof testInitiallyLazyRouteImport + parentRoute: typeof rootRouteImport + } + '/(test)/initiallyEmpty': { + id: '/(test)/initiallyEmpty' + path: '/initiallyEmpty' + fullPath: '/initiallyEmpty' + preLoaderRoute: typeof testInitiallyEmptyRouteImport + parentRoute: typeof rootRouteImport + } + '/(test)/foo': { + id: '/(test)/foo' + path: '/foo' + fullPath: '/foo' + preLoaderRoute: typeof testFooRouteImport + parentRoute: typeof rootRouteImport + } + '/(test)/foo/bar': { + id: '/(test)/foo/bar' + path: '/bar' + fullPath: '/foo/bar' + preLoaderRoute: typeof testFooBarRouteImport + parentRoute: typeof testFooRoute + } + } +} + +interface testFooRouteChildren { + testFooBarRoute: typeof testFooBarRoute +} + +const testFooRouteChildren: testFooRouteChildren = { + testFooBarRoute: testFooBarRoute, +} + +const testFooRouteWithChildren = + testFooRoute._addFileChildren(testFooRouteChildren) + +const rootRouteChildren: RootRouteChildren = { + testFooRoute: testFooRouteWithChildren, + testInitiallyEmptyRoute: testInitiallyEmptyRoute, + testInitiallyLazyRoute: testInitiallyLazyRoute, + testBarLazyRoute: testBarLazyRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes<FileRouteTypes>() diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/lowercase-function-declaration@notFoundComponent.tsx b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-true/routes/(test)/-keep-directory similarity index 100% rename from packages/router-plugin/tests/code-splitter/snapshots/react/1-default/lowercase-function-declaration@notFoundComponent.tsx rename to packages/router-generator/tests/generator/file-modification-verboseFileRoutes-true/routes/(test)/-keep-directory diff --git a/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-true/routes/.gitignore b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-true/routes/.gitignore new file mode 100644 index 0000000000..e0c201406d --- /dev/null +++ b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-true/routes/.gitignore @@ -0,0 +1 @@ +(test)/*.tsx \ No newline at end of file diff --git a/packages/router-generator/tests/generator/nested/routes/__root.tsx b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-true/routes/__root.tsx similarity index 100% rename from packages/router-generator/tests/generator/nested/routes/__root.tsx rename to packages/router-generator/tests/generator/file-modification-verboseFileRoutes-true/routes/__root.tsx diff --git a/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-true/snapshots/bar.lazy.tsx b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-true/snapshots/bar.lazy.tsx new file mode 100644 index 0000000000..11e597239d --- /dev/null +++ b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-true/snapshots/bar.lazy.tsx @@ -0,0 +1,43 @@ +// @ts-nocheck + +import * as React from 'react' +import { ErrorComponent, ErrorComponentProps, Link, createLazyFileRoute } from '@tanstack/react-router' + +export const Route = createLazyFileRoute('/(test)/bar')({ + loader: async ({ params: { postId } }) => ({ + postId, + title: 'title', + body: 'body', + id: 'id', + }), + errorComponent: PostErrorComponent as any, + notFoundComponent: () => { + return <p>Post not found</p> + }, + component: PostComponent, +}) + +export function PostErrorComponent({ error }: ErrorComponentProps) { + return <ErrorComponent error={error} /> +} + +function PostComponent() { + const post = Route.useLoaderData() + + return ( + <div className="space-y-2"> + <h4 className="text-xl font-bold underline">{post.title}</h4> + <div className="text-sm">{post.body}</div> + <Link + to="/posts/$postId/deep" + params={{ + postId: post.id, + }} + activeProps={{ className: 'text-black font-bold' }} + className="inline-block py-1 text-blue-800 hover:text-blue-600" + > + Deep View + </Link> + </div> + ) +} diff --git a/packages/router-generator/tests/generator/file-modification/snapshots/foo.bar.tsx b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-true/snapshots/foo.bar.tsx similarity index 100% rename from packages/router-generator/tests/generator/file-modification/snapshots/foo.bar.tsx rename to packages/router-generator/tests/generator/file-modification-verboseFileRoutes-true/snapshots/foo.bar.tsx diff --git a/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-true/snapshots/foo.tsx b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-true/snapshots/foo.tsx new file mode 100644 index 0000000000..f6d4c9b072 --- /dev/null +++ b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-true/snapshots/foo.tsx @@ -0,0 +1,43 @@ +// @ts-nocheck + +import * as React from 'react' +import { ErrorComponent, ErrorComponentProps, Link, createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/(test)/foo')({ + loader: async ({ params: { postId } }) => ({ + postId, + title: 'title', + body: 'body', + id: 'id', + }), + errorComponent: PostErrorComponent as any, + notFoundComponent: () => { + return <p>Post not found</p> + }, + component: PostComponent, +}) + +export function PostErrorComponent({ error }: ErrorComponentProps) { + return <ErrorComponent error={error} /> +} + +function PostComponent() { + const post = Route.useLoaderData() + + return ( + <div className="space-y-2"> + <h4 className="text-xl font-bold underline">{post.title}</h4> + <div className="text-sm">{post.body}</div> + <Link + to="/posts/$postId/deep" + params={{ + postId: post.id, + }} + activeProps={{ className: 'text-black font-bold' }} + className="inline-block py-1 text-blue-800 hover:text-blue-600" + > + Deep View + </Link> + </div> + ) +} diff --git a/packages/router-generator/tests/generator/file-modification/snapshots/initiallyEmpty.lazy.tsx b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-true/snapshots/initiallyEmpty.lazy.tsx similarity index 100% rename from packages/router-generator/tests/generator/file-modification/snapshots/initiallyEmpty.lazy.tsx rename to packages/router-generator/tests/generator/file-modification-verboseFileRoutes-true/snapshots/initiallyEmpty.lazy.tsx diff --git a/packages/router-generator/tests/generator/file-modification/snapshots/initiallyEmpty.tsx b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-true/snapshots/initiallyEmpty.tsx similarity index 100% rename from packages/router-generator/tests/generator/file-modification/snapshots/initiallyEmpty.tsx rename to packages/router-generator/tests/generator/file-modification-verboseFileRoutes-true/snapshots/initiallyEmpty.tsx diff --git a/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-true/snapshots/initiallyLazy.tsx b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-true/snapshots/initiallyLazy.tsx new file mode 100644 index 0000000000..258a8f7619 --- /dev/null +++ b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-true/snapshots/initiallyLazy.tsx @@ -0,0 +1,26 @@ +// @ts-nocheck + +import { Link, createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/(test)/initiallyLazy')({ + component: () => { + const post = Route.useLoaderData() + + return ( + <div className="space-y-2"> + <h4 className="text-xl font-bold underline">{post.title}</h4> + <div className="text-sm">{post.body}</div> + <Link + to="/posts/$postId/deep" + params={{ + postId: post.id, + }} + activeProps={{ className: 'text-black font-bold' }} + className="block py-1 text-blue-800 hover:text-blue-600" + > + Deep View + </Link> + </div> + ) + }, +}) diff --git a/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-true/template-verbose.tsx b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-true/template-verbose.tsx new file mode 100644 index 0000000000..9756170d6e --- /dev/null +++ b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-true/template-verbose.tsx @@ -0,0 +1,47 @@ +// @ts-nocheck + +import * as React from 'react' +import { + ErrorComponent, + ErrorComponentProps, + Link, +} from '@tanstack/react-router' + +export const Route = createFileRoute('/foo/bar')({ + loader: async ({ params: { postId } }) => ({ + postId, + title: 'title', + body: 'body', + id: 'id', + }), + errorComponent: PostErrorComponent as any, + notFoundComponent: () => { + return <p>Post not found</p> + }, + component: PostComponent, +}) + +export function PostErrorComponent({ error }: ErrorComponentProps) { + return <ErrorComponent error={error} /> +} + +function PostComponent() { + const post = Route.useLoaderData() + + return ( + <div className="space-y-2"> + <h4 className="text-xl font-bold underline">{post.title}</h4> + <div className="text-sm">{post.body}</div> + <Link + to="/posts/$postId/deep" + params={{ + postId: post.id, + }} + activeProps={{ className: 'text-black font-bold' }} + className="inline-block py-1 text-blue-800 hover:text-blue-600" + > + Deep View + </Link> + </div> + ) +} diff --git a/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-true/template.lazy.tsx b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-true/template.lazy.tsx new file mode 100644 index 0000000000..45a3d5871f --- /dev/null +++ b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-true/template.lazy.tsx @@ -0,0 +1,26 @@ +// @ts-nocheck + +import { createLazyFileRoute, Link } from '@tanstack/react-router' + +export const Route = createLazyFileRoute({ + component: () => { + const post = Route.useLoaderData() + + return ( + <div className="space-y-2"> + <h4 className="text-xl font-bold underline">{post.title}</h4> + <div className="text-sm">{post.body}</div> + <Link + to="/posts/$postId/deep" + params={{ + postId: post.id, + }} + activeProps={{ className: 'text-black font-bold' }} + className="block py-1 text-blue-800 hover:text-blue-600" + > + Deep View + </Link> + </div> + ) + }, +}) diff --git a/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-true/template.tsx b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-true/template.tsx new file mode 100644 index 0000000000..cf174606e1 --- /dev/null +++ b/packages/router-generator/tests/generator/file-modification-verboseFileRoutes-true/template.tsx @@ -0,0 +1,47 @@ +// @ts-nocheck + +import * as React from 'react' +import { + ErrorComponent, + ErrorComponentProps, + Link, +} from '@tanstack/react-router' + +export const Route = createFileRoute({ + loader: async ({ params: { postId } }) => ({ + postId, + title: 'title', + body: 'body', + id: 'id', + }), + errorComponent: PostErrorComponent as any, + notFoundComponent: () => { + return <p>Post not found</p> + }, + component: PostComponent, +}) + +export function PostErrorComponent({ error }: ErrorComponentProps) { + return <ErrorComponent error={error} /> +} + +function PostComponent() { + const post = Route.useLoaderData() + + return ( + <div className="space-y-2"> + <h4 className="text-xl font-bold underline">{post.title}</h4> + <div className="text-sm">{post.body}</div> + <Link + to="/posts/$postId/deep" + params={{ + postId: post.id, + }} + activeProps={{ className: 'text-black font-bold' }} + className="inline-block py-1 text-blue-800 hover:text-blue-600" + > + Deep View + </Link> + </div> + ) +} diff --git a/packages/router-generator/tests/generator/file-modification/routeTree.snapshot.ts b/packages/router-generator/tests/generator/file-modification/routeTree.snapshot.ts deleted file mode 100644 index 7ec8640782..0000000000 --- a/packages/router-generator/tests/generator/file-modification/routeTree.snapshot.ts +++ /dev/null @@ -1,228 +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 { createFileRoute } from '@tanstack/react-router' - -import { Route as rootRouteImport } from './routes/__root' -import { Route as testDoubleQuotesRouteImport } from './routes/(test)/double-quotes' -import { Route as testDuplicateImportRouteImport } from './routes/(test)/duplicate-import' -import { Route as testFooRouteImport } from './routes/(test)/foo' -import { Route as testInitiallyEmptyRouteImport } from './routes/(test)/initiallyEmpty' -import { Route as testInitiallyLazyRouteImport } from './routes/(test)/initiallyLazy' -import { Route as testTemplateLiteralRouteImport } from './routes/(test)/template-literal' -import { Route as testFooBarRouteImport } from './routes/(test)/foo.bar' - -const testBarLazyRouteImport = createFileRoute('/(test)/bar')() - -const testBarLazyRoute = testBarLazyRouteImport - .update({ - id: '/(test)/bar', - path: '/bar', - getParentRoute: () => rootRouteImport, - } as any) - .lazy(() => import('./routes/(test)/bar.lazy').then((d) => d.Route)) -const testDoubleQuotesRoute = testDoubleQuotesRouteImport.update({ - id: '/(test)/double-quotes', - path: '/double-quotes', - getParentRoute: () => rootRouteImport, -} as any) -const testDuplicateImportRoute = testDuplicateImportRouteImport.update({ - id: '/(test)/duplicate-import', - path: '/duplicate-import', - getParentRoute: () => rootRouteImport, -} as any) -const testFooRoute = testFooRouteImport.update({ - id: '/(test)/foo', - path: '/foo', - getParentRoute: () => rootRouteImport, -} as any) -const testInitiallyEmptyRoute = testInitiallyEmptyRouteImport - .update({ - id: '/(test)/initiallyEmpty', - path: '/initiallyEmpty', - getParentRoute: () => rootRouteImport, - } as any) - .lazy(() => - import('./routes/(test)/initiallyEmpty.lazy').then((d) => d.Route), - ) -const testInitiallyLazyRoute = testInitiallyLazyRouteImport.update({ - id: '/(test)/initiallyLazy', - path: '/initiallyLazy', - getParentRoute: () => rootRouteImport, -} as any) -const testTemplateLiteralRoute = testTemplateLiteralRouteImport.update({ - id: '/(test)/template-literal', - path: '/template-literal', - getParentRoute: () => rootRouteImport, -} as any) -const testFooBarRoute = testFooBarRouteImport.update({ - id: '/bar', - path: '/bar', - getParentRoute: () => testFooRoute, -} as any) - -export interface FileRoutesByFullPath { - '/double-quotes': typeof testDoubleQuotesRoute - '/duplicate-import': typeof testDuplicateImportRoute - '/foo': typeof testFooRouteWithChildren - '/initiallyEmpty': typeof testInitiallyEmptyRoute - '/initiallyLazy': typeof testInitiallyLazyRoute - '/template-literal': typeof testTemplateLiteralRoute - '/bar': typeof testBarLazyRoute - '/foo/bar': typeof testFooBarRoute -} -export interface FileRoutesByTo { - '/double-quotes': typeof testDoubleQuotesRoute - '/duplicate-import': typeof testDuplicateImportRoute - '/foo': typeof testFooRouteWithChildren - '/initiallyEmpty': typeof testInitiallyEmptyRoute - '/initiallyLazy': typeof testInitiallyLazyRoute - '/template-literal': typeof testTemplateLiteralRoute - '/bar': typeof testBarLazyRoute - '/foo/bar': typeof testFooBarRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/(test)/double-quotes': typeof testDoubleQuotesRoute - '/(test)/duplicate-import': typeof testDuplicateImportRoute - '/(test)/foo': typeof testFooRouteWithChildren - '/(test)/initiallyEmpty': typeof testInitiallyEmptyRoute - '/(test)/initiallyLazy': typeof testInitiallyLazyRoute - '/(test)/template-literal': typeof testTemplateLiteralRoute - '/(test)/bar': typeof testBarLazyRoute - '/(test)/foo/bar': typeof testFooBarRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/double-quotes' - | '/duplicate-import' - | '/foo' - | '/initiallyEmpty' - | '/initiallyLazy' - | '/template-literal' - | '/bar' - | '/foo/bar' - fileRoutesByTo: FileRoutesByTo - to: - | '/double-quotes' - | '/duplicate-import' - | '/foo' - | '/initiallyEmpty' - | '/initiallyLazy' - | '/template-literal' - | '/bar' - | '/foo/bar' - id: - | '__root__' - | '/(test)/double-quotes' - | '/(test)/duplicate-import' - | '/(test)/foo' - | '/(test)/initiallyEmpty' - | '/(test)/initiallyLazy' - | '/(test)/template-literal' - | '/(test)/bar' - | '/(test)/foo/bar' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - testDoubleQuotesRoute: typeof testDoubleQuotesRoute - testDuplicateImportRoute: typeof testDuplicateImportRoute - testFooRoute: typeof testFooRouteWithChildren - testInitiallyEmptyRoute: typeof testInitiallyEmptyRoute - testInitiallyLazyRoute: typeof testInitiallyLazyRoute - testTemplateLiteralRoute: typeof testTemplateLiteralRoute - testBarLazyRoute: typeof testBarLazyRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/(test)/bar': { - id: '/(test)/bar' - path: '/bar' - fullPath: '/bar' - preLoaderRoute: typeof testBarLazyRouteImport - parentRoute: typeof rootRouteImport - } - '/(test)/double-quotes': { - id: '/(test)/double-quotes' - path: '/double-quotes' - fullPath: '/double-quotes' - preLoaderRoute: typeof testDoubleQuotesRouteImport - parentRoute: typeof rootRouteImport - } - '/(test)/duplicate-import': { - id: '/(test)/duplicate-import' - path: '/duplicate-import' - fullPath: '/duplicate-import' - preLoaderRoute: typeof testDuplicateImportRouteImport - parentRoute: typeof rootRouteImport - } - '/(test)/foo': { - id: '/(test)/foo' - path: '/foo' - fullPath: '/foo' - preLoaderRoute: typeof testFooRouteImport - parentRoute: typeof rootRouteImport - } - '/(test)/initiallyEmpty': { - id: '/(test)/initiallyEmpty' - path: '/initiallyEmpty' - fullPath: '/initiallyEmpty' - preLoaderRoute: typeof testInitiallyEmptyRouteImport - parentRoute: typeof rootRouteImport - } - '/(test)/initiallyLazy': { - id: '/(test)/initiallyLazy' - path: '/initiallyLazy' - fullPath: '/initiallyLazy' - preLoaderRoute: typeof testInitiallyLazyRouteImport - parentRoute: typeof rootRouteImport - } - '/(test)/template-literal': { - id: '/(test)/template-literal' - path: '/template-literal' - fullPath: '/template-literal' - preLoaderRoute: typeof testTemplateLiteralRouteImport - parentRoute: typeof rootRouteImport - } - '/(test)/foo/bar': { - id: '/(test)/foo/bar' - path: '/bar' - fullPath: '/foo/bar' - preLoaderRoute: typeof testFooBarRouteImport - parentRoute: typeof testFooRoute - } - } -} - -interface testFooRouteChildren { - testFooBarRoute: typeof testFooBarRoute -} - -const testFooRouteChildren: testFooRouteChildren = { - testFooBarRoute: testFooBarRoute, -} - -const testFooRouteWithChildren = - testFooRoute._addFileChildren(testFooRouteChildren) - -const rootRouteChildren: RootRouteChildren = { - testDoubleQuotesRoute: testDoubleQuotesRoute, - testDuplicateImportRoute: testDuplicateImportRoute, - testFooRoute: testFooRouteWithChildren, - testInitiallyEmptyRoute: testInitiallyEmptyRoute, - testInitiallyLazyRoute: testInitiallyLazyRoute, - testTemplateLiteralRoute: testTemplateLiteralRoute, - testBarLazyRoute: testBarLazyRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes<FileRouteTypes>() diff --git a/packages/router-generator/tests/generator/file-modification/routes/.gitignore b/packages/router-generator/tests/generator/file-modification/routes/.gitignore deleted file mode 100644 index a7828561f2..0000000000 --- a/packages/router-generator/tests/generator/file-modification/routes/.gitignore +++ /dev/null @@ -1 +0,0 @@ -(test)/*.tsx diff --git a/packages/router-generator/tests/generator/file-modification/snapshots/bar.lazy.tsx b/packages/router-generator/tests/generator/file-modification/snapshots/bar.lazy.tsx deleted file mode 100644 index 24db5929dd..0000000000 --- a/packages/router-generator/tests/generator/file-modification/snapshots/bar.lazy.tsx +++ /dev/null @@ -1,48 +0,0 @@ -// @ts-nocheck - -import * as React from 'react' -import { - ErrorComponent, - ErrorComponentProps, - Link, - createLazyFileRoute, -} from '@tanstack/react-router' - -export const Route = createLazyFileRoute('/(test)/bar')({ - loader: async ({ params: { postId } }) => ({ - postId, - title: 'title', - body: 'body', - id: 'id', - }), - errorComponent: PostErrorComponent as any, - notFoundComponent: () => { - return <p>Post not found</p> - }, - component: PostComponent, -}) - -export function PostErrorComponent({ error }: ErrorComponentProps) { - return <ErrorComponent error={error} /> -} - -function PostComponent() { - const post = Route.useLoaderData() - - return ( - <div className="space-y-2"> - <h4 className="text-xl font-bold underline">{post.title}</h4> - <div className="text-sm">{post.body}</div> - <Link - to="/posts/$postId/deep" - params={{ - postId: post.id, - }} - activeProps={{ className: 'text-black font-bold' }} - className="inline-block py-1 text-blue-800 hover:text-blue-600" - > - Deep View - </Link> - </div> - ) -} diff --git a/packages/router-generator/tests/generator/file-modification/snapshots/double-quotes.tsx b/packages/router-generator/tests/generator/file-modification/snapshots/double-quotes.tsx deleted file mode 100644 index d03bf88405..0000000000 --- a/packages/router-generator/tests/generator/file-modification/snapshots/double-quotes.tsx +++ /dev/null @@ -1,48 +0,0 @@ -// @ts-nocheck - -import * as React from 'react' -import { - ErrorComponent, - ErrorComponentProps, - Link, - createFileRoute, -} from '@tanstack/react-router' - -export const Route = createFileRoute("/(test)/double-quotes")({ - loader: async ({ params: { postId } }) => ({ - postId, - title: 'title', - body: 'body', - id: 'id', - }), - errorComponent: PostErrorComponent as any, - notFoundComponent: () => { - return <p>Post not found</p> - }, - component: PostComponent, -}) - -export function PostErrorComponent({ error }: ErrorComponentProps) { - return <ErrorComponent error={error} /> -} - -function PostComponent() { - const post = Route.useLoaderData() - - return ( - <div className="space-y-2"> - <h4 className="text-xl font-bold underline">{post.title}</h4> - <div className="text-sm">{post.body}</div> - <Link - to="/posts/$postId/deep" - params={{ - postId: post.id, - }} - activeProps={{ className: 'text-black font-bold' }} - className="inline-block py-1 text-blue-800 hover:text-blue-600" - > - Deep View - </Link> - </div> - ) -} diff --git a/packages/router-generator/tests/generator/file-modification/snapshots/duplicate-import.tsx b/packages/router-generator/tests/generator/file-modification/snapshots/duplicate-import.tsx deleted file mode 100644 index 6a668f371f..0000000000 --- a/packages/router-generator/tests/generator/file-modification/snapshots/duplicate-import.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import * as React from 'react' -import { Link, Outlet } from '@tanstack/react-router' - -export const Route = createFileRoute('/(test)/duplicate-import')({ - component: PostsLayoutComponent, -}) - -function PostsLayoutComponent() { - return ( - <> - <Link to="/">Home</Link> - <Outlet /> - </> - ) -} diff --git a/packages/router-generator/tests/generator/file-modification/snapshots/foo.tsx b/packages/router-generator/tests/generator/file-modification/snapshots/foo.tsx deleted file mode 100644 index 400df7e122..0000000000 --- a/packages/router-generator/tests/generator/file-modification/snapshots/foo.tsx +++ /dev/null @@ -1,48 +0,0 @@ -// @ts-nocheck - -import * as React from 'react' -import { - ErrorComponent, - ErrorComponentProps, - Link, - createFileRoute, -} from '@tanstack/react-router' - -export const Route = createFileRoute('/(test)/foo')({ - loader: async ({ params: { postId } }) => ({ - postId, - title: 'title', - body: 'body', - id: 'id', - }), - errorComponent: PostErrorComponent as any, - notFoundComponent: () => { - return <p>Post not found</p> - }, - component: PostComponent, -}) - -export function PostErrorComponent({ error }: ErrorComponentProps) { - return <ErrorComponent error={error} /> -} - -function PostComponent() { - const post = Route.useLoaderData() - - return ( - <div className="space-y-2"> - <h4 className="text-xl font-bold underline">{post.title}</h4> - <div className="text-sm">{post.body}</div> - <Link - to="/posts/$postId/deep" - params={{ - postId: post.id, - }} - activeProps={{ className: 'text-black font-bold' }} - className="inline-block py-1 text-blue-800 hover:text-blue-600" - > - Deep View - </Link> - </div> - ) -} diff --git a/packages/router-generator/tests/generator/file-modification/snapshots/initiallyLazy.tsx b/packages/router-generator/tests/generator/file-modification/snapshots/initiallyLazy.tsx deleted file mode 100644 index b9d388acd0..0000000000 --- a/packages/router-generator/tests/generator/file-modification/snapshots/initiallyLazy.tsx +++ /dev/null @@ -1,26 +0,0 @@ -// @ts-nocheck - -import { createFileRoute, Link } from '@tanstack/react-router' - -export const Route = createFileRoute('/(test)/initiallyLazy')({ - component: () => { - const post = Route.useLoaderData() - - return ( - <div className="space-y-2"> - <h4 className="text-xl font-bold underline">{post.title}</h4> - <div className="text-sm">{post.body}</div> - <Link - to="/posts/$postId/deep" - params={{ - postId: post.id, - }} - activeProps={{ className: 'text-black font-bold' }} - className="block py-1 text-blue-800 hover:text-blue-600" - > - Deep View - </Link> - </div> - ) - }, -}) diff --git a/packages/router-generator/tests/generator/file-modification/snapshots/template-literal.tsx b/packages/router-generator/tests/generator/file-modification/snapshots/template-literal.tsx deleted file mode 100644 index 1e31639331..0000000000 --- a/packages/router-generator/tests/generator/file-modification/snapshots/template-literal.tsx +++ /dev/null @@ -1,48 +0,0 @@ -// @ts-nocheck - -import * as React from 'react' -import { - ErrorComponent, - ErrorComponentProps, - Link, - createFileRoute, -} from '@tanstack/react-router' - -export const Route = createFileRoute(`/(test)/template-literal`)({ - loader: async ({ params: { postId } }) => ({ - postId, - title: 'title', - body: 'body', - id: 'id', - }), - errorComponent: PostErrorComponent as any, - notFoundComponent: () => { - return <p>Post not found</p> - }, - component: PostComponent, -}) - -export function PostErrorComponent({ error }: ErrorComponentProps) { - return <ErrorComponent error={error} /> -} - -function PostComponent() { - const post = Route.useLoaderData() - - return ( - <div className="space-y-2"> - <h4 className="text-xl font-bold underline">{post.title}</h4> - <div className="text-sm">{post.body}</div> - <Link - to="/posts/$postId/deep" - params={{ - postId: post.id, - }} - activeProps={{ className: 'text-black font-bold' }} - className="inline-block py-1 text-blue-800 hover:text-blue-600" - > - Deep View - </Link> - </div> - ) -} diff --git a/packages/router-generator/tests/generator/file-modification/template.lazy.tsx b/packages/router-generator/tests/generator/file-modification/template.lazy.tsx deleted file mode 100644 index 99604a5ccb..0000000000 --- a/packages/router-generator/tests/generator/file-modification/template.lazy.tsx +++ /dev/null @@ -1,26 +0,0 @@ -// @ts-nocheck - -import { createLazyFileRoute, Link } from '@tanstack/react-router' - -export const Route = createLazyFileRoute('/foo/bar')({ - component: () => { - const post = Route.useLoaderData() - - return ( - <div className="space-y-2"> - <h4 className="text-xl font-bold underline">{post.title}</h4> - <div className="text-sm">{post.body}</div> - <Link - to="/posts/$postId/deep" - params={{ - postId: post.id, - }} - activeProps={{ className: 'text-black font-bold' }} - className="block py-1 text-blue-800 hover:text-blue-600" - > - Deep View - </Link> - </div> - ) - }, -}) diff --git a/packages/router-generator/tests/generator/file-modification/template.tsx b/packages/router-generator/tests/generator/file-modification/template.tsx deleted file mode 100644 index 1598aa3c9f..0000000000 --- a/packages/router-generator/tests/generator/file-modification/template.tsx +++ /dev/null @@ -1,48 +0,0 @@ -// @ts-nocheck - -import * as React from 'react' -import { - ErrorComponent, - ErrorComponentProps, - Link, - createFileRoute, -} from '@tanstack/react-router' - -export const Route = createFileRoute('/foo/bar')({ - loader: async ({ params: { postId } }) => ({ - postId, - title: 'title', - body: 'body', - id: 'id', - }), - errorComponent: PostErrorComponent as any, - notFoundComponent: () => { - return <p>Post not found</p> - }, - component: PostComponent, -}) - -export function PostErrorComponent({ error }: ErrorComponentProps) { - return <ErrorComponent error={error} /> -} - -function PostComponent() { - const post = Route.useLoaderData() - - return ( - <div className="space-y-2"> - <h4 className="text-xl font-bold underline">{post.title}</h4> - <div className="text-sm">{post.body}</div> - <Link - to="/posts/$postId/deep" - params={{ - postId: post.id, - }} - activeProps={{ className: 'text-black font-bold' }} - className="inline-block py-1 text-blue-800 hover:text-blue-600" - > - Deep View - </Link> - </div> - ) -} diff --git a/packages/router-generator/tests/generator/flat-route-group/routeTree.snapshot.ts b/packages/router-generator/tests/generator/flat-route-group/routeTree.snapshot.ts index 542a64a174..7f7990e787 100644 --- a/packages/router-generator/tests/generator/flat-route-group/routeTree.snapshot.ts +++ b/packages/router-generator/tests/generator/flat-route-group/routeTree.snapshot.ts @@ -10,8 +10,8 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as AppRouteImport } from './routes/app' -import { Route as AppcomprasCompras_masRouteImport } from './routes/app.(compras)/compras_._mas' import { Route as AppcomprasComprasOrdenesRouteImport } from './routes/app.(compras)/compras_.ordenes' +import { Route as AppcomprasCompras_masRouteImport } from './routes/app.(compras)/compras_._mas' import { Route as AppcomprasCompras_masDivisionesRouteImport } from './routes/app.(compras)/compras_._mas.divisiones' const AppRoute = AppRouteImport.update({ @@ -19,17 +19,17 @@ const AppRoute = AppRouteImport.update({ path: '/app', getParentRoute: () => rootRouteImport, } as any) -const AppcomprasCompras_masRoute = AppcomprasCompras_masRouteImport.update({ - id: '/(compras)/compras_/_mas', - path: '/compras', - getParentRoute: () => AppRoute, -} as any) const AppcomprasComprasOrdenesRoute = AppcomprasComprasOrdenesRouteImport.update({ id: '/(compras)/compras_/ordenes', path: '/compras/ordenes', getParentRoute: () => AppRoute, } as any) +const AppcomprasCompras_masRoute = AppcomprasCompras_masRouteImport.update({ + id: '/(compras)/compras_/_mas', + path: '/compras', + getParentRoute: () => AppRoute, +} as any) const AppcomprasCompras_masDivisionesRoute = AppcomprasCompras_masDivisionesRouteImport.update({ id: '/divisiones', @@ -59,10 +59,16 @@ export interface FileRoutesById { export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath fullPaths: - '/app' | '/app/compras' | '/app/compras/ordenes' | '/app/compras/divisiones' + | '/app' + | '/app/compras' + | '/app/compras/ordenes' + | '/app/compras/divisiones' fileRoutesByTo: FileRoutesByTo to: - '/app' | '/app/compras' | '/app/compras/ordenes' | '/app/compras/divisiones' + | '/app' + | '/app/compras' + | '/app/compras/ordenes' + | '/app/compras/divisiones' id: | '__root__' | '/app' @@ -84,13 +90,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AppRouteImport parentRoute: typeof rootRouteImport } - '/app/(compras)/compras_/_mas': { - id: '/app/(compras)/compras_/_mas' - path: '/compras' - fullPath: '/app/compras' - preLoaderRoute: typeof AppcomprasCompras_masRouteImport - parentRoute: typeof AppRoute - } '/app/(compras)/compras_/ordenes': { id: '/app/(compras)/compras_/ordenes' path: '/compras/ordenes' @@ -98,6 +97,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AppcomprasComprasOrdenesRouteImport parentRoute: typeof AppRoute } + '/app/(compras)/compras_/_mas': { + id: '/app/(compras)/compras_/_mas' + path: '/compras' + fullPath: '/app/compras' + preLoaderRoute: typeof AppcomprasCompras_masRouteImport + parentRoute: typeof AppRoute + } '/app/(compras)/compras_/_mas/divisiones': { id: '/app/(compras)/compras_/_mas/divisiones' path: '/divisiones' diff --git a/packages/router-generator/tests/generator/flat/routeTree.snapshot.ts b/packages/router-generator/tests/generator/flat/routeTree.snapshot.ts index 923cfc0530..b1bf6587fc 100644 --- a/packages/router-generator/tests/generator/flat/routeTree.snapshot.ts +++ b/packages/router-generator/tests/generator/flat/routeTree.snapshot.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 IndexRouteImport } from './routes/index' -import { Route as BlogRouteRouteImport } from './routes/blog.route' import { Route as PostsRouteRouteImport } from './routes/posts.route' -import { Route as BlogIndexRouteImport } from './routes/blog.index' -import { Route as BlogBlogIdRouteRouteImport } from './routes/blog_.$blogId.route' -import { Route as BlogStatsRouteImport } from './routes/blog_.stats' +import { Route as BlogRouteRouteImport } from './routes/blog.route' +import { Route as IndexRouteImport } from './routes/index' import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as BlogSlugIndexRouteImport } from './routes/blog.$slug.index' -import { Route as BlogBlogIdSlugRouteRouteImport } from './routes/blog_.$blogId.$slug.route' -import { Route as BlogBlogIdEditRouteImport } from './routes/blog_.$blogId_.edit' +import { Route as BlogIndexRouteImport } from './routes/blog.index' +import { Route as BlogStatsRouteImport } from './routes/blog_.stats' +import { Route as BlogBlogIdRouteRouteImport } from './routes/blog_.$blogId.route' import { Route as PostsPostIdIndexRouteImport } from './routes/posts.$postId.index' +import { Route as BlogSlugIndexRouteImport } from './routes/blog.$slug.index' import { Route as PostsPostIdDeepRouteImport } from './routes/posts.$postId.deep' +import { Route as BlogBlogIdEditRouteImport } from './routes/blog_.$blogId_.edit' +import { Route as BlogBlogIdSlugRouteRouteImport } from './routes/blog_.$blogId.$slug.route' import { Route as BlogBlogIdSlugBarRouteImport } from './routes/blog_.$blogId.$slug_.bar' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const PostsRouteRoute = PostsRouteRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) const BlogRouteRoute = BlogRouteRouteImport.update({ @@ -33,24 +33,9 @@ const BlogRouteRoute = BlogRouteRouteImport.update({ path: '/blog', getParentRoute: () => rootRouteImport, } as any) -const PostsRouteRoute = PostsRouteRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) -const BlogIndexRoute = BlogIndexRouteImport.update({ +const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', - getParentRoute: () => BlogRouteRoute, -} as any) -const BlogBlogIdRouteRoute = BlogBlogIdRouteRouteImport.update({ - id: '/blog_/$blogId', - path: '/blog/$blogId', - getParentRoute: () => rootRouteImport, -} as any) -const BlogStatsRoute = BlogStatsRouteImport.update({ - id: '/blog_/stats', - path: '/blog/stats', getParentRoute: () => rootRouteImport, } as any) const PostsIndexRoute = PostsIndexRouteImport.update({ @@ -58,19 +43,19 @@ const PostsIndexRoute = PostsIndexRouteImport.update({ path: '/', getParentRoute: () => PostsRouteRoute, } as any) -const BlogSlugIndexRoute = BlogSlugIndexRouteImport.update({ - id: '/$slug/', - path: '/$slug/', +const BlogIndexRoute = BlogIndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => BlogRouteRoute, } as any) -const BlogBlogIdSlugRouteRoute = BlogBlogIdSlugRouteRouteImport.update({ - id: '/$slug', - path: '/$slug', - getParentRoute: () => BlogBlogIdRouteRoute, +const BlogStatsRoute = BlogStatsRouteImport.update({ + id: '/blog_/stats', + path: '/blog/stats', + getParentRoute: () => rootRouteImport, } as any) -const BlogBlogIdEditRoute = BlogBlogIdEditRouteImport.update({ - id: '/blog_/$blogId_/edit', - path: '/blog/$blogId/edit', +const BlogBlogIdRouteRoute = BlogBlogIdRouteRouteImport.update({ + id: '/blog_/$blogId', + path: '/blog/$blogId', getParentRoute: () => rootRouteImport, } as any) const PostsPostIdIndexRoute = PostsPostIdIndexRouteImport.update({ @@ -78,11 +63,26 @@ const PostsPostIdIndexRoute = PostsPostIdIndexRouteImport.update({ path: '/$postId/', getParentRoute: () => PostsRouteRoute, } as any) +const BlogSlugIndexRoute = BlogSlugIndexRouteImport.update({ + id: '/$slug/', + path: '/$slug/', + getParentRoute: () => BlogRouteRoute, +} as any) const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ id: '/$postId/deep', path: '/$postId/deep', getParentRoute: () => PostsRouteRoute, } as any) +const BlogBlogIdEditRoute = BlogBlogIdEditRouteImport.update({ + id: '/blog_/$blogId_/edit', + path: '/blog/$blogId/edit', + getParentRoute: () => rootRouteImport, +} as any) +const BlogBlogIdSlugRouteRoute = BlogBlogIdSlugRouteRouteImport.update({ + id: '/$slug', + path: '/$slug', + getParentRoute: () => BlogBlogIdRouteRoute, +} as any) const BlogBlogIdSlugBarRoute = BlogBlogIdSlugBarRouteImport.update({ id: '/$slug_/bar', path: '/$slug/bar', @@ -190,11 +190,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } '/blog': { @@ -204,32 +204,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof BlogRouteRouteImport parentRoute: typeof rootRouteImport } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteRouteImport - parentRoute: typeof rootRouteImport - } - '/blog/': { - id: '/blog/' + '/': { + id: '/' path: '/' - fullPath: '/blog/' - preLoaderRoute: typeof BlogIndexRouteImport - parentRoute: typeof BlogRouteRoute - } - '/blog_/$blogId': { - id: '/blog_/$blogId' - path: '/blog/$blogId' - fullPath: '/blog/$blogId' - preLoaderRoute: typeof BlogBlogIdRouteRouteImport - parentRoute: typeof rootRouteImport - } - '/blog_/stats': { - id: '/blog_/stats' - path: '/blog/stats' - fullPath: '/blog/stats' - preLoaderRoute: typeof BlogStatsRouteImport + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/posts/': { @@ -239,25 +218,25 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsIndexRouteImport parentRoute: typeof PostsRouteRoute } - '/blog/$slug/': { - id: '/blog/$slug/' - path: '/$slug' - fullPath: '/blog/$slug/' - preLoaderRoute: typeof BlogSlugIndexRouteImport + '/blog/': { + id: '/blog/' + path: '/' + fullPath: '/blog/' + preLoaderRoute: typeof BlogIndexRouteImport parentRoute: typeof BlogRouteRoute } - '/blog_/$blogId/$slug': { - id: '/blog_/$blogId/$slug' - path: '/$slug' - fullPath: '/blog/$blogId/$slug' - preLoaderRoute: typeof BlogBlogIdSlugRouteRouteImport - parentRoute: typeof BlogBlogIdRouteRoute + '/blog_/stats': { + id: '/blog_/stats' + path: '/blog/stats' + fullPath: '/blog/stats' + preLoaderRoute: typeof BlogStatsRouteImport + parentRoute: typeof rootRouteImport } - '/blog_/$blogId_/edit': { - id: '/blog_/$blogId_/edit' - path: '/blog/$blogId/edit' - fullPath: '/blog/$blogId/edit' - preLoaderRoute: typeof BlogBlogIdEditRouteImport + '/blog_/$blogId': { + id: '/blog_/$blogId' + path: '/blog/$blogId' + fullPath: '/blog/$blogId' + preLoaderRoute: typeof BlogBlogIdRouteRouteImport parentRoute: typeof rootRouteImport } '/posts/$postId/': { @@ -267,6 +246,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsPostIdIndexRouteImport parentRoute: typeof PostsRouteRoute } + '/blog/$slug/': { + id: '/blog/$slug/' + path: '/$slug' + fullPath: '/blog/$slug/' + preLoaderRoute: typeof BlogSlugIndexRouteImport + parentRoute: typeof BlogRouteRoute + } '/posts/$postId/deep': { id: '/posts/$postId/deep' path: '/$postId/deep' @@ -274,6 +260,20 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsPostIdDeepRouteImport parentRoute: typeof PostsRouteRoute } + '/blog_/$blogId_/edit': { + id: '/blog_/$blogId_/edit' + path: '/blog/$blogId/edit' + fullPath: '/blog/$blogId/edit' + preLoaderRoute: typeof BlogBlogIdEditRouteImport + parentRoute: typeof rootRouteImport + } + '/blog_/$blogId/$slug': { + id: '/blog_/$blogId/$slug' + path: '/$slug' + fullPath: '/blog/$blogId/$slug' + preLoaderRoute: typeof BlogBlogIdSlugRouteRouteImport + parentRoute: typeof BlogBlogIdRouteRoute + } '/blog_/$blogId/$slug_/bar': { id: '/blog_/$blogId/$slug_/bar' path: '/$slug/bar' diff --git a/packages/router-generator/tests/generator/invalid-param-names/routeTree.snapshot.ts b/packages/router-generator/tests/generator/invalid-param-names/routeTree.snapshot.ts index 9048976e40..4728dd439e 100644 --- a/packages/router-generator/tests/generator/invalid-param-names/routeTree.snapshot.ts +++ b/packages/router-generator/tests/generator/invalid-param-names/routeTree.snapshot.ts @@ -9,13 +9,13 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as R123RouteImport } from './routes/$123' -import { Route as UserNameRouteImport } from './routes/$user-name' import { Route as ValidParamRouteImport } from './routes/$validParam' +import { Route as UserNameRouteImport } from './routes/$user-name' +import { Route as R123RouteImport } from './routes/$123' -const R123Route = R123RouteImport.update({ - id: '/$123', - path: '/$123', +const ValidParamRoute = ValidParamRouteImport.update({ + id: '/$validParam', + path: '/$validParam', getParentRoute: () => rootRouteImport, } as any) const UserNameRoute = UserNameRouteImport.update({ @@ -23,9 +23,9 @@ const UserNameRoute = UserNameRouteImport.update({ path: '/$user-name', getParentRoute: () => rootRouteImport, } as any) -const ValidParamRoute = ValidParamRouteImport.update({ - id: '/$validParam', - path: '/$validParam', +const R123Route = R123RouteImport.update({ + id: '/$123', + path: '/$123', getParentRoute: () => rootRouteImport, } as any) @@ -61,11 +61,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/$123': { - id: '/$123' - path: '/$123' - fullPath: '/$123' - preLoaderRoute: typeof R123RouteImport + '/$validParam': { + id: '/$validParam' + path: '/$validParam' + fullPath: '/$validParam' + preLoaderRoute: typeof ValidParamRouteImport parentRoute: typeof rootRouteImport } '/$user-name': { @@ -75,11 +75,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof UserNameRouteImport parentRoute: typeof rootRouteImport } - '/$validParam': { - id: '/$validParam' - path: '/$validParam' - fullPath: '/$validParam' - preLoaderRoute: typeof ValidParamRouteImport + '/$123': { + id: '/$123' + path: '/$123' + fullPath: '/$123' + preLoaderRoute: typeof R123RouteImport parentRoute: typeof rootRouteImport } } diff --git a/packages/router-generator/tests/generator/nested-layouts/routeTree.snapshot.ts b/packages/router-generator/tests/generator/nested-layouts/routeTree.snapshot.ts index 7fb6ebb0d0..c38345a64b 100644 --- a/packages/router-generator/tests/generator/nested-layouts/routeTree.snapshot.ts +++ b/packages/router-generator/tests/generator/nested-layouts/routeTree.snapshot.ts @@ -9,84 +9,46 @@ // Additionally, you should also exclude this file 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 LayoutA1RouteImport } from './routes/_layout-a1' import { Route as LayoutA2RouteImport } from './routes/_layout-a2' +import { Route as LayoutA1RouteImport } from './routes/_layout-a1' import { Route as JestedRouteRouteImport } from './routes/jested/route' -import { Route as folderInFolderRouteImport } from './routes/(folder)/in-folder' -import { Route as LayoutA1FooRouteImport } from './routes/_layout-a1/foo' -import { Route as LayoutA2BarRouteImport } from './routes/_layout-a2/bar' -import { Route as FooLayoutB5RouteRouteImport } from './routes/foo/_layout-b5/route' -import { Route as FooBarRouteImport } from './routes/foo/bar' -import { Route as JestedLayoutB3RouteImport } from './routes/jested/_layout-b3' -import { Route as JestedLayoutB4RouteImport } from './routes/jested/_layout-b4' -import { Route as NestedLayoutB1RouteImport } from './routes/nested/_layout-b1' +import { Route as IndexRouteImport } from './routes/index' import { Route as NestedLayoutB2RouteImport } from './routes/nested/_layout-b2' -import { Route as FooLayoutB5IndexRouteImport } from './routes/foo/_layout-b5/index' -import { Route as FooLayoutB5IdRouteImport } from './routes/foo/_layout-b5/$id' -import { Route as JestedLayoutB3IndexRouteImport } from './routes/jested/_layout-b3/index' -import { Route as JestedLayoutB3LayoutC2RouteImport } from './routes/jested/_layout-b3/_layout-c2' -import { Route as JestedLayoutB4FooRouteImport } from './routes/jested/_layout-b4/foo' +import { Route as NestedLayoutB1RouteImport } from './routes/nested/_layout-b1' +import { Route as JestedLayoutB4RouteImport } from './routes/jested/_layout-b4' +import { Route as JestedLayoutB3RouteImport } from './routes/jested/_layout-b3' +import { Route as FooBarRouteImport } from './routes/foo/bar' +import { Route as LayoutA2BarRouteImport } from './routes/_layout-a2/bar' +import { Route as LayoutA1FooRouteImport } from './routes/_layout-a1/foo' +import { Route as folderInFolderRouteImport } from './routes/(folder)/in-folder' +import { Route as FooLayoutB5RouteRouteImport } from './routes/foo/_layout-b5/route' import { Route as NestedLayoutB1IndexRouteImport } from './routes/nested/_layout-b1/index' -import { Route as NestedLayoutB1LayoutC1RouteImport } from './routes/nested/_layout-b1/_layout-c1' +import { Route as JestedLayoutB3IndexRouteImport } from './routes/jested/_layout-b3/index' +import { Route as FooLayoutB5IndexRouteImport } from './routes/foo/_layout-b5/index' import { Route as NestedLayoutB2FooRouteImport } from './routes/nested/_layout-b2/foo' -import { Route as JestedLayoutB3LayoutC2BarRouteImport } from './routes/jested/_layout-b3/_layout-c2/bar' +import { Route as NestedLayoutB1LayoutC1RouteImport } from './routes/nested/_layout-b1/_layout-c1' +import { Route as JestedLayoutB4FooRouteImport } from './routes/jested/_layout-b4/foo' +import { Route as JestedLayoutB3LayoutC2RouteImport } from './routes/jested/_layout-b3/_layout-c2' +import { Route as FooLayoutB5IdRouteImport } from './routes/foo/_layout-b5/$id' import { Route as NestedLayoutB1LayoutC1BarRouteImport } from './routes/nested/_layout-b1/_layout-c1/bar' +import { Route as JestedLayoutB3LayoutC2BarRouteImport } from './routes/jested/_layout-b3/_layout-c2/bar' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const LayoutA2Route = LayoutA2RouteImport.update({ + id: '/_layout-a2', getParentRoute: () => rootRouteImport, } as any) const LayoutA1Route = LayoutA1RouteImport.update({ id: '/_layout-a1', getParentRoute: () => rootRouteImport, } as any) -const LayoutA2Route = LayoutA2RouteImport.update({ - id: '/_layout-a2', - getParentRoute: () => rootRouteImport, -} as any) const JestedRouteRoute = JestedRouteRouteImport.update({ id: '/jested', path: '/jested', getParentRoute: () => rootRouteImport, } as any) -const folderInFolderRoute = folderInFolderRouteImport.update({ - id: '/(folder)/in-folder', - path: '/in-folder', - getParentRoute: () => rootRouteImport, -} as any) -const LayoutA1FooRoute = LayoutA1FooRouteImport.update({ - id: '/foo', - path: '/foo', - getParentRoute: () => LayoutA1Route, -} as any) -const LayoutA2BarRoute = LayoutA2BarRouteImport.update({ - id: '/bar', - path: '/bar', - getParentRoute: () => LayoutA2Route, -} as any) -const FooLayoutB5RouteRoute = FooLayoutB5RouteRouteImport.update({ - id: '/foo/_layout-b5', - path: '/foo', - getParentRoute: () => rootRouteImport, -} as any) -const FooBarRoute = FooBarRouteImport.update({ - id: '/foo/bar', - path: '/foo/bar', - getParentRoute: () => rootRouteImport, -} as any) -const JestedLayoutB3Route = JestedLayoutB3RouteImport.update({ - id: '/_layout-b3', - getParentRoute: () => JestedRouteRoute, -} as any) -const JestedLayoutB4Route = JestedLayoutB4RouteImport.update({ - id: '/_layout-b4', - getParentRoute: () => JestedRouteRoute, -} as any) -const NestedLayoutB1Route = NestedLayoutB1RouteImport.update({ - id: '/nested/_layout-b1', - path: '/nested', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const NestedLayoutB2Route = NestedLayoutB2RouteImport.update({ @@ -94,60 +56,98 @@ const NestedLayoutB2Route = NestedLayoutB2RouteImport.update({ path: '/nested', getParentRoute: () => rootRouteImport, } as any) -const FooLayoutB5IndexRoute = FooLayoutB5IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => FooLayoutB5RouteRoute, +const NestedLayoutB1Route = NestedLayoutB1RouteImport.update({ + id: '/nested/_layout-b1', + path: '/nested', + getParentRoute: () => rootRouteImport, } as any) -const FooLayoutB5IdRoute = FooLayoutB5IdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => FooLayoutB5RouteRoute, +const JestedLayoutB4Route = JestedLayoutB4RouteImport.update({ + id: '/_layout-b4', + getParentRoute: () => JestedRouteRoute, } as any) -const JestedLayoutB3IndexRoute = JestedLayoutB3IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => JestedLayoutB3Route, +const JestedLayoutB3Route = JestedLayoutB3RouteImport.update({ + id: '/_layout-b3', + getParentRoute: () => JestedRouteRoute, } as any) -const JestedLayoutB3LayoutC2Route = JestedLayoutB3LayoutC2RouteImport.update({ - id: '/_layout-c2', - getParentRoute: () => JestedLayoutB3Route, +const FooBarRoute = FooBarRouteImport.update({ + id: '/foo/bar', + path: '/foo/bar', + getParentRoute: () => rootRouteImport, } as any) -const JestedLayoutB4FooRoute = JestedLayoutB4FooRouteImport.update({ +const LayoutA2BarRoute = LayoutA2BarRouteImport.update({ + id: '/bar', + path: '/bar', + getParentRoute: () => LayoutA2Route, +} as any) +const LayoutA1FooRoute = LayoutA1FooRouteImport.update({ id: '/foo', path: '/foo', - getParentRoute: () => JestedLayoutB4Route, + getParentRoute: () => LayoutA1Route, +} as any) +const folderInFolderRoute = folderInFolderRouteImport.update({ + id: '/(folder)/in-folder', + path: '/in-folder', + getParentRoute: () => rootRouteImport, +} as any) +const FooLayoutB5RouteRoute = FooLayoutB5RouteRouteImport.update({ + id: '/foo/_layout-b5', + path: '/foo', + getParentRoute: () => rootRouteImport, } as any) const NestedLayoutB1IndexRoute = NestedLayoutB1IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => NestedLayoutB1Route, } as any) -const NestedLayoutB1LayoutC1Route = NestedLayoutB1LayoutC1RouteImport.update({ - id: '/_layout-c1', - getParentRoute: () => NestedLayoutB1Route, +const JestedLayoutB3IndexRoute = JestedLayoutB3IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => JestedLayoutB3Route, +} as any) +const FooLayoutB5IndexRoute = FooLayoutB5IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => FooLayoutB5RouteRoute, } as any) const NestedLayoutB2FooRoute = NestedLayoutB2FooRouteImport.update({ id: '/foo', path: '/foo', getParentRoute: () => NestedLayoutB2Route, } as any) -const JestedLayoutB3LayoutC2BarRoute = - JestedLayoutB3LayoutC2BarRouteImport.update({ - id: '/bar', - path: '/bar', - getParentRoute: () => JestedLayoutB3LayoutC2Route, - } as any) +const NestedLayoutB1LayoutC1Route = NestedLayoutB1LayoutC1RouteImport.update({ + id: '/_layout-c1', + getParentRoute: () => NestedLayoutB1Route, +} as any) +const JestedLayoutB4FooRoute = JestedLayoutB4FooRouteImport.update({ + id: '/foo', + path: '/foo', + getParentRoute: () => JestedLayoutB4Route, +} as any) +const JestedLayoutB3LayoutC2Route = JestedLayoutB3LayoutC2RouteImport.update({ + id: '/_layout-c2', + getParentRoute: () => JestedLayoutB3Route, +} as any) +const FooLayoutB5IdRoute = FooLayoutB5IdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => FooLayoutB5RouteRoute, +} as any) const NestedLayoutB1LayoutC1BarRoute = NestedLayoutB1LayoutC1BarRouteImport.update({ id: '/bar', path: '/bar', getParentRoute: () => NestedLayoutB1LayoutC1Route, } as any) +const JestedLayoutB3LayoutC2BarRoute = + JestedLayoutB3LayoutC2BarRouteImport.update({ + id: '/bar', + path: '/bar', + getParentRoute: () => JestedLayoutB3LayoutC2Route, + } as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute - '/jested': typeof JestedRouteRouteWithChildren + '/jested': typeof JestedLayoutB3LayoutC2RouteWithChildren '/foo': typeof LayoutA1FooRoute '/in-folder': typeof folderInFolderRoute '/bar': typeof LayoutA2BarRoute @@ -275,11 +275,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' + '/_layout-a2': { + id: '/_layout-a2' + path: '' fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + preLoaderRoute: typeof LayoutA2RouteImport parentRoute: typeof rootRouteImport } '/_layout-a1': { @@ -289,13 +289,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof LayoutA1RouteImport parentRoute: typeof rootRouteImport } - '/_layout-a2': { - id: '/_layout-a2' - path: '' - fullPath: '/' - preLoaderRoute: typeof LayoutA2RouteImport - parentRoute: typeof rootRouteImport - } '/jested': { id: '/jested' path: '/jested' @@ -303,60 +296,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof JestedRouteRouteImport parentRoute: typeof rootRouteImport } - '/(folder)/in-folder': { - id: '/(folder)/in-folder' - path: '/in-folder' - fullPath: '/in-folder' - preLoaderRoute: typeof folderInFolderRouteImport - parentRoute: typeof rootRouteImport - } - '/_layout-a1/foo': { - id: '/_layout-a1/foo' - path: '/foo' - fullPath: '/foo' - preLoaderRoute: typeof LayoutA1FooRouteImport - parentRoute: typeof LayoutA1Route - } - '/_layout-a2/bar': { - id: '/_layout-a2/bar' - path: '/bar' - fullPath: '/bar' - preLoaderRoute: typeof LayoutA2BarRouteImport - parentRoute: typeof LayoutA2Route - } - '/foo/_layout-b5': { - id: '/foo/_layout-b5' - path: '/foo' - fullPath: '/foo' - preLoaderRoute: typeof FooLayoutB5RouteRouteImport - parentRoute: typeof rootRouteImport - } - '/foo/bar': { - id: '/foo/bar' - path: '/foo/bar' - fullPath: '/foo/bar' - preLoaderRoute: typeof FooBarRouteImport - parentRoute: typeof rootRouteImport - } - '/jested/_layout-b3': { - id: '/jested/_layout-b3' - path: '' - fullPath: '/jested' - preLoaderRoute: typeof JestedLayoutB3RouteImport - parentRoute: typeof JestedRouteRoute - } - '/jested/_layout-b4': { - id: '/jested/_layout-b4' - path: '' - fullPath: '/jested' - preLoaderRoute: typeof JestedLayoutB4RouteImport - parentRoute: typeof JestedRouteRoute - } - '/nested/_layout-b1': { - id: '/nested/_layout-b1' - path: '/nested' - fullPath: '/nested' - preLoaderRoute: typeof NestedLayoutB1RouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/nested/_layout-b2': { @@ -366,40 +310,61 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof NestedLayoutB2RouteImport parentRoute: typeof rootRouteImport } - '/foo/_layout-b5/': { - id: '/foo/_layout-b5/' - path: '/' - fullPath: '/foo/' - preLoaderRoute: typeof FooLayoutB5IndexRouteImport - parentRoute: typeof FooLayoutB5RouteRoute + '/nested/_layout-b1': { + id: '/nested/_layout-b1' + path: '/nested' + fullPath: '/nested' + preLoaderRoute: typeof NestedLayoutB1RouteImport + parentRoute: typeof rootRouteImport } - '/foo/_layout-b5/$id': { - id: '/foo/_layout-b5/$id' - path: '/$id' - fullPath: '/foo/$id' - preLoaderRoute: typeof FooLayoutB5IdRouteImport - parentRoute: typeof FooLayoutB5RouteRoute - } - '/jested/_layout-b3/': { - id: '/jested/_layout-b3/' - path: '/' - fullPath: '/jested/' - preLoaderRoute: typeof JestedLayoutB3IndexRouteImport - parentRoute: typeof JestedLayoutB3Route - } - '/jested/_layout-b3/_layout-c2': { - id: '/jested/_layout-b3/_layout-c2' + '/jested/_layout-b4': { + id: '/jested/_layout-b4' path: '' fullPath: '/jested' - preLoaderRoute: typeof JestedLayoutB3LayoutC2RouteImport - parentRoute: typeof JestedLayoutB3Route + preLoaderRoute: typeof JestedLayoutB4RouteImport + parentRoute: typeof JestedRouteRoute } - '/jested/_layout-b4/foo': { - id: '/jested/_layout-b4/foo' + '/jested/_layout-b3': { + id: '/jested/_layout-b3' + path: '' + fullPath: '/jested' + preLoaderRoute: typeof JestedLayoutB3RouteImport + parentRoute: typeof JestedRouteRoute + } + '/foo/bar': { + id: '/foo/bar' + path: '/foo/bar' + fullPath: '/foo/bar' + preLoaderRoute: typeof FooBarRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout-a2/bar': { + id: '/_layout-a2/bar' + path: '/bar' + fullPath: '/bar' + preLoaderRoute: typeof LayoutA2BarRouteImport + parentRoute: typeof LayoutA2Route + } + '/_layout-a1/foo': { + id: '/_layout-a1/foo' path: '/foo' - fullPath: '/jested/foo' - preLoaderRoute: typeof JestedLayoutB4FooRouteImport - parentRoute: typeof JestedLayoutB4Route + fullPath: '/foo' + preLoaderRoute: typeof LayoutA1FooRouteImport + parentRoute: typeof LayoutA1Route + } + '/(folder)/in-folder': { + id: '/(folder)/in-folder' + path: '/in-folder' + fullPath: '/in-folder' + preLoaderRoute: typeof folderInFolderRouteImport + parentRoute: typeof rootRouteImport + } + '/foo/_layout-b5': { + id: '/foo/_layout-b5' + path: '/foo' + fullPath: '/foo' + preLoaderRoute: typeof FooLayoutB5RouteRouteImport + parentRoute: typeof rootRouteImport } '/nested/_layout-b1/': { id: '/nested/_layout-b1/' @@ -408,12 +373,19 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof NestedLayoutB1IndexRouteImport parentRoute: typeof NestedLayoutB1Route } - '/nested/_layout-b1/_layout-c1': { - id: '/nested/_layout-b1/_layout-c1' - path: '' - fullPath: '/nested' - preLoaderRoute: typeof NestedLayoutB1LayoutC1RouteImport - parentRoute: typeof NestedLayoutB1Route + '/jested/_layout-b3/': { + id: '/jested/_layout-b3/' + path: '/' + fullPath: '/jested/' + preLoaderRoute: typeof JestedLayoutB3IndexRouteImport + parentRoute: typeof JestedLayoutB3Route + } + '/foo/_layout-b5/': { + id: '/foo/_layout-b5/' + path: '/' + fullPath: '/foo/' + preLoaderRoute: typeof FooLayoutB5IndexRouteImport + parentRoute: typeof FooLayoutB5RouteRoute } '/nested/_layout-b2/foo': { id: '/nested/_layout-b2/foo' @@ -422,12 +394,33 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof NestedLayoutB2FooRouteImport parentRoute: typeof NestedLayoutB2Route } - '/jested/_layout-b3/_layout-c2/bar': { - id: '/jested/_layout-b3/_layout-c2/bar' - path: '/bar' - fullPath: '/jested/bar' - preLoaderRoute: typeof JestedLayoutB3LayoutC2BarRouteImport - parentRoute: typeof JestedLayoutB3LayoutC2Route + '/nested/_layout-b1/_layout-c1': { + id: '/nested/_layout-b1/_layout-c1' + path: '' + fullPath: '/nested' + preLoaderRoute: typeof NestedLayoutB1LayoutC1RouteImport + parentRoute: typeof NestedLayoutB1Route + } + '/jested/_layout-b4/foo': { + id: '/jested/_layout-b4/foo' + path: '/foo' + fullPath: '/jested/foo' + preLoaderRoute: typeof JestedLayoutB4FooRouteImport + parentRoute: typeof JestedLayoutB4Route + } + '/jested/_layout-b3/_layout-c2': { + id: '/jested/_layout-b3/_layout-c2' + path: '' + fullPath: '/jested' + preLoaderRoute: typeof JestedLayoutB3LayoutC2RouteImport + parentRoute: typeof JestedLayoutB3Route + } + '/foo/_layout-b5/$id': { + id: '/foo/_layout-b5/$id' + path: '/$id' + fullPath: '/foo/$id' + preLoaderRoute: typeof FooLayoutB5IdRouteImport + parentRoute: typeof FooLayoutB5RouteRoute } '/nested/_layout-b1/_layout-c1/bar': { id: '/nested/_layout-b1/_layout-c1/bar' @@ -436,6 +429,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof NestedLayoutB1LayoutC1BarRouteImport parentRoute: typeof NestedLayoutB1LayoutC1Route } + '/jested/_layout-b3/_layout-c2/bar': { + id: '/jested/_layout-b3/_layout-c2/bar' + path: '/bar' + fullPath: '/jested/bar' + preLoaderRoute: typeof JestedLayoutB3LayoutC2BarRouteImport + parentRoute: typeof JestedLayoutB3LayoutC2Route + } } } diff --git a/packages/router-generator/tests/generator/nested-route-groups-with-layouts-before-physical/routeTree.snapshot.ts b/packages/router-generator/tests/generator/nested-route-groups-with-layouts-before-physical/routeTree.snapshot.ts index bda946f97b..6c5c9950b2 100644 --- a/packages/router-generator/tests/generator/nested-route-groups-with-layouts-before-physical/routeTree.snapshot.ts +++ b/packages/router-generator/tests/generator/nested-route-groups-with-layouts-before-physical/routeTree.snapshot.ts @@ -9,58 +9,58 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as groupALayoutARouteImport } from './routes/(group-a)/_layout-a' -import { Route as groupBLayoutBRouteImport } from './routes/(group-b)/_layout-b' import { Route as groupCLayoutCRouteImport } from './routes/(group-c)/_layout-c' -import { Route as groupALayoutALoginRouteImport } from './routes/(group-a)/_layout-a/login' -import { Route as groupALayoutASignupRouteImport } from './routes/(group-a)/_layout-a/signup' -import { Route as groupBLayoutBDashboardRouteImport } from './routes/(group-b)/_layout-b/dashboard' +import { Route as groupBLayoutBRouteImport } from './routes/(group-b)/_layout-b' +import { Route as groupALayoutARouteImport } from './routes/(group-a)/_layout-a' import { Route as groupCLayoutCIndexRouteImport } from './routes/(group-c)/_layout-c/index' +import { Route as groupBLayoutBDashboardRouteImport } from './routes/(group-b)/_layout-b/dashboard' +import { Route as groupALayoutASignupRouteImport } from './routes/(group-a)/_layout-a/signup' +import { Route as groupALayoutALoginRouteImport } from './routes/(group-a)/_layout-a/login' -const groupALayoutARoute = groupALayoutARouteImport.update({ - id: '/(group-a)/_layout-a', +const groupCLayoutCRoute = groupCLayoutCRouteImport.update({ + id: '/(group-c)/_layout-c', getParentRoute: () => rootRouteImport, } as any) const groupBLayoutBRoute = groupBLayoutBRouteImport.update({ id: '/(group-b)/_layout-b', getParentRoute: () => rootRouteImport, } as any) -const groupCLayoutCRoute = groupCLayoutCRouteImport.update({ - id: '/(group-c)/_layout-c', +const groupALayoutARoute = groupALayoutARouteImport.update({ + id: '/(group-a)/_layout-a', getParentRoute: () => rootRouteImport, } as any) -const groupALayoutALoginRoute = groupALayoutALoginRouteImport.update({ - id: '/login', - path: '/login', - getParentRoute: () => groupALayoutARoute, -} as any) -const groupALayoutASignupRoute = groupALayoutASignupRouteImport.update({ - id: '/signup', - path: '/signup', - getParentRoute: () => groupALayoutARoute, -} as any) -const groupBLayoutBDashboardRoute = groupBLayoutBDashboardRouteImport.update({ - id: '/dashboard', - path: '/dashboard', - getParentRoute: () => groupBLayoutBRoute, -} as any) const groupCLayoutCIndexRoute = groupCLayoutCIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => groupCLayoutCRoute, } as any) +const groupBLayoutBDashboardRoute = groupBLayoutBDashboardRouteImport.update({ + id: '/dashboard', + path: '/dashboard', + getParentRoute: () => groupBLayoutBRoute, +} as any) +const groupALayoutASignupRoute = groupALayoutASignupRouteImport.update({ + id: '/signup', + path: '/signup', + getParentRoute: () => groupALayoutARoute, +} as any) +const groupALayoutALoginRoute = groupALayoutALoginRouteImport.update({ + id: '/login', + path: '/login', + getParentRoute: () => groupALayoutARoute, +} as any) export interface FileRoutesByFullPath { - '/': typeof groupCLayoutCIndexRoute '/login': typeof groupALayoutALoginRoute '/signup': typeof groupALayoutASignupRoute '/dashboard': typeof groupBLayoutBDashboardRoute + '/': typeof groupCLayoutCIndexRoute } export interface FileRoutesByTo { - '/': typeof groupCLayoutCIndexRoute '/login': typeof groupALayoutALoginRoute '/signup': typeof groupALayoutASignupRoute '/dashboard': typeof groupBLayoutBDashboardRoute + '/': typeof groupCLayoutCIndexRoute } export interface FileRoutesById { __root__: typeof rootRouteImport @@ -74,9 +74,9 @@ export interface FileRoutesById { } export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/login' | '/signup' | '/dashboard' + fullPaths: '/login' | '/signup' | '/dashboard' | '/' fileRoutesByTo: FileRoutesByTo - to: '/' | '/login' | '/signup' | '/dashboard' + to: '/login' | '/signup' | '/dashboard' | '/' id: | '__root__' | '/(group-a)/_layout-a' @@ -96,40 +96,33 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/(group-a)/_layout-a': { - id: '/(group-a)/_layout-a' + '/(group-c)/_layout-c': { + id: '/(group-c)/_layout-c' path: '' - fullPath: '/' - preLoaderRoute: typeof groupALayoutARouteImport + fullPath: '' + preLoaderRoute: typeof groupCLayoutCRouteImport parentRoute: typeof rootRouteImport } '/(group-b)/_layout-b': { id: '/(group-b)/_layout-b' path: '' - fullPath: '/' + fullPath: '' preLoaderRoute: typeof groupBLayoutBRouteImport parentRoute: typeof rootRouteImport } - '/(group-c)/_layout-c': { - id: '/(group-c)/_layout-c' + '/(group-a)/_layout-a': { + id: '/(group-a)/_layout-a' path: '' - fullPath: '/' - preLoaderRoute: typeof groupCLayoutCRouteImport + fullPath: '' + preLoaderRoute: typeof groupALayoutARouteImport parentRoute: typeof rootRouteImport } - '/(group-a)/_layout-a/login': { - id: '/(group-a)/_layout-a/login' - path: '/login' - fullPath: '/login' - preLoaderRoute: typeof groupALayoutALoginRouteImport - parentRoute: typeof groupALayoutARoute - } - '/(group-a)/_layout-a/signup': { - id: '/(group-a)/_layout-a/signup' - path: '/signup' - fullPath: '/signup' - preLoaderRoute: typeof groupALayoutASignupRouteImport - parentRoute: typeof groupALayoutARoute + '/(group-c)/_layout-c/': { + id: '/(group-c)/_layout-c/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof groupCLayoutCIndexRouteImport + parentRoute: typeof groupCLayoutCRoute } '/(group-b)/_layout-b/dashboard': { id: '/(group-b)/_layout-b/dashboard' @@ -138,12 +131,19 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof groupBLayoutBDashboardRouteImport parentRoute: typeof groupBLayoutBRoute } - '/(group-c)/_layout-c/': { - id: '/(group-c)/_layout-c/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof groupCLayoutCIndexRouteImport - parentRoute: typeof groupCLayoutCRoute + '/(group-a)/_layout-a/signup': { + id: '/(group-a)/_layout-a/signup' + path: '/signup' + fullPath: '/signup' + preLoaderRoute: typeof groupALayoutASignupRouteImport + parentRoute: typeof groupALayoutARoute + } + '/(group-a)/_layout-a/login': { + id: '/(group-a)/_layout-a/login' + path: '/login' + fullPath: '/login' + preLoaderRoute: typeof groupALayoutALoginRouteImport + parentRoute: typeof groupALayoutARoute } } } diff --git a/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routeTree.snapshot.ts b/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routeTree.snapshot.ts new file mode 100644 index 0000000000..ce5d831534 --- /dev/null +++ b/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routeTree.snapshot.ts @@ -0,0 +1,526 @@ +/* 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 type { CreateFileRoute, FileRoutesByPath } from '@tanstack/react-router' + +import { Route as rootRouteImport } from './routes/__root' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as PostsRouteRouteImport } from './routes/posts/route' +import { Route as BlogRouteRouteImport } from './routes/blog/route' +import { Route as IndexRouteImport } from './routes/index' +import { Route as PostsIndexRouteImport } from './routes/posts/index' +import { Route as BlogIndexRouteImport } from './routes/blog/index' +import { Route as BlogStatsRouteImport } from './routes/blog_/stats' +import { Route as BlogSlugRouteImport } from './routes/blog/$slug' +import { Route as PathlessLayoutSettingsRouteImport } from './routes/_pathlessLayout/settings' +import { Route as BlogBlogIdRouteRouteImport } from './routes/blog_/$blogId/route' +import { Route as PostsPostIdIndexRouteImport } from './routes/posts/$postId/index' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts/$postId/deep' +import { Route as BlogBlogIdEditRouteImport } from './routes/blog_/$blogId_/edit' +import { Route as BlogBlogIdSlugRouteRouteImport } from './routes/blog_/$blogId/$slug/route' +import { Route as BlogBlogIdSlugBarRouteImport } from './routes/blog_/$blogId/$slug_/bar' + +const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ + id: '/_pathlessLayout', + getParentRoute: () => rootRouteImport, +} as any) +const PostsRouteRoute = PostsRouteRouteImport.update({ + id: '/posts', + path: '/posts', + getParentRoute: () => rootRouteImport, +} as any) +const BlogRouteRoute = BlogRouteRouteImport.update({ + id: '/blog', + path: '/blog', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const PostsIndexRoute = PostsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PostsRouteRoute, +} as any) +const BlogIndexRoute = BlogIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => BlogRouteRoute, +} as any) +const BlogStatsRoute = BlogStatsRouteImport.update({ + id: '/blog_/stats', + path: '/blog/stats', + getParentRoute: () => rootRouteImport, +} as any) +const BlogSlugRoute = BlogSlugRouteImport.update({ + id: '/$slug', + path: '/$slug', + getParentRoute: () => BlogRouteRoute, +} as any) +const PathlessLayoutSettingsRoute = PathlessLayoutSettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => PathlessLayoutRoute, +} as any) +const BlogBlogIdRouteRoute = BlogBlogIdRouteRouteImport.update({ + id: '/blog_/$blogId', + path: '/blog/$blogId', + getParentRoute: () => rootRouteImport, +} as any) +const PostsPostIdIndexRoute = PostsPostIdIndexRouteImport.update({ + id: '/$postId/', + path: '/$postId/', + getParentRoute: () => PostsRouteRoute, +} as any) +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/$postId/deep', + path: '/$postId/deep', + getParentRoute: () => PostsRouteRoute, +} as any) +const BlogBlogIdEditRoute = BlogBlogIdEditRouteImport.update({ + id: '/blog_/$blogId_/edit', + path: '/blog/$blogId/edit', + getParentRoute: () => rootRouteImport, +} as any) +const BlogBlogIdSlugRouteRoute = BlogBlogIdSlugRouteRouteImport.update({ + id: '/$slug', + path: '/$slug', + getParentRoute: () => BlogBlogIdRouteRoute, +} as any) +const BlogBlogIdSlugBarRoute = BlogBlogIdSlugBarRouteImport.update({ + id: '/$slug_/bar', + path: '/$slug/bar', + getParentRoute: () => BlogBlogIdRouteRoute, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/blog': typeof BlogRouteRouteWithChildren + '/posts': typeof PostsRouteRouteWithChildren + '/blog/$blogId': typeof BlogBlogIdRouteRouteWithChildren + '/settings': typeof PathlessLayoutSettingsRoute + '/blog/$slug': typeof BlogSlugRoute + '/blog/stats': typeof BlogStatsRoute + '/blog/': typeof BlogIndexRoute + '/posts/': typeof PostsIndexRoute + '/blog/$blogId/$slug': typeof BlogBlogIdSlugRouteRoute + '/blog/$blogId/edit': typeof BlogBlogIdEditRoute + '/posts/$postId/deep': typeof PostsPostIdDeepRoute + '/posts/$postId/': typeof PostsPostIdIndexRoute + '/blog/$blogId/$slug/bar': typeof BlogBlogIdSlugBarRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/blog/$blogId': typeof BlogBlogIdRouteRouteWithChildren + '/settings': typeof PathlessLayoutSettingsRoute + '/blog/$slug': typeof BlogSlugRoute + '/blog/stats': typeof BlogStatsRoute + '/blog': typeof BlogIndexRoute + '/posts': typeof PostsIndexRoute + '/blog/$blogId/$slug': typeof BlogBlogIdSlugRouteRoute + '/blog/$blogId/edit': typeof BlogBlogIdEditRoute + '/posts/$postId/deep': typeof PostsPostIdDeepRoute + '/posts/$postId': typeof PostsPostIdIndexRoute + '/blog/$blogId/$slug/bar': typeof BlogBlogIdSlugBarRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/blog': typeof BlogRouteRouteWithChildren + '/posts': typeof PostsRouteRouteWithChildren + '/_pathlessLayout': typeof PathlessLayoutRouteWithChildren + '/blog_/$blogId': typeof BlogBlogIdRouteRouteWithChildren + '/_pathlessLayout/settings': typeof PathlessLayoutSettingsRoute + '/blog/$slug': typeof BlogSlugRoute + '/blog_/stats': typeof BlogStatsRoute + '/blog/': typeof BlogIndexRoute + '/posts/': typeof PostsIndexRoute + '/blog_/$blogId/$slug': typeof BlogBlogIdSlugRouteRoute + '/blog_/$blogId_/edit': typeof BlogBlogIdEditRoute + '/posts/$postId/deep': typeof PostsPostIdDeepRoute + '/posts/$postId/': typeof PostsPostIdIndexRoute + '/blog_/$blogId/$slug_/bar': typeof BlogBlogIdSlugBarRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/blog' + | '/posts' + | '/blog/$blogId' + | '/settings' + | '/blog/$slug' + | '/blog/stats' + | '/blog/' + | '/posts/' + | '/blog/$blogId/$slug' + | '/blog/$blogId/edit' + | '/posts/$postId/deep' + | '/posts/$postId/' + | '/blog/$blogId/$slug/bar' + fileRoutesByTo: FileRoutesByTo + to: + | '/' + | '/blog/$blogId' + | '/settings' + | '/blog/$slug' + | '/blog/stats' + | '/blog' + | '/posts' + | '/blog/$blogId/$slug' + | '/blog/$blogId/edit' + | '/posts/$postId/deep' + | '/posts/$postId' + | '/blog/$blogId/$slug/bar' + id: + | '__root__' + | '/' + | '/blog' + | '/posts' + | '/_pathlessLayout' + | '/blog_/$blogId' + | '/_pathlessLayout/settings' + | '/blog/$slug' + | '/blog_/stats' + | '/blog/' + | '/posts/' + | '/blog_/$blogId/$slug' + | '/blog_/$blogId_/edit' + | '/posts/$postId/deep' + | '/posts/$postId/' + | '/blog_/$blogId/$slug_/bar' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + BlogRouteRoute: typeof BlogRouteRouteWithChildren + PostsRouteRoute: typeof PostsRouteRouteWithChildren + PathlessLayoutRoute: typeof PathlessLayoutRouteWithChildren + BlogBlogIdRouteRoute: typeof BlogBlogIdRouteRouteWithChildren + BlogStatsRoute: typeof BlogStatsRoute + BlogBlogIdEditRoute: typeof BlogBlogIdEditRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/_pathlessLayout': { + id: '/_pathlessLayout' + path: '' + fullPath: '/' + preLoaderRoute: typeof PathlessLayoutRouteImport + parentRoute: typeof rootRouteImport + } + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteRouteImport + parentRoute: typeof rootRouteImport + } + '/blog': { + id: '/blog' + path: '/blog' + fullPath: '/blog' + preLoaderRoute: typeof BlogRouteRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRouteRoute + } + '/blog/': { + id: '/blog/' + path: '/' + fullPath: '/blog/' + preLoaderRoute: typeof BlogIndexRouteImport + parentRoute: typeof BlogRouteRoute + } + '/blog_/stats': { + id: '/blog_/stats' + path: '/blog/stats' + fullPath: '/blog/stats' + preLoaderRoute: typeof BlogStatsRouteImport + parentRoute: typeof rootRouteImport + } + '/blog/$slug': { + id: '/blog/$slug' + path: '/$slug' + fullPath: '/blog/$slug' + preLoaderRoute: typeof BlogSlugRouteImport + parentRoute: typeof BlogRouteRoute + } + '/_pathlessLayout/settings': { + id: '/_pathlessLayout/settings' + path: '/settings' + fullPath: '/settings' + preLoaderRoute: typeof PathlessLayoutSettingsRouteImport + parentRoute: typeof PathlessLayoutRoute + } + '/blog_/$blogId': { + id: '/blog_/$blogId' + path: '/blog/$blogId' + fullPath: '/blog/$blogId' + preLoaderRoute: typeof BlogBlogIdRouteRouteImport + parentRoute: typeof rootRouteImport + } + '/posts/$postId/': { + id: '/posts/$postId/' + path: '/$postId' + fullPath: '/posts/$postId/' + preLoaderRoute: typeof PostsPostIdIndexRouteImport + parentRoute: typeof PostsRouteRoute + } + '/posts/$postId/deep': { + id: '/posts/$postId/deep' + path: '/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport + parentRoute: typeof PostsRouteRoute + } + '/blog_/$blogId_/edit': { + id: '/blog_/$blogId_/edit' + path: '/blog/$blogId/edit' + fullPath: '/blog/$blogId/edit' + preLoaderRoute: typeof BlogBlogIdEditRouteImport + parentRoute: typeof rootRouteImport + } + '/blog_/$blogId/$slug': { + id: '/blog_/$blogId/$slug' + path: '/$slug' + fullPath: '/blog/$blogId/$slug' + preLoaderRoute: typeof BlogBlogIdSlugRouteRouteImport + parentRoute: typeof BlogBlogIdRouteRoute + } + '/blog_/$blogId/$slug_/bar': { + id: '/blog_/$blogId/$slug_/bar' + path: '/$slug/bar' + fullPath: '/blog/$blogId/$slug/bar' + preLoaderRoute: typeof BlogBlogIdSlugBarRouteImport + parentRoute: typeof BlogBlogIdRouteRoute + } + } +} + +declare module './routes/index' { + const createFileRoute: CreateFileRoute< + '/', + FileRoutesByPath['/']['parentRoute'], + FileRoutesByPath['/']['id'], + FileRoutesByPath['/']['path'], + FileRoutesByPath['/']['fullPath'] + > +} +declare module './routes/blog/route' { + const createFileRoute: CreateFileRoute< + '/blog', + FileRoutesByPath['/blog']['parentRoute'], + FileRoutesByPath['/blog']['id'], + FileRoutesByPath['/blog']['path'], + FileRoutesByPath['/blog']['fullPath'] + > +} +declare module './routes/posts/route' { + const createFileRoute: CreateFileRoute< + '/posts', + FileRoutesByPath['/posts']['parentRoute'], + FileRoutesByPath['/posts']['id'], + FileRoutesByPath['/posts']['path'], + FileRoutesByPath['/posts']['fullPath'] + > +} +declare module './routes/_pathlessLayout' { + const createFileRoute: CreateFileRoute< + '/_pathlessLayout', + FileRoutesByPath['/_pathlessLayout']['parentRoute'], + FileRoutesByPath['/_pathlessLayout']['id'], + FileRoutesByPath['/_pathlessLayout']['path'], + FileRoutesByPath['/_pathlessLayout']['fullPath'] + > +} +declare module './routes/blog_/$blogId/route' { + const createFileRoute: CreateFileRoute< + '/blog_/$blogId', + FileRoutesByPath['/blog_/$blogId']['parentRoute'], + FileRoutesByPath['/blog_/$blogId']['id'], + FileRoutesByPath['/blog_/$blogId']['path'], + FileRoutesByPath['/blog_/$blogId']['fullPath'] + > +} +declare module './routes/_pathlessLayout/settings' { + const createFileRoute: CreateFileRoute< + '/_pathlessLayout/settings', + FileRoutesByPath['/_pathlessLayout/settings']['parentRoute'], + FileRoutesByPath['/_pathlessLayout/settings']['id'], + FileRoutesByPath['/_pathlessLayout/settings']['path'], + FileRoutesByPath['/_pathlessLayout/settings']['fullPath'] + > +} +declare module './routes/blog/$slug' { + const createFileRoute: CreateFileRoute< + '/blog/$slug', + FileRoutesByPath['/blog/$slug']['parentRoute'], + FileRoutesByPath['/blog/$slug']['id'], + FileRoutesByPath['/blog/$slug']['path'], + FileRoutesByPath['/blog/$slug']['fullPath'] + > +} +declare module './routes/blog_/stats' { + const createFileRoute: CreateFileRoute< + '/blog_/stats', + FileRoutesByPath['/blog_/stats']['parentRoute'], + FileRoutesByPath['/blog_/stats']['id'], + FileRoutesByPath['/blog_/stats']['path'], + FileRoutesByPath['/blog_/stats']['fullPath'] + > +} +declare module './routes/blog/index' { + const createFileRoute: CreateFileRoute< + '/blog/', + FileRoutesByPath['/blog/']['parentRoute'], + FileRoutesByPath['/blog/']['id'], + FileRoutesByPath['/blog/']['path'], + FileRoutesByPath['/blog/']['fullPath'] + > +} +declare module './routes/posts/index' { + const createFileRoute: CreateFileRoute< + '/posts/', + FileRoutesByPath['/posts/']['parentRoute'], + FileRoutesByPath['/posts/']['id'], + FileRoutesByPath['/posts/']['path'], + FileRoutesByPath['/posts/']['fullPath'] + > +} +declare module './routes/blog_/$blogId/$slug/route' { + const createFileRoute: CreateFileRoute< + '/blog_/$blogId/$slug', + FileRoutesByPath['/blog_/$blogId/$slug']['parentRoute'], + FileRoutesByPath['/blog_/$blogId/$slug']['id'], + FileRoutesByPath['/blog_/$blogId/$slug']['path'], + FileRoutesByPath['/blog_/$blogId/$slug']['fullPath'] + > +} +declare module './routes/blog_/$blogId_/edit' { + const createFileRoute: CreateFileRoute< + '/blog_/$blogId_/edit', + FileRoutesByPath['/blog_/$blogId_/edit']['parentRoute'], + FileRoutesByPath['/blog_/$blogId_/edit']['id'], + FileRoutesByPath['/blog_/$blogId_/edit']['path'], + FileRoutesByPath['/blog_/$blogId_/edit']['fullPath'] + > +} +declare module './routes/posts/$postId/deep' { + const createFileRoute: CreateFileRoute< + '/posts/$postId/deep', + FileRoutesByPath['/posts/$postId/deep']['parentRoute'], + FileRoutesByPath['/posts/$postId/deep']['id'], + FileRoutesByPath['/posts/$postId/deep']['path'], + FileRoutesByPath['/posts/$postId/deep']['fullPath'] + > +} +declare module './routes/posts/$postId/index' { + const createFileRoute: CreateFileRoute< + '/posts/$postId/', + FileRoutesByPath['/posts/$postId/']['parentRoute'], + FileRoutesByPath['/posts/$postId/']['id'], + FileRoutesByPath['/posts/$postId/']['path'], + FileRoutesByPath['/posts/$postId/']['fullPath'] + > +} +declare module './routes/blog_/$blogId/$slug_/bar' { + const createFileRoute: CreateFileRoute< + '/blog_/$blogId/$slug_/bar', + FileRoutesByPath['/blog_/$blogId/$slug_/bar']['parentRoute'], + FileRoutesByPath['/blog_/$blogId/$slug_/bar']['id'], + FileRoutesByPath['/blog_/$blogId/$slug_/bar']['path'], + FileRoutesByPath['/blog_/$blogId/$slug_/bar']['fullPath'] + > +} + +interface BlogRouteRouteChildren { + BlogSlugRoute: typeof BlogSlugRoute + BlogIndexRoute: typeof BlogIndexRoute +} + +const BlogRouteRouteChildren: BlogRouteRouteChildren = { + BlogSlugRoute: BlogSlugRoute, + BlogIndexRoute: BlogIndexRoute, +} + +const BlogRouteRouteWithChildren = BlogRouteRoute._addFileChildren( + BlogRouteRouteChildren, +) + +interface PostsRouteRouteChildren { + PostsIndexRoute: typeof PostsIndexRoute + PostsPostIdDeepRoute: typeof PostsPostIdDeepRoute + PostsPostIdIndexRoute: typeof PostsPostIdIndexRoute +} + +const PostsRouteRouteChildren: PostsRouteRouteChildren = { + PostsIndexRoute: PostsIndexRoute, + PostsPostIdDeepRoute: PostsPostIdDeepRoute, + PostsPostIdIndexRoute: PostsPostIdIndexRoute, +} + +const PostsRouteRouteWithChildren = PostsRouteRoute._addFileChildren( + PostsRouteRouteChildren, +) + +interface PathlessLayoutRouteChildren { + PathlessLayoutSettingsRoute: typeof PathlessLayoutSettingsRoute +} + +const PathlessLayoutRouteChildren: PathlessLayoutRouteChildren = { + PathlessLayoutSettingsRoute: PathlessLayoutSettingsRoute, +} + +const PathlessLayoutRouteWithChildren = PathlessLayoutRoute._addFileChildren( + PathlessLayoutRouteChildren, +) + +interface BlogBlogIdRouteRouteChildren { + BlogBlogIdSlugRouteRoute: typeof BlogBlogIdSlugRouteRoute + BlogBlogIdSlugBarRoute: typeof BlogBlogIdSlugBarRoute +} + +const BlogBlogIdRouteRouteChildren: BlogBlogIdRouteRouteChildren = { + BlogBlogIdSlugRouteRoute: BlogBlogIdSlugRouteRoute, + BlogBlogIdSlugBarRoute: BlogBlogIdSlugBarRoute, +} + +const BlogBlogIdRouteRouteWithChildren = BlogBlogIdRouteRoute._addFileChildren( + BlogBlogIdRouteRouteChildren, +) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + BlogRouteRoute: BlogRouteRouteWithChildren, + PostsRouteRoute: PostsRouteRouteWithChildren, + PathlessLayoutRoute: PathlessLayoutRouteWithChildren, + BlogBlogIdRouteRoute: BlogBlogIdRouteRouteWithChildren, + BlogStatsRoute: BlogStatsRoute, + BlogBlogIdEditRoute: BlogBlogIdEditRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes<FileRouteTypes>() diff --git a/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/__root.tsx b/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/__root.tsx new file mode 100644 index 0000000000..f89644e82d --- /dev/null +++ b/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/__root.tsx @@ -0,0 +1,11 @@ +import * as React from 'react' +import { Outlet, createRootRoute } from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: () => ( + <React.Fragment> + <div>Hello "__root"!</div> + <Outlet /> + </React.Fragment> + ), +}) diff --git a/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/_pathlessLayout.tsx b/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/_pathlessLayout.tsx new file mode 100644 index 0000000000..ae38370b80 --- /dev/null +++ b/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/_pathlessLayout.tsx @@ -0,0 +1,4 @@ +import { Outlet } from '@tanstack/react-router' +export const Route = createFileRoute({ + component: () => <Outlet />, +}) diff --git a/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/_pathlessLayout/settings.tsx b/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/_pathlessLayout/settings.tsx new file mode 100644 index 0000000000..b2a1f1a950 --- /dev/null +++ b/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/_pathlessLayout/settings.tsx @@ -0,0 +1,3 @@ +export const Route = createFileRoute({ + component: () => <div>Settings</div>, +}) diff --git a/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/blog/$slug.tsx b/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/blog/$slug.tsx new file mode 100644 index 0000000000..784c2b78ae --- /dev/null +++ b/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/blog/$slug.tsx @@ -0,0 +1,3 @@ +export const Route = createFileRoute({ + component: () => <div>Hello /blog/$slug!</div>, +}) diff --git a/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/blog/index.tsx b/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/blog/index.tsx new file mode 100644 index 0000000000..0754024ed7 --- /dev/null +++ b/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/blog/index.tsx @@ -0,0 +1,3 @@ +export const Route = createFileRoute({ + component: () => <div>Hello /blog/!</div>, +}) diff --git a/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/blog/route.tsx b/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/blog/route.tsx new file mode 100644 index 0000000000..ea94edad49 --- /dev/null +++ b/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/blog/route.tsx @@ -0,0 +1,3 @@ +export const Route = createFileRoute({ + component: () => <div>Hello /blog!</div>, +}) diff --git a/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/blog_/$blogId/$slug/route.tsx b/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/blog_/$blogId/$slug/route.tsx new file mode 100644 index 0000000000..3411fd0b37 --- /dev/null +++ b/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/blog_/$blogId/$slug/route.tsx @@ -0,0 +1,3 @@ +export const Route = createFileRoute({ + component: () => <div>Hello /blog_/$blogId/$slug/route!</div>, +}) diff --git a/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/blog_/$blogId/$slug_/bar.tsx b/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/blog_/$blogId/$slug_/bar.tsx new file mode 100644 index 0000000000..c39dd91dfe --- /dev/null +++ b/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/blog_/$blogId/$slug_/bar.tsx @@ -0,0 +1,3 @@ +export const Route = createFileRoute({ + component: () => <div>Hello /blog_/$blogId/$slug_/bar!</div>, +}) diff --git a/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/blog_/$blogId/route.tsx b/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/blog_/$blogId/route.tsx new file mode 100644 index 0000000000..e1d6f6524f --- /dev/null +++ b/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/blog_/$blogId/route.tsx @@ -0,0 +1,3 @@ +export const Route = createFileRoute({ + component: () => <div>Hello /blog_/$blogId/route!</div>, +}) diff --git a/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/blog_/$blogId_/edit.tsx b/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/blog_/$blogId_/edit.tsx new file mode 100644 index 0000000000..1337ddd18b --- /dev/null +++ b/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/blog_/$blogId_/edit.tsx @@ -0,0 +1,3 @@ +export const Route = createFileRoute({ + component: () => <div>Hello /blog_/$blogId_/edit!</div>, +}) diff --git a/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/blog_/stats.tsx b/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/blog_/stats.tsx new file mode 100644 index 0000000000..16cc7268df --- /dev/null +++ b/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/blog_/stats.tsx @@ -0,0 +1,3 @@ +export const Route = createFileRoute({ + component: () => <div>Hello /blog/stats!</div>, +}) diff --git a/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/index.tsx b/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/index.tsx new file mode 100644 index 0000000000..22cab82307 --- /dev/null +++ b/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/index.tsx @@ -0,0 +1,3 @@ +export const Route = createFileRoute({ + component: () => <div>Hello /!</div>, +}) diff --git a/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/posts/$postId/deep.tsx b/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/posts/$postId/deep.tsx new file mode 100644 index 0000000000..6e634d9098 --- /dev/null +++ b/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/posts/$postId/deep.tsx @@ -0,0 +1,6 @@ +export const Route = createFileRoute({ + context: () => ({ someContext: 'context' }), + loaderDeps: () => ({ dep: 1 }), + loader: () => ({ data: 'data' }), + component: () => <div>Hello /posts/$postId/deep!</div>, +}) diff --git a/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/posts/$postId/index.tsx b/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/posts/$postId/index.tsx new file mode 100644 index 0000000000..6e8e65dae7 --- /dev/null +++ b/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/posts/$postId/index.tsx @@ -0,0 +1,6 @@ +export const Route = createFileRoute({ + validateSearch: () => ({ + indexSearch: 'search', + }), + component: () => <div>Hello /posts/$postId/!</div>, +}) diff --git a/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/posts/index.tsx b/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/posts/index.tsx new file mode 100644 index 0000000000..2e16af1ca1 --- /dev/null +++ b/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/posts/index.tsx @@ -0,0 +1,3 @@ +export const Route = createFileRoute({ + component: () => <div>Hello /posts/!</div>, +}) diff --git a/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/posts/route.tsx b/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/posts/route.tsx new file mode 100644 index 0000000000..3617558181 --- /dev/null +++ b/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/routes/posts/route.tsx @@ -0,0 +1,3 @@ +export const Route = createFileRoute({ + component: () => <div>Hello /posts!</div>, +}) diff --git a/packages/router-generator/tests/generator/nested/tests.test-d.ts b/packages/router-generator/tests/generator/nested-verboseFileRoutes-false/tests.test-d.ts similarity index 100% rename from packages/router-generator/tests/generator/nested/tests.test-d.ts rename to packages/router-generator/tests/generator/nested-verboseFileRoutes-false/tests.test-d.ts diff --git a/packages/router-generator/tests/generator/nested-verboseFileRoutes-true/routeTree.snapshot.ts b/packages/router-generator/tests/generator/nested-verboseFileRoutes-true/routeTree.snapshot.ts new file mode 100644 index 0000000000..9a87dd6953 --- /dev/null +++ b/packages/router-generator/tests/generator/nested-verboseFileRoutes-true/routeTree.snapshot.ts @@ -0,0 +1,388 @@ +/* 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 PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as PostsRouteRouteImport } from './routes/posts/route' +import { Route as BlogRouteRouteImport } from './routes/blog/route' +import { Route as IndexRouteImport } from './routes/index' +import { Route as PostsIndexRouteImport } from './routes/posts/index' +import { Route as BlogIndexRouteImport } from './routes/blog/index' +import { Route as BlogStatsRouteImport } from './routes/blog_/stats' +import { Route as BlogSlugRouteImport } from './routes/blog/$slug' +import { Route as PathlessLayoutSettingsRouteImport } from './routes/_pathlessLayout/settings' +import { Route as BlogBlogIdRouteRouteImport } from './routes/blog_/$blogId/route' +import { Route as PostsPostIdIndexRouteImport } from './routes/posts/$postId/index' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts/$postId/deep' +import { Route as BlogBlogIdEditRouteImport } from './routes/blog_/$blogId_/edit' +import { Route as BlogBlogIdSlugRouteRouteImport } from './routes/blog_/$blogId/$slug/route' +import { Route as BlogBlogIdSlugBarRouteImport } from './routes/blog_/$blogId/$slug_/bar' + +const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ + id: '/_pathlessLayout', + getParentRoute: () => rootRouteImport, +} as any) +const PostsRouteRoute = PostsRouteRouteImport.update({ + id: '/posts', + path: '/posts', + getParentRoute: () => rootRouteImport, +} as any) +const BlogRouteRoute = BlogRouteRouteImport.update({ + id: '/blog', + path: '/blog', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const PostsIndexRoute = PostsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PostsRouteRoute, +} as any) +const BlogIndexRoute = BlogIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => BlogRouteRoute, +} as any) +const BlogStatsRoute = BlogStatsRouteImport.update({ + id: '/blog_/stats', + path: '/blog/stats', + getParentRoute: () => rootRouteImport, +} as any) +const BlogSlugRoute = BlogSlugRouteImport.update({ + id: '/$slug', + path: '/$slug', + getParentRoute: () => BlogRouteRoute, +} as any) +const PathlessLayoutSettingsRoute = PathlessLayoutSettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => PathlessLayoutRoute, +} as any) +const BlogBlogIdRouteRoute = BlogBlogIdRouteRouteImport.update({ + id: '/blog_/$blogId', + path: '/blog/$blogId', + getParentRoute: () => rootRouteImport, +} as any) +const PostsPostIdIndexRoute = PostsPostIdIndexRouteImport.update({ + id: '/$postId/', + path: '/$postId/', + getParentRoute: () => PostsRouteRoute, +} as any) +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/$postId/deep', + path: '/$postId/deep', + getParentRoute: () => PostsRouteRoute, +} as any) +const BlogBlogIdEditRoute = BlogBlogIdEditRouteImport.update({ + id: '/blog_/$blogId_/edit', + path: '/blog/$blogId/edit', + getParentRoute: () => rootRouteImport, +} as any) +const BlogBlogIdSlugRouteRoute = BlogBlogIdSlugRouteRouteImport.update({ + id: '/$slug', + path: '/$slug', + getParentRoute: () => BlogBlogIdRouteRoute, +} as any) +const BlogBlogIdSlugBarRoute = BlogBlogIdSlugBarRouteImport.update({ + id: '/$slug_/bar', + path: '/$slug/bar', + getParentRoute: () => BlogBlogIdRouteRoute, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/blog': typeof BlogRouteRouteWithChildren + '/posts': typeof PostsRouteRouteWithChildren + '/blog/$blogId': typeof BlogBlogIdRouteRouteWithChildren + '/settings': typeof PathlessLayoutSettingsRoute + '/blog/$slug': typeof BlogSlugRoute + '/blog/stats': typeof BlogStatsRoute + '/blog/': typeof BlogIndexRoute + '/posts/': typeof PostsIndexRoute + '/blog/$blogId/$slug': typeof BlogBlogIdSlugRouteRoute + '/blog/$blogId/edit': typeof BlogBlogIdEditRoute + '/posts/$postId/deep': typeof PostsPostIdDeepRoute + '/posts/$postId/': typeof PostsPostIdIndexRoute + '/blog/$blogId/$slug/bar': typeof BlogBlogIdSlugBarRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/blog/$blogId': typeof BlogBlogIdRouteRouteWithChildren + '/settings': typeof PathlessLayoutSettingsRoute + '/blog/$slug': typeof BlogSlugRoute + '/blog/stats': typeof BlogStatsRoute + '/blog': typeof BlogIndexRoute + '/posts': typeof PostsIndexRoute + '/blog/$blogId/$slug': typeof BlogBlogIdSlugRouteRoute + '/blog/$blogId/edit': typeof BlogBlogIdEditRoute + '/posts/$postId/deep': typeof PostsPostIdDeepRoute + '/posts/$postId': typeof PostsPostIdIndexRoute + '/blog/$blogId/$slug/bar': typeof BlogBlogIdSlugBarRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/blog': typeof BlogRouteRouteWithChildren + '/posts': typeof PostsRouteRouteWithChildren + '/_pathlessLayout': typeof PathlessLayoutRouteWithChildren + '/blog_/$blogId': typeof BlogBlogIdRouteRouteWithChildren + '/_pathlessLayout/settings': typeof PathlessLayoutSettingsRoute + '/blog/$slug': typeof BlogSlugRoute + '/blog_/stats': typeof BlogStatsRoute + '/blog/': typeof BlogIndexRoute + '/posts/': typeof PostsIndexRoute + '/blog_/$blogId/$slug': typeof BlogBlogIdSlugRouteRoute + '/blog_/$blogId_/edit': typeof BlogBlogIdEditRoute + '/posts/$postId/deep': typeof PostsPostIdDeepRoute + '/posts/$postId/': typeof PostsPostIdIndexRoute + '/blog_/$blogId/$slug_/bar': typeof BlogBlogIdSlugBarRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/blog' + | '/posts' + | '/blog/$blogId' + | '/settings' + | '/blog/$slug' + | '/blog/stats' + | '/blog/' + | '/posts/' + | '/blog/$blogId/$slug' + | '/blog/$blogId/edit' + | '/posts/$postId/deep' + | '/posts/$postId/' + | '/blog/$blogId/$slug/bar' + fileRoutesByTo: FileRoutesByTo + to: + | '/' + | '/blog/$blogId' + | '/settings' + | '/blog/$slug' + | '/blog/stats' + | '/blog' + | '/posts' + | '/blog/$blogId/$slug' + | '/blog/$blogId/edit' + | '/posts/$postId/deep' + | '/posts/$postId' + | '/blog/$blogId/$slug/bar' + id: + | '__root__' + | '/' + | '/blog' + | '/posts' + | '/_pathlessLayout' + | '/blog_/$blogId' + | '/_pathlessLayout/settings' + | '/blog/$slug' + | '/blog_/stats' + | '/blog/' + | '/posts/' + | '/blog_/$blogId/$slug' + | '/blog_/$blogId_/edit' + | '/posts/$postId/deep' + | '/posts/$postId/' + | '/blog_/$blogId/$slug_/bar' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + BlogRouteRoute: typeof BlogRouteRouteWithChildren + PostsRouteRoute: typeof PostsRouteRouteWithChildren + PathlessLayoutRoute: typeof PathlessLayoutRouteWithChildren + BlogBlogIdRouteRoute: typeof BlogBlogIdRouteRouteWithChildren + BlogStatsRoute: typeof BlogStatsRoute + BlogBlogIdEditRoute: typeof BlogBlogIdEditRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/_pathlessLayout': { + id: '/_pathlessLayout' + path: '' + fullPath: '/' + preLoaderRoute: typeof PathlessLayoutRouteImport + parentRoute: typeof rootRouteImport + } + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteRouteImport + parentRoute: typeof rootRouteImport + } + '/blog': { + id: '/blog' + path: '/blog' + fullPath: '/blog' + preLoaderRoute: typeof BlogRouteRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRouteRoute + } + '/blog/': { + id: '/blog/' + path: '/' + fullPath: '/blog/' + preLoaderRoute: typeof BlogIndexRouteImport + parentRoute: typeof BlogRouteRoute + } + '/blog_/stats': { + id: '/blog_/stats' + path: '/blog/stats' + fullPath: '/blog/stats' + preLoaderRoute: typeof BlogStatsRouteImport + parentRoute: typeof rootRouteImport + } + '/blog/$slug': { + id: '/blog/$slug' + path: '/$slug' + fullPath: '/blog/$slug' + preLoaderRoute: typeof BlogSlugRouteImport + parentRoute: typeof BlogRouteRoute + } + '/_pathlessLayout/settings': { + id: '/_pathlessLayout/settings' + path: '/settings' + fullPath: '/settings' + preLoaderRoute: typeof PathlessLayoutSettingsRouteImport + parentRoute: typeof PathlessLayoutRoute + } + '/blog_/$blogId': { + id: '/blog_/$blogId' + path: '/blog/$blogId' + fullPath: '/blog/$blogId' + preLoaderRoute: typeof BlogBlogIdRouteRouteImport + parentRoute: typeof rootRouteImport + } + '/posts/$postId/': { + id: '/posts/$postId/' + path: '/$postId' + fullPath: '/posts/$postId/' + preLoaderRoute: typeof PostsPostIdIndexRouteImport + parentRoute: typeof PostsRouteRoute + } + '/posts/$postId/deep': { + id: '/posts/$postId/deep' + path: '/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport + parentRoute: typeof PostsRouteRoute + } + '/blog_/$blogId_/edit': { + id: '/blog_/$blogId_/edit' + path: '/blog/$blogId/edit' + fullPath: '/blog/$blogId/edit' + preLoaderRoute: typeof BlogBlogIdEditRouteImport + parentRoute: typeof rootRouteImport + } + '/blog_/$blogId/$slug': { + id: '/blog_/$blogId/$slug' + path: '/$slug' + fullPath: '/blog/$blogId/$slug' + preLoaderRoute: typeof BlogBlogIdSlugRouteRouteImport + parentRoute: typeof BlogBlogIdRouteRoute + } + '/blog_/$blogId/$slug_/bar': { + id: '/blog_/$blogId/$slug_/bar' + path: '/$slug/bar' + fullPath: '/blog/$blogId/$slug/bar' + preLoaderRoute: typeof BlogBlogIdSlugBarRouteImport + parentRoute: typeof BlogBlogIdRouteRoute + } + } +} + +interface BlogRouteRouteChildren { + BlogSlugRoute: typeof BlogSlugRoute + BlogIndexRoute: typeof BlogIndexRoute +} + +const BlogRouteRouteChildren: BlogRouteRouteChildren = { + BlogSlugRoute: BlogSlugRoute, + BlogIndexRoute: BlogIndexRoute, +} + +const BlogRouteRouteWithChildren = BlogRouteRoute._addFileChildren( + BlogRouteRouteChildren, +) + +interface PostsRouteRouteChildren { + PostsIndexRoute: typeof PostsIndexRoute + PostsPostIdDeepRoute: typeof PostsPostIdDeepRoute + PostsPostIdIndexRoute: typeof PostsPostIdIndexRoute +} + +const PostsRouteRouteChildren: PostsRouteRouteChildren = { + PostsIndexRoute: PostsIndexRoute, + PostsPostIdDeepRoute: PostsPostIdDeepRoute, + PostsPostIdIndexRoute: PostsPostIdIndexRoute, +} + +const PostsRouteRouteWithChildren = PostsRouteRoute._addFileChildren( + PostsRouteRouteChildren, +) + +interface PathlessLayoutRouteChildren { + PathlessLayoutSettingsRoute: typeof PathlessLayoutSettingsRoute +} + +const PathlessLayoutRouteChildren: PathlessLayoutRouteChildren = { + PathlessLayoutSettingsRoute: PathlessLayoutSettingsRoute, +} + +const PathlessLayoutRouteWithChildren = PathlessLayoutRoute._addFileChildren( + PathlessLayoutRouteChildren, +) + +interface BlogBlogIdRouteRouteChildren { + BlogBlogIdSlugRouteRoute: typeof BlogBlogIdSlugRouteRoute + BlogBlogIdSlugBarRoute: typeof BlogBlogIdSlugBarRoute +} + +const BlogBlogIdRouteRouteChildren: BlogBlogIdRouteRouteChildren = { + BlogBlogIdSlugRouteRoute: BlogBlogIdSlugRouteRoute, + BlogBlogIdSlugBarRoute: BlogBlogIdSlugBarRoute, +} + +const BlogBlogIdRouteRouteWithChildren = BlogBlogIdRouteRoute._addFileChildren( + BlogBlogIdRouteRouteChildren, +) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + BlogRouteRoute: BlogRouteRouteWithChildren, + PostsRouteRoute: PostsRouteRouteWithChildren, + PathlessLayoutRoute: PathlessLayoutRouteWithChildren, + BlogBlogIdRouteRoute: BlogBlogIdRouteRouteWithChildren, + BlogStatsRoute: BlogStatsRoute, + BlogBlogIdEditRoute: BlogBlogIdEditRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes<FileRouteTypes>() diff --git a/packages/router-generator/tests/generator/nested-verboseFileRoutes-true/routes/__root.tsx b/packages/router-generator/tests/generator/nested-verboseFileRoutes-true/routes/__root.tsx new file mode 100644 index 0000000000..f89644e82d --- /dev/null +++ b/packages/router-generator/tests/generator/nested-verboseFileRoutes-true/routes/__root.tsx @@ -0,0 +1,11 @@ +import * as React from 'react' +import { Outlet, createRootRoute } from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: () => ( + <React.Fragment> + <div>Hello "__root"!</div> + <Outlet /> + </React.Fragment> + ), +}) diff --git a/packages/router-generator/tests/generator/nested/routes/_pathlessLayout.tsx b/packages/router-generator/tests/generator/nested-verboseFileRoutes-true/routes/_pathlessLayout.tsx similarity index 100% rename from packages/router-generator/tests/generator/nested/routes/_pathlessLayout.tsx rename to packages/router-generator/tests/generator/nested-verboseFileRoutes-true/routes/_pathlessLayout.tsx diff --git a/packages/router-generator/tests/generator/nested/routes/_pathlessLayout/settings.tsx b/packages/router-generator/tests/generator/nested-verboseFileRoutes-true/routes/_pathlessLayout/settings.tsx similarity index 100% rename from packages/router-generator/tests/generator/nested/routes/_pathlessLayout/settings.tsx rename to packages/router-generator/tests/generator/nested-verboseFileRoutes-true/routes/_pathlessLayout/settings.tsx diff --git a/packages/router-generator/tests/generator/nested/routes/blog/$slug.tsx b/packages/router-generator/tests/generator/nested-verboseFileRoutes-true/routes/blog/$slug.tsx similarity index 100% rename from packages/router-generator/tests/generator/nested/routes/blog/$slug.tsx rename to packages/router-generator/tests/generator/nested-verboseFileRoutes-true/routes/blog/$slug.tsx diff --git a/packages/router-generator/tests/generator/nested/routes/blog/index.tsx b/packages/router-generator/tests/generator/nested-verboseFileRoutes-true/routes/blog/index.tsx similarity index 100% rename from packages/router-generator/tests/generator/nested/routes/blog/index.tsx rename to packages/router-generator/tests/generator/nested-verboseFileRoutes-true/routes/blog/index.tsx diff --git a/packages/router-generator/tests/generator/nested/routes/blog/route.tsx b/packages/router-generator/tests/generator/nested-verboseFileRoutes-true/routes/blog/route.tsx similarity index 100% rename from packages/router-generator/tests/generator/nested/routes/blog/route.tsx rename to packages/router-generator/tests/generator/nested-verboseFileRoutes-true/routes/blog/route.tsx diff --git a/packages/router-generator/tests/generator/nested/routes/blog_/$blogId/$slug/route.tsx b/packages/router-generator/tests/generator/nested-verboseFileRoutes-true/routes/blog_/$blogId/$slug/route.tsx similarity index 100% rename from packages/router-generator/tests/generator/nested/routes/blog_/$blogId/$slug/route.tsx rename to packages/router-generator/tests/generator/nested-verboseFileRoutes-true/routes/blog_/$blogId/$slug/route.tsx diff --git a/packages/router-generator/tests/generator/nested/routes/blog_/$blogId/$slug_/bar.tsx b/packages/router-generator/tests/generator/nested-verboseFileRoutes-true/routes/blog_/$blogId/$slug_/bar.tsx similarity index 100% rename from packages/router-generator/tests/generator/nested/routes/blog_/$blogId/$slug_/bar.tsx rename to packages/router-generator/tests/generator/nested-verboseFileRoutes-true/routes/blog_/$blogId/$slug_/bar.tsx diff --git a/packages/router-generator/tests/generator/nested/routes/blog_/$blogId/route.tsx b/packages/router-generator/tests/generator/nested-verboseFileRoutes-true/routes/blog_/$blogId/route.tsx similarity index 100% rename from packages/router-generator/tests/generator/nested/routes/blog_/$blogId/route.tsx rename to packages/router-generator/tests/generator/nested-verboseFileRoutes-true/routes/blog_/$blogId/route.tsx diff --git a/packages/router-generator/tests/generator/nested/routes/blog_/$blogId_/edit.tsx b/packages/router-generator/tests/generator/nested-verboseFileRoutes-true/routes/blog_/$blogId_/edit.tsx similarity index 100% rename from packages/router-generator/tests/generator/nested/routes/blog_/$blogId_/edit.tsx rename to packages/router-generator/tests/generator/nested-verboseFileRoutes-true/routes/blog_/$blogId_/edit.tsx diff --git a/packages/router-generator/tests/generator/nested/routes/blog_/stats.tsx b/packages/router-generator/tests/generator/nested-verboseFileRoutes-true/routes/blog_/stats.tsx similarity index 100% rename from packages/router-generator/tests/generator/nested/routes/blog_/stats.tsx rename to packages/router-generator/tests/generator/nested-verboseFileRoutes-true/routes/blog_/stats.tsx diff --git a/packages/router-generator/tests/generator/nested/routes/index.tsx b/packages/router-generator/tests/generator/nested-verboseFileRoutes-true/routes/index.tsx similarity index 100% rename from packages/router-generator/tests/generator/nested/routes/index.tsx rename to packages/router-generator/tests/generator/nested-verboseFileRoutes-true/routes/index.tsx diff --git a/packages/router-generator/tests/generator/nested/routes/posts/$postId/deep.tsx b/packages/router-generator/tests/generator/nested-verboseFileRoutes-true/routes/posts/$postId/deep.tsx similarity index 100% rename from packages/router-generator/tests/generator/nested/routes/posts/$postId/deep.tsx rename to packages/router-generator/tests/generator/nested-verboseFileRoutes-true/routes/posts/$postId/deep.tsx diff --git a/packages/router-generator/tests/generator/nested/routes/posts/$postId/index.tsx b/packages/router-generator/tests/generator/nested-verboseFileRoutes-true/routes/posts/$postId/index.tsx similarity index 100% rename from packages/router-generator/tests/generator/nested/routes/posts/$postId/index.tsx rename to packages/router-generator/tests/generator/nested-verboseFileRoutes-true/routes/posts/$postId/index.tsx diff --git a/packages/router-generator/tests/generator/nested/routes/posts/index.tsx b/packages/router-generator/tests/generator/nested-verboseFileRoutes-true/routes/posts/index.tsx similarity index 100% rename from packages/router-generator/tests/generator/nested/routes/posts/index.tsx rename to packages/router-generator/tests/generator/nested-verboseFileRoutes-true/routes/posts/index.tsx diff --git a/packages/router-generator/tests/generator/nested/routes/posts/route.tsx b/packages/router-generator/tests/generator/nested-verboseFileRoutes-true/routes/posts/route.tsx similarity index 100% rename from packages/router-generator/tests/generator/nested/routes/posts/route.tsx rename to packages/router-generator/tests/generator/nested-verboseFileRoutes-true/routes/posts/route.tsx diff --git a/packages/router-generator/tests/generator/nested-verboseFileRoutes-true/tests.test-d.ts b/packages/router-generator/tests/generator/nested-verboseFileRoutes-true/tests.test-d.ts new file mode 100644 index 0000000000..47dcc0f5b1 --- /dev/null +++ b/packages/router-generator/tests/generator/nested-verboseFileRoutes-true/tests.test-d.ts @@ -0,0 +1,672 @@ +import { + Link, + createRouter, + redirect, + useLoaderData, + useLoaderDeps, + useMatch, + useNavigate, + useParams, + useRouteContext, + useSearch, +} from '@tanstack/react-router' +import type { FileRoutesByPath, MakeRouteMatch } from '@tanstack/react-router' +import { expectTypeOf, test } from 'vitest' +import { routeTree } from './routeTree.gen' +import type { FileRouteTypes } from './routeTree.gen' + +const defaultRouter = createRouter({ + routeTree, +}) + +type DefaultRouter = typeof defaultRouter + +const alwaysTrailingSlashRouter = createRouter({ + routeTree, + trailingSlash: 'always', +}) + +const neverTrailingSlashRouter = createRouter({ + routeTree, + trailingSlash: 'never', +}) + +const preserveTrailingSlashRouter = createRouter({ + routeTree, + trailingSlash: 'preserve', +}) + +test('when navigating to the root', () => { + // Issue #4892: Pathless layout routes should have fullPath: '/' not '' + expectTypeOf<FileRoutesByPath['/']['fullPath']>().toEqualTypeOf<'/'>() + expectTypeOf< + FileRoutesByPath['/posts/']['fullPath'] + >().toEqualTypeOf<'/posts/'>() + // Issue #6403: Index routes should have trailing slash in fullPath to match runtime + expectTypeOf< + FileRoutesByPath['/posts/$postId/']['fullPath'] + >().toEqualTypeOf<'/posts/$postId/'>() + expectTypeOf< + FileRoutesByPath['/blog/']['fullPath'] + >().toEqualTypeOf<'/blog/'>() + // Verify empty string is not in fullPaths union + expectTypeOf<''>().not.toMatchTypeOf<FileRouteTypes['fullPaths']>() + // Verify pathless layout's fullPath is '/' (not '') + expectTypeOf< + FileRoutesByPath['/_pathlessLayout']['fullPath'] + >().toEqualTypeOf<'/'>() + // Child of pathless layout should have correct fullPath + expectTypeOf< + FileRoutesByPath['/_pathlessLayout/settings']['fullPath'] + >().toEqualTypeOf<'/settings'>() + + expectTypeOf(Link<typeof defaultRouter, '/', '/'>) + .parameter(0) + .toHaveProperty('to') + .toEqualTypeOf< + | '/' + | '/blog' + | '/posts' + | '/blog/$blogId' + | '/blog/$blogId/edit' + | '/blog/$blogId/$slug' + | '/blog/$blogId/$slug/bar' + | '/blog/$slug' + | '/blog/stats' + | '/posts/$postId/deep' + | '/posts/$postId' + | '/settings' + | undefined + >() + + expectTypeOf(Link<typeof alwaysTrailingSlashRouter, '/', '/'>) + .parameter(0) + .toHaveProperty('to') + .toEqualTypeOf< + | '/' + | '/blog/' + | '/posts/' + | '/blog/$blogId/' + | '/blog/$blogId/edit/' + | '/blog/$blogId/$slug/' + | '/blog/$blogId/$slug/bar/' + | '/blog/$slug/' + | '/blog/stats/' + | '/posts/$postId/deep/' + | '/posts/$postId/' + | '/settings/' + | undefined + >() + + expectTypeOf(Link<typeof neverTrailingSlashRouter, '/', '/'>) + .parameter(0) + .toHaveProperty('to') + .toEqualTypeOf< + | '/' + | '/blog' + | '/posts' + | '/blog/$blogId' + | '/blog/$blogId/edit' + | '/blog/$blogId/$slug' + | '/blog/$blogId/$slug/bar' + | '/blog/$slug' + | '/blog/stats' + | '/posts/$postId/deep' + | '/posts/$postId' + | '/settings' + | undefined + >() + + expectTypeOf(Link<typeof preserveTrailingSlashRouter, '/', '/'>) + .parameter(0) + .toHaveProperty('to') + .toEqualTypeOf< + | '/' + | '/blog' + | '/posts' + | '/blog/$blogId' + | '/blog/$blogId/edit' + | '/blog/$blogId/$slug' + | '/blog/$blogId/$slug/bar' + | '/blog/$slug' + | '/blog/stats' + | '/posts/$postId/deep' + | '/posts/$postId' + | '/blog/' + | '/posts/' + | '/blog/$blogId/' + | '/blog/$blogId/edit/' + | '/blog/$blogId/$slug/' + | '/blog/$blogId/$slug/bar/' + | '/blog/$slug/' + | '/blog/stats/' + | '/posts/$postId/deep/' + | '/posts/$postId/' + | '/settings/' + | '/settings' + | undefined + >() + + expectTypeOf(Link<typeof defaultRouter, '/', '/'>) + .parameter(0) + .toHaveProperty('from') + .toEqualTypeOf< + | '/' + | '/blog' + | '/posts' + | '/blog/$blogId' + | '/blog/$blogId/edit' + | '/blog/$blogId/$slug' + | '/blog/$blogId/$slug/bar' + | '/blog/$slug' + | '/blog/stats' + | '/blog/' + | '/posts/' + | '/posts/$postId/deep' + | '/posts/$postId/' + | '/settings' + | undefined + >() + + expectTypeOf(Link<typeof defaultRouter, '/', '/'>) + .parameter(0) + .toHaveProperty('search') + .exclude<(...args: any) => any>() + .toEqualTypeOf<true | {} | undefined>() + + expectTypeOf(Link<typeof alwaysTrailingSlashRouter, '/', '/'>) + .parameter(0) + .toHaveProperty('search') + .exclude<(...args: any) => any>() + .toEqualTypeOf<true | {} | undefined>() + + expectTypeOf(Link<typeof neverTrailingSlashRouter, '/', '/'>) + .parameter(0) + .toHaveProperty('search') + .exclude<(...args: any) => any>() + .toEqualTypeOf<true | {} | undefined>() + + expectTypeOf(Link<typeof preserveTrailingSlashRouter, '/', '/'>) + .parameter(0) + .toHaveProperty('search') + .exclude<(...args: any) => any>() + .toEqualTypeOf<true | {} | undefined>() +}) + +test('when navigating a index route with search and params', () => { + expectTypeOf(Link<typeof defaultRouter, string, '/posts/$postId'>) + .parameter(0) + .toHaveProperty('to') + .toEqualTypeOf< + | '.' + | '..' + | '/' + | '/blog' + | '/posts' + | '/blog/$blogId' + | '/blog/$blogId/edit' + | '/blog/$blogId/$slug' + | '/blog/$blogId/$slug/bar' + | '/blog/$slug' + | '/blog/stats' + | '/posts/$postId/deep' + | '/posts/$postId' + | '/settings' + >() + + expectTypeOf( + Link<typeof alwaysTrailingSlashRouter, string, '/posts/$postId/'>, + ) + .parameter(0) + .toHaveProperty('to') + .toEqualTypeOf< + | './' + | '../' + | '/' + | '/blog/' + | '/posts/' + | '/blog/$blogId/' + | '/blog/$blogId/edit/' + | '/blog/$blogId/$slug/' + | '/blog/$blogId/$slug/bar/' + | '/blog/$slug/' + | '/blog/stats/' + | '/posts/$postId/deep/' + | '/posts/$postId/' + | '/settings/' + >() + + expectTypeOf(Link<typeof neverTrailingSlashRouter, string, '/posts/$postId'>) + .parameter(0) + .toHaveProperty('to') + .toEqualTypeOf< + | '/' + | '/blog' + | '/posts' + | '/blog/$blogId' + | '/blog/$blogId/edit' + | '/blog/$blogId/$slug' + | '/blog/$blogId/$slug/bar' + | '/blog/$slug' + | '/blog/stats' + | '/posts/$postId/deep' + | '/posts/$postId' + | '/settings' + | '.' + | '..' + >() + + expectTypeOf( + Link<typeof preserveTrailingSlashRouter, string, '/posts/$postId'>, + ) + .parameter(0) + .toHaveProperty('to') + .toEqualTypeOf< + | '..' + | '../' + | '.' + | './' + | '/' + | '/blog' + | '/posts' + | '/blog/$blogId' + | '/blog/$blogId/edit' + | '/blog/$blogId/$slug' + | '/blog/$blogId/$slug/bar' + | '/blog/$slug' + | '/blog/stats' + | '/posts/$postId/deep' + | '/posts/$postId' + | '/blog/' + | '/posts/' + | '/blog/$blogId/' + | '/blog/$blogId/edit/' + | '/blog/$blogId/$slug/' + | '/blog/$blogId/$slug/bar/' + | '/blog/$slug/' + | '/blog/stats/' + | '/posts/$postId/deep/' + | '/posts/$postId/' + | '/settings' + | '/settings/' + >() + + expectTypeOf(Link<typeof defaultRouter, '/', '/posts/$postId'>) + .parameter(0) + .toHaveProperty('from') + .toEqualTypeOf< + | '/' + | '/posts/$postId/' + | '/blog' + | '/posts' + | '/blog/$blogId' + | '/blog/$blogId/edit' + | '/blog/$blogId/$slug' + | '/blog/$blogId/$slug/bar' + | '/blog/$slug' + | '/blog/stats' + | '/blog/' + | '/posts/' + | '/posts/$postId/deep' + | '/settings' + | undefined + >() + + expectTypeOf(Link<typeof defaultRouter, string, '/posts/$postId'>) + .parameter(0) + .toHaveProperty('search') + .exclude<(...args: any) => any>() + .toEqualTypeOf<{ indexSearch: string }>() + + expectTypeOf(Link<typeof defaultRouter, string, '/posts/$postId/'>) + .parameter(0) + .toHaveProperty('search') + .exclude<(...args: any) => any>() + .toEqualTypeOf<never>() + + expectTypeOf( + Link<typeof alwaysTrailingSlashRouter, string, '/posts/$postId/'>, + ) + .parameter(0) + .toHaveProperty('search') + .exclude<(...args: any) => any>() + .toEqualTypeOf<{ indexSearch: string }>() + + expectTypeOf(Link<typeof alwaysTrailingSlashRouter, string, '/posts/$postId'>) + .parameter(0) + .toHaveProperty('search') + .exclude<(...args: any) => any>() + .toEqualTypeOf<never>() + + expectTypeOf(Link<typeof neverTrailingSlashRouter, string, '/posts/$postId'>) + .parameter(0) + .toHaveProperty('search') + .exclude<(...args: any) => any>() + .toEqualTypeOf<{ indexSearch: string }>() + + expectTypeOf(Link<typeof preserveTrailingSlashRouter, '/', '/posts/$postId'>) + .parameter(0) + .toHaveProperty('search') + .exclude<(...args: any) => any>() + .toEqualTypeOf<{ indexSearch: string }>() + + expectTypeOf(Link<typeof preserveTrailingSlashRouter, '/', '/posts/$postId/'>) + .parameter(0) + .toHaveProperty('search') + .exclude<(...args: any) => any>() + .toEqualTypeOf<{ indexSearch: string }>() + + expectTypeOf(Link<typeof defaultRouter, string, '/posts/$postId'>) + .parameter(0) + .toHaveProperty('params') + .exclude<(...args: any) => any>() + .toEqualTypeOf<{ postId: string }>() + + expectTypeOf(Link<typeof defaultRouter, string, '/posts/$postId/'>) + .parameter(0) + .toHaveProperty('params') + .exclude<(...args: any) => any>() + .toEqualTypeOf<never>() + + expectTypeOf( + Link<typeof alwaysTrailingSlashRouter, string, '/posts/$postId/'>, + ) + .parameter(0) + .toHaveProperty('params') + .exclude<(...args: any) => any>() + .toEqualTypeOf<{ postId: string }>() + + expectTypeOf(Link<typeof alwaysTrailingSlashRouter, string, '/posts/$postId'>) + .parameter(0) + .toHaveProperty('params') + .exclude<(...args: any) => any>() + .toEqualTypeOf<never>() + + expectTypeOf(Link<typeof neverTrailingSlashRouter, string, '/posts/$postId'>) + .parameter(0) + .toHaveProperty('params') + .exclude<(...args: any) => any>() + .toEqualTypeOf<{ postId: string }>() + + expectTypeOf(Link<typeof preserveTrailingSlashRouter, '/', '/posts/$postId'>) + .parameter(0) + .toHaveProperty('params') + .exclude<(...args: any) => any>() + .toEqualTypeOf<{ postId: string }>() + + expectTypeOf(Link<typeof preserveTrailingSlashRouter, '/', '/posts/$postId/'>) + .parameter(0) + .toHaveProperty('params') + .exclude<(...args: any) => any>() + .toEqualTypeOf<{ postId: string }>() +}) + +test('when navigating from a index route with search and params', () => { + expectTypeOf(Link<typeof defaultRouter, '/posts/$postId/', undefined>) + .parameter(0) + .toHaveProperty('from') + .toEqualTypeOf< + | '/' + | '/posts/$postId/' + | '/blog' + | '/posts' + | '/blog/$blogId' + | '/blog/$blogId/edit' + | '/blog/$blogId/$slug' + | '/blog/$blogId/$slug/bar' + | '/blog/$slug' + | '/blog/stats' + | '/blog/' + | '/posts/' + | '/posts/$postId/deep' + | '/settings' + | undefined + >() + + expectTypeOf(Link<typeof defaultRouter, '/posts/$postId/', undefined>) + .parameter(0) + .toHaveProperty('search') + .parameter(0) + .toEqualTypeOf<{ indexSearch: string }>() +}) + +test('when using useNavigate', () => { + const navigate = useNavigate() + + expectTypeOf(navigate<DefaultRouter, '/'>) + .parameter(0) + .toHaveProperty('to') + .toEqualTypeOf< + | '/' + | '.' + | '..' + | '/blog' + | '/posts' + | '/blog/$blogId' + | '/blog/$blogId/edit' + | '/blog/$blogId/$slug' + | '/blog/$blogId/$slug/bar' + | '/blog/$slug' + | '/blog/stats' + | '/posts/$postId/deep' + | '/posts/$postId' + | '/settings' + >() +}) + +test('when using redirect', () => { + expectTypeOf(redirect<DefaultRouter, '/', '/'>) + .parameter(0) + .toHaveProperty('to') + .toEqualTypeOf< + | '/' + | '/posts/$postId' + | '/blog' + | '/posts' + | '/blog/$blogId' + | '/blog/$blogId/edit' + | '/blog/$blogId/$slug' + | '/blog/$blogId/$slug/bar' + | '/blog/$slug' + | '/blog/stats' + | '/posts/$postId/deep' + | '/settings' + | undefined + >() +}) + +test('when using useSearch from a route with no search', () => { + expectTypeOf(useSearch<DefaultRouter, '/blog'>) + .parameter(0) + .toHaveProperty('from') + .toEqualTypeOf< + | '__root__' + | '/' + | '/blog' + | '/posts' + | '/blog/$slug' + | '/blog_/$blogId' + | '/blog_/$blogId_/edit' + | '/blog_/$blogId/$slug' + | '/blog_/$blogId/$slug_/bar' + | '/blog_/stats' + | '/blog/' + | '/posts/' + | '/posts/$postId/deep' + | '/posts/$postId/' + | '/_pathlessLayout' + | '/_pathlessLayout/settings' + >() + + expectTypeOf(useSearch<DefaultRouter, '/blog'>).returns.toEqualTypeOf<{}>() +}) + +test('when using useSearch from a route with search', () => { + expectTypeOf(useSearch<DefaultRouter, '/blog'>) + .parameter(0) + .toHaveProperty('from') + .toEqualTypeOf< + | '__root__' + | '/' + | '/blog' + | '/posts' + | '/blog/$slug' + | '/blog_/$blogId' + | '/blog_/$blogId_/edit' + | '/blog_/$blogId/$slug' + | '/blog_/$blogId/$slug_/bar' + | '/blog_/stats' + | '/blog/' + | '/posts/' + | '/posts/$postId/deep' + | '/posts/$postId/' + | '/_pathlessLayout' + | '/_pathlessLayout/settings' + >() + + expectTypeOf( + useSearch<DefaultRouter, '/posts/$postId/'>, + ).returns.toEqualTypeOf<{ indexSearch: string }>() +}) + +test('when using useLoaderData from a route with loaderData', () => { + expectTypeOf(useLoaderData<DefaultRouter, '/posts/$postId/deep'>) + .parameter(0) + .toHaveProperty('from') + .toEqualTypeOf< + | '__root__' + | '/' + | '/blog' + | '/posts' + | '/blog/$slug' + | '/blog_/$blogId' + | '/blog_/$blogId_/edit' + | '/blog_/$blogId/$slug' + | '/blog_/$blogId/$slug_/bar' + | '/blog_/stats' + | '/blog/' + | '/posts/' + | '/posts/$postId/deep' + | '/posts/$postId/' + | '/_pathlessLayout' + | '/_pathlessLayout/settings' + >() + + expectTypeOf( + useLoaderData<DefaultRouter, '/posts/$postId/deep'>, + ).returns.toEqualTypeOf<{ data: string }>() +}) + +test('when using useLoaderDeps from a route with loaderDeps', () => { + expectTypeOf(useLoaderDeps<DefaultRouter, '/posts/$postId/deep'>) + .parameter(0) + .toHaveProperty('from') + .toEqualTypeOf< + | '__root__' + | '/' + | '/blog' + | '/posts' + | '/blog/$slug' + | '/blog_/$blogId' + | '/blog_/$blogId_/edit' + | '/blog_/$blogId/$slug' + | '/blog_/$blogId/$slug_/bar' + | '/blog_/stats' + | '/blog/' + | '/posts/' + | '/posts/$postId/deep' + | '/posts/$postId/' + | '/_pathlessLayout' + | '/_pathlessLayout/settings' + >() + + expectTypeOf( + useLoaderDeps<DefaultRouter, '/posts/$postId/deep'>, + ).returns.toEqualTypeOf<{ dep: number }>() +}) + +test('when using useMatch from a route', () => { + expectTypeOf(useMatch<DefaultRouter, '/posts/$postId/deep'>) + .parameter(0) + .toHaveProperty('from') + .toEqualTypeOf< + | '__root__' + | '/' + | '/blog' + | '/posts' + | '/blog/$slug' + | '/blog_/$blogId' + | '/blog_/$blogId_/edit' + | '/blog_/$blogId/$slug' + | '/blog_/$blogId/$slug_/bar' + | '/blog_/stats' + | '/blog/' + | '/posts/' + | '/posts/$postId/deep' + | '/posts/$postId/' + | '/_pathlessLayout' + | '/_pathlessLayout/settings' + >() + + expectTypeOf( + useMatch<DefaultRouter, '/posts/$postId/deep'>, + ).returns.toEqualTypeOf< + MakeRouteMatch<DefaultRouter['routeTree'], '/posts/$postId/deep', true> + >() +}) + +test('when using useParams from a route', () => { + expectTypeOf(useParams<DefaultRouter, '/posts/$postId/deep'>) + .parameter(0) + .toHaveProperty('from') + .toEqualTypeOf< + | '__root__' + | '/' + | '/blog' + | '/posts' + | '/blog/$slug' + | '/blog_/$blogId' + | '/blog_/$blogId_/edit' + | '/blog_/$blogId/$slug' + | '/blog_/$blogId/$slug_/bar' + | '/blog_/stats' + | '/blog/' + | '/posts/' + | '/posts/$postId/deep' + | '/posts/$postId/' + | '/_pathlessLayout' + | '/_pathlessLayout/settings' + >() + + expectTypeOf( + useParams<DefaultRouter, '/posts/$postId/deep'>, + ).returns.toEqualTypeOf<{ postId: string }>() +}) + +test('when using useRouteContext from a route', () => { + expectTypeOf(useRouteContext<DefaultRouter, '/posts/$postId/deep'>) + .parameter(0) + .toHaveProperty('from') + .toEqualTypeOf< + | '__root__' + | '/' + | '/blog' + | '/posts' + | '/blog/$slug' + | '/blog_/$blogId' + | '/blog_/$blogId_/edit' + | '/blog_/$blogId/$slug' + | '/blog_/$blogId/$slug_/bar' + | '/blog_/stats' + | '/blog/' + | '/posts/' + | '/posts/$postId/deep' + | '/posts/$postId/' + | '/_pathlessLayout' + | '/_pathlessLayout/settings' + >() + + expectTypeOf( + useRouteContext<DefaultRouter, '/posts/$postId/deep'>, + ).returns.toEqualTypeOf<{ someContext: string }>() +}) diff --git a/packages/router-generator/tests/generator/nested/routeTree.snapshot.ts b/packages/router-generator/tests/generator/nested/routeTree.snapshot.ts deleted file mode 100644 index 685b1b29ca..0000000000 --- a/packages/router-generator/tests/generator/nested/routeTree.snapshot.ts +++ /dev/null @@ -1,388 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' -import { Route as BlogRouteRouteImport } from './routes/blog/route' -import { Route as PostsRouteRouteImport } from './routes/posts/route' -import { Route as PathlessLayoutSettingsRouteImport } from './routes/_pathlessLayout/settings' -import { Route as BlogIndexRouteImport } from './routes/blog/index' -import { Route as BlogSlugRouteImport } from './routes/blog/$slug' -import { Route as BlogBlogIdRouteRouteImport } from './routes/blog_/$blogId/route' -import { Route as BlogStatsRouteImport } from './routes/blog_/stats' -import { Route as PostsIndexRouteImport } from './routes/posts/index' -import { Route as BlogBlogIdSlugRouteRouteImport } from './routes/blog_/$blogId/$slug/route' -import { Route as BlogBlogIdEditRouteImport } from './routes/blog_/$blogId_/edit' -import { Route as PostsPostIdIndexRouteImport } from './routes/posts/$postId/index' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts/$postId/deep' -import { Route as BlogBlogIdSlugBarRouteImport } from './routes/blog_/$blogId/$slug_/bar' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', - getParentRoute: () => rootRouteImport, -} as any) -const BlogRouteRoute = BlogRouteRouteImport.update({ - id: '/blog', - path: '/blog', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRouteRoute = PostsRouteRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) -const PathlessLayoutSettingsRoute = PathlessLayoutSettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => PathlessLayoutRoute, -} as any) -const BlogIndexRoute = BlogIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => BlogRouteRoute, -} as any) -const BlogSlugRoute = BlogSlugRouteImport.update({ - id: '/$slug', - path: '/$slug', - getParentRoute: () => BlogRouteRoute, -} as any) -const BlogBlogIdRouteRoute = BlogBlogIdRouteRouteImport.update({ - id: '/blog_/$blogId', - path: '/blog/$blogId', - getParentRoute: () => rootRouteImport, -} as any) -const BlogStatsRoute = BlogStatsRouteImport.update({ - id: '/blog_/stats', - path: '/blog/stats', - getParentRoute: () => rootRouteImport, -} as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => PostsRouteRoute, -} as any) -const BlogBlogIdSlugRouteRoute = BlogBlogIdSlugRouteRouteImport.update({ - id: '/$slug', - path: '/$slug', - getParentRoute: () => BlogBlogIdRouteRoute, -} as any) -const BlogBlogIdEditRoute = BlogBlogIdEditRouteImport.update({ - id: '/blog_/$blogId_/edit', - path: '/blog/$blogId/edit', - getParentRoute: () => rootRouteImport, -} as any) -const PostsPostIdIndexRoute = PostsPostIdIndexRouteImport.update({ - id: '/$postId/', - path: '/$postId/', - getParentRoute: () => PostsRouteRoute, -} as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/$postId/deep', - path: '/$postId/deep', - getParentRoute: () => PostsRouteRoute, -} as any) -const BlogBlogIdSlugBarRoute = BlogBlogIdSlugBarRouteImport.update({ - id: '/$slug_/bar', - path: '/$slug/bar', - getParentRoute: () => BlogBlogIdRouteRoute, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/blog': typeof BlogRouteRouteWithChildren - '/posts': typeof PostsRouteRouteWithChildren - '/blog/$blogId': typeof BlogBlogIdRouteRouteWithChildren - '/settings': typeof PathlessLayoutSettingsRoute - '/blog/$slug': typeof BlogSlugRoute - '/blog/stats': typeof BlogStatsRoute - '/blog/': typeof BlogIndexRoute - '/posts/': typeof PostsIndexRoute - '/blog/$blogId/$slug': typeof BlogBlogIdSlugRouteRoute - '/blog/$blogId/edit': typeof BlogBlogIdEditRoute - '/posts/$postId/deep': typeof PostsPostIdDeepRoute - '/posts/$postId/': typeof PostsPostIdIndexRoute - '/blog/$blogId/$slug/bar': typeof BlogBlogIdSlugBarRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/blog/$blogId': typeof BlogBlogIdRouteRouteWithChildren - '/settings': typeof PathlessLayoutSettingsRoute - '/blog/$slug': typeof BlogSlugRoute - '/blog/stats': typeof BlogStatsRoute - '/blog': typeof BlogIndexRoute - '/posts': typeof PostsIndexRoute - '/blog/$blogId/$slug': typeof BlogBlogIdSlugRouteRoute - '/blog/$blogId/edit': typeof BlogBlogIdEditRoute - '/posts/$postId/deep': typeof PostsPostIdDeepRoute - '/posts/$postId': typeof PostsPostIdIndexRoute - '/blog/$blogId/$slug/bar': typeof BlogBlogIdSlugBarRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/blog': typeof BlogRouteRouteWithChildren - '/posts': typeof PostsRouteRouteWithChildren - '/_pathlessLayout': typeof PathlessLayoutRouteWithChildren - '/blog_/$blogId': typeof BlogBlogIdRouteRouteWithChildren - '/_pathlessLayout/settings': typeof PathlessLayoutSettingsRoute - '/blog/$slug': typeof BlogSlugRoute - '/blog_/stats': typeof BlogStatsRoute - '/blog/': typeof BlogIndexRoute - '/posts/': typeof PostsIndexRoute - '/blog_/$blogId/$slug': typeof BlogBlogIdSlugRouteRoute - '/blog_/$blogId_/edit': typeof BlogBlogIdEditRoute - '/posts/$postId/deep': typeof PostsPostIdDeepRoute - '/posts/$postId/': typeof PostsPostIdIndexRoute - '/blog_/$blogId/$slug_/bar': typeof BlogBlogIdSlugBarRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/blog' - | '/posts' - | '/blog/$blogId' - | '/settings' - | '/blog/$slug' - | '/blog/stats' - | '/blog/' - | '/posts/' - | '/blog/$blogId/$slug' - | '/blog/$blogId/edit' - | '/posts/$postId/deep' - | '/posts/$postId/' - | '/blog/$blogId/$slug/bar' - fileRoutesByTo: FileRoutesByTo - to: - | '/' - | '/blog/$blogId' - | '/settings' - | '/blog/$slug' - | '/blog/stats' - | '/blog' - | '/posts' - | '/blog/$blogId/$slug' - | '/blog/$blogId/edit' - | '/posts/$postId/deep' - | '/posts/$postId' - | '/blog/$blogId/$slug/bar' - id: - | '__root__' - | '/' - | '/blog' - | '/posts' - | '/_pathlessLayout' - | '/blog_/$blogId' - | '/_pathlessLayout/settings' - | '/blog/$slug' - | '/blog_/stats' - | '/blog/' - | '/posts/' - | '/blog_/$blogId/$slug' - | '/blog_/$blogId_/edit' - | '/posts/$postId/deep' - | '/posts/$postId/' - | '/blog_/$blogId/$slug_/bar' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - BlogRouteRoute: typeof BlogRouteRouteWithChildren - PostsRouteRoute: typeof PostsRouteRouteWithChildren - PathlessLayoutRoute: typeof PathlessLayoutRouteWithChildren - BlogBlogIdRouteRoute: typeof BlogBlogIdRouteRouteWithChildren - BlogStatsRoute: typeof BlogStatsRoute - BlogBlogIdEditRoute: typeof BlogBlogIdEditRoute -} - -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 - } - '/blog': { - id: '/blog' - path: '/blog' - fullPath: '/blog' - preLoaderRoute: typeof BlogRouteRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteRouteImport - parentRoute: typeof rootRouteImport - } - '/_pathlessLayout/settings': { - id: '/_pathlessLayout/settings' - path: '/settings' - fullPath: '/settings' - preLoaderRoute: typeof PathlessLayoutSettingsRouteImport - parentRoute: typeof PathlessLayoutRoute - } - '/blog/': { - id: '/blog/' - path: '/' - fullPath: '/blog/' - preLoaderRoute: typeof BlogIndexRouteImport - parentRoute: typeof BlogRouteRoute - } - '/blog/$slug': { - id: '/blog/$slug' - path: '/$slug' - fullPath: '/blog/$slug' - preLoaderRoute: typeof BlogSlugRouteImport - parentRoute: typeof BlogRouteRoute - } - '/blog_/$blogId': { - id: '/blog_/$blogId' - path: '/blog/$blogId' - fullPath: '/blog/$blogId' - preLoaderRoute: typeof BlogBlogIdRouteRouteImport - parentRoute: typeof rootRouteImport - } - '/blog_/stats': { - id: '/blog_/stats' - path: '/blog/stats' - fullPath: '/blog/stats' - preLoaderRoute: typeof BlogStatsRouteImport - parentRoute: typeof rootRouteImport - } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRouteRoute - } - '/blog_/$blogId/$slug': { - id: '/blog_/$blogId/$slug' - path: '/$slug' - fullPath: '/blog/$blogId/$slug' - preLoaderRoute: typeof BlogBlogIdSlugRouteRouteImport - parentRoute: typeof BlogBlogIdRouteRoute - } - '/blog_/$blogId_/edit': { - id: '/blog_/$blogId_/edit' - path: '/blog/$blogId/edit' - fullPath: '/blog/$blogId/edit' - preLoaderRoute: typeof BlogBlogIdEditRouteImport - parentRoute: typeof rootRouteImport - } - '/posts/$postId/': { - id: '/posts/$postId/' - path: '/$postId' - fullPath: '/posts/$postId/' - preLoaderRoute: typeof PostsPostIdIndexRouteImport - parentRoute: typeof PostsRouteRoute - } - '/posts/$postId/deep': { - id: '/posts/$postId/deep' - path: '/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport - parentRoute: typeof PostsRouteRoute - } - '/blog_/$blogId/$slug_/bar': { - id: '/blog_/$blogId/$slug_/bar' - path: '/$slug/bar' - fullPath: '/blog/$blogId/$slug/bar' - preLoaderRoute: typeof BlogBlogIdSlugBarRouteImport - parentRoute: typeof BlogBlogIdRouteRoute - } - } -} - -interface BlogRouteRouteChildren { - BlogSlugRoute: typeof BlogSlugRoute - BlogIndexRoute: typeof BlogIndexRoute -} - -const BlogRouteRouteChildren: BlogRouteRouteChildren = { - BlogSlugRoute: BlogSlugRoute, - BlogIndexRoute: BlogIndexRoute, -} - -const BlogRouteRouteWithChildren = BlogRouteRoute._addFileChildren( - BlogRouteRouteChildren, -) - -interface PostsRouteRouteChildren { - PostsIndexRoute: typeof PostsIndexRoute - PostsPostIdDeepRoute: typeof PostsPostIdDeepRoute - PostsPostIdIndexRoute: typeof PostsPostIdIndexRoute -} - -const PostsRouteRouteChildren: PostsRouteRouteChildren = { - PostsIndexRoute: PostsIndexRoute, - PostsPostIdDeepRoute: PostsPostIdDeepRoute, - PostsPostIdIndexRoute: PostsPostIdIndexRoute, -} - -const PostsRouteRouteWithChildren = PostsRouteRoute._addFileChildren( - PostsRouteRouteChildren, -) - -interface PathlessLayoutRouteChildren { - PathlessLayoutSettingsRoute: typeof PathlessLayoutSettingsRoute -} - -const PathlessLayoutRouteChildren: PathlessLayoutRouteChildren = { - PathlessLayoutSettingsRoute: PathlessLayoutSettingsRoute, -} - -const PathlessLayoutRouteWithChildren = PathlessLayoutRoute._addFileChildren( - PathlessLayoutRouteChildren, -) - -interface BlogBlogIdRouteRouteChildren { - BlogBlogIdSlugRouteRoute: typeof BlogBlogIdSlugRouteRoute - BlogBlogIdSlugBarRoute: typeof BlogBlogIdSlugBarRoute -} - -const BlogBlogIdRouteRouteChildren: BlogBlogIdRouteRouteChildren = { - BlogBlogIdSlugRouteRoute: BlogBlogIdSlugRouteRoute, - BlogBlogIdSlugBarRoute: BlogBlogIdSlugBarRoute, -} - -const BlogBlogIdRouteRouteWithChildren = BlogBlogIdRouteRoute._addFileChildren( - BlogBlogIdRouteRouteChildren, -) - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - BlogRouteRoute: BlogRouteRouteWithChildren, - PostsRouteRoute: PostsRouteRouteWithChildren, - PathlessLayoutRoute: PathlessLayoutRouteWithChildren, - BlogBlogIdRouteRoute: BlogBlogIdRouteRouteWithChildren, - BlogStatsRoute: BlogStatsRoute, - BlogBlogIdEditRoute: BlogBlogIdEditRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes<FileRouteTypes>() diff --git a/packages/router-generator/tests/generator/numbers-in-path/routeTree.snapshot.ts b/packages/router-generator/tests/generator/numbers-in-path/routeTree.snapshot.ts index 826e1b8b4f..76af935401 100644 --- a/packages/router-generator/tests/generator/numbers-in-path/routeTree.snapshot.ts +++ b/packages/router-generator/tests/generator/numbers-in-path/routeTree.snapshot.ts @@ -9,15 +9,15 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as R03RouteImport } from './routes/03' import { Route as AboutRouteImport } from './routes/about' -import { Route as R01ExampleIndexRouteImport } from './routes/01-example/index' +import { Route as R03RouteImport } from './routes/03' +import { Route as IndexRouteImport } from './routes/index' import { Route as R02IndexRouteImport } from './routes/02.index' +import { Route as R01ExampleIndexRouteImport } from './routes/01-example/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', getParentRoute: () => rootRouteImport, } as any) const R03Route = R03RouteImport.update({ @@ -25,14 +25,9 @@ const R03Route = R03RouteImport.update({ path: '/03', getParentRoute: () => rootRouteImport, } as any) -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) -const R01ExampleIndexRoute = R01ExampleIndexRouteImport.update({ - id: '/01-example/', - path: '/01-example/', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const R02IndexRoute = R02IndexRouteImport.update({ @@ -40,6 +35,11 @@ const R02IndexRoute = R02IndexRouteImport.update({ path: '/02/', getParentRoute: () => rootRouteImport, } as any) +const R01ExampleIndexRoute = R01ExampleIndexRouteImport.update({ + id: '/01-example/', + path: '/01-example/', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -81,11 +81,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport parentRoute: typeof rootRouteImport } '/03': { @@ -95,18 +95,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof R03RouteImport parentRoute: typeof rootRouteImport } - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } - '/01-example/': { - id: '/01-example/' - path: '/01-example' - fullPath: '/01-example/' - preLoaderRoute: typeof R01ExampleIndexRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/02/': { @@ -116,6 +109,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof R02IndexRouteImport parentRoute: typeof rootRouteImport } + '/01-example/': { + id: '/01-example/' + path: '/01-example' + fullPath: '/01-example/' + preLoaderRoute: typeof R01ExampleIndexRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/packages/router-generator/tests/generator/pathless-to-index-preference/routeTree.snapshot.ts b/packages/router-generator/tests/generator/pathless-to-index-preference/routeTree.snapshot.ts deleted file mode 100644 index e9c9d6fac6..0000000000 --- a/packages/router-generator/tests/generator/pathless-to-index-preference/routeTree.snapshot.ts +++ /dev/null @@ -1,147 +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 LivestockFarmIdMedicineRouteRouteImport } from './routes/livestock/$farmId/medicine/route' -import { Route as LivestockFarmIdMedicineIndexRouteImport } from './routes/livestock/$farmId/medicine/index' -import { Route as LivestockFarmIdMedicineFormRouteImport } from './routes/livestock/$farmId/medicine/_form' -import { Route as LivestockFarmIdMedicineFormNewRouteImport } from './routes/livestock/$farmId/medicine/_form.new' - -const LivestockFarmIdMedicineRouteRoute = - LivestockFarmIdMedicineRouteRouteImport.update({ - id: '/livestock/$farmId/medicine', - path: '/livestock/$farmId/medicine', - getParentRoute: () => rootRouteImport, - } as any) -const LivestockFarmIdMedicineIndexRoute = - LivestockFarmIdMedicineIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => LivestockFarmIdMedicineRouteRoute, - } as any) -const LivestockFarmIdMedicineFormRoute = - LivestockFarmIdMedicineFormRouteImport.update({ - id: '/_form', - getParentRoute: () => LivestockFarmIdMedicineRouteRoute, - } as any) -const LivestockFarmIdMedicineFormNewRoute = - LivestockFarmIdMedicineFormNewRouteImport.update({ - id: '/new', - path: '/new', - getParentRoute: () => LivestockFarmIdMedicineFormRoute, - } as any) - -export interface FileRoutesByFullPath { - '/livestock/$farmId/medicine': typeof LivestockFarmIdMedicineRouteRouteWithChildren - '/livestock/$farmId/medicine/': typeof LivestockFarmIdMedicineIndexRoute - '/livestock/$farmId/medicine/new': typeof LivestockFarmIdMedicineFormNewRoute -} -export interface FileRoutesByTo { - '/livestock/$farmId/medicine': typeof LivestockFarmIdMedicineIndexRoute - '/livestock/$farmId/medicine/new': typeof LivestockFarmIdMedicineFormNewRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/livestock/$farmId/medicine': typeof LivestockFarmIdMedicineRouteRouteWithChildren - '/livestock/$farmId/medicine/_form': typeof LivestockFarmIdMedicineFormRouteWithChildren - '/livestock/$farmId/medicine/': typeof LivestockFarmIdMedicineIndexRoute - '/livestock/$farmId/medicine/_form/new': typeof LivestockFarmIdMedicineFormNewRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/livestock/$farmId/medicine' - | '/livestock/$farmId/medicine/' - | '/livestock/$farmId/medicine/new' - fileRoutesByTo: FileRoutesByTo - to: '/livestock/$farmId/medicine' | '/livestock/$farmId/medicine/new' - id: - | '__root__' - | '/livestock/$farmId/medicine' - | '/livestock/$farmId/medicine/_form' - | '/livestock/$farmId/medicine/' - | '/livestock/$farmId/medicine/_form/new' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - LivestockFarmIdMedicineRouteRoute: typeof LivestockFarmIdMedicineRouteRouteWithChildren -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/livestock/$farmId/medicine': { - id: '/livestock/$farmId/medicine' - path: '/livestock/$farmId/medicine' - fullPath: '/livestock/$farmId/medicine' - preLoaderRoute: typeof LivestockFarmIdMedicineRouteRouteImport - parentRoute: typeof rootRouteImport - } - '/livestock/$farmId/medicine/': { - id: '/livestock/$farmId/medicine/' - path: '/' - fullPath: '/livestock/$farmId/medicine/' - preLoaderRoute: typeof LivestockFarmIdMedicineIndexRouteImport - parentRoute: typeof LivestockFarmIdMedicineRouteRoute - } - '/livestock/$farmId/medicine/_form': { - id: '/livestock/$farmId/medicine/_form' - path: '' - fullPath: '/livestock/$farmId/medicine' - preLoaderRoute: typeof LivestockFarmIdMedicineFormRouteImport - parentRoute: typeof LivestockFarmIdMedicineRouteRoute - } - '/livestock/$farmId/medicine/_form/new': { - id: '/livestock/$farmId/medicine/_form/new' - path: '/new' - fullPath: '/livestock/$farmId/medicine/new' - preLoaderRoute: typeof LivestockFarmIdMedicineFormNewRouteImport - parentRoute: typeof LivestockFarmIdMedicineFormRoute - } - } -} - -interface LivestockFarmIdMedicineFormRouteChildren { - LivestockFarmIdMedicineFormNewRoute: typeof LivestockFarmIdMedicineFormNewRoute -} - -const LivestockFarmIdMedicineFormRouteChildren: LivestockFarmIdMedicineFormRouteChildren = - { - LivestockFarmIdMedicineFormNewRoute: LivestockFarmIdMedicineFormNewRoute, - } - -const LivestockFarmIdMedicineFormRouteWithChildren = - LivestockFarmIdMedicineFormRoute._addFileChildren( - LivestockFarmIdMedicineFormRouteChildren, - ) - -interface LivestockFarmIdMedicineRouteRouteChildren { - LivestockFarmIdMedicineFormRoute: typeof LivestockFarmIdMedicineFormRouteWithChildren - LivestockFarmIdMedicineIndexRoute: typeof LivestockFarmIdMedicineIndexRoute -} - -const LivestockFarmIdMedicineRouteRouteChildren: LivestockFarmIdMedicineRouteRouteChildren = - { - LivestockFarmIdMedicineFormRoute: - LivestockFarmIdMedicineFormRouteWithChildren, - LivestockFarmIdMedicineIndexRoute: LivestockFarmIdMedicineIndexRoute, - } - -const LivestockFarmIdMedicineRouteRouteWithChildren = - LivestockFarmIdMedicineRouteRoute._addFileChildren( - LivestockFarmIdMedicineRouteRouteChildren, - ) - -const rootRouteChildren: RootRouteChildren = { - LivestockFarmIdMedicineRouteRoute: - LivestockFarmIdMedicineRouteRouteWithChildren, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes<FileRouteTypes>() diff --git a/packages/router-generator/tests/generator/pathless-to-index-preference/routes/__root.tsx b/packages/router-generator/tests/generator/pathless-to-index-preference/routes/__root.tsx deleted file mode 100644 index 742d24a4ea..0000000000 --- a/packages/router-generator/tests/generator/pathless-to-index-preference/routes/__root.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { Outlet, createRootRoute } from '@tanstack/react-router' - -export const Route = createRootRoute({ - component: () => <Outlet />, -}) diff --git a/packages/router-generator/tests/generator/pathless-to-index-preference/routes/livestock/$farmId/medicine/_form.new.tsx b/packages/router-generator/tests/generator/pathless-to-index-preference/routes/livestock/$farmId/medicine/_form.new.tsx deleted file mode 100644 index 0a7a240962..0000000000 --- a/packages/router-generator/tests/generator/pathless-to-index-preference/routes/livestock/$farmId/medicine/_form.new.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/livestock/$farmId/medicine/_form/new')({ - component: () => <div>New medicine</div>, -}) diff --git a/packages/router-generator/tests/generator/pathless-to-index-preference/routes/livestock/$farmId/medicine/_form.tsx b/packages/router-generator/tests/generator/pathless-to-index-preference/routes/livestock/$farmId/medicine/_form.tsx deleted file mode 100644 index 2fe794b8b3..0000000000 --- a/packages/router-generator/tests/generator/pathless-to-index-preference/routes/livestock/$farmId/medicine/_form.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/livestock/$farmId/medicine/_form')({ - component: () => <Outlet />, -}) diff --git a/packages/router-generator/tests/generator/pathless-to-index-preference/routes/livestock/$farmId/medicine/index.tsx b/packages/router-generator/tests/generator/pathless-to-index-preference/routes/livestock/$farmId/medicine/index.tsx deleted file mode 100644 index 13b4c3fb13..0000000000 --- a/packages/router-generator/tests/generator/pathless-to-index-preference/routes/livestock/$farmId/medicine/index.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/livestock/$farmId/medicine/')({ - component: () => <div>Medicine index</div>, -}) diff --git a/packages/router-generator/tests/generator/pathless-to-index-preference/routes/livestock/$farmId/medicine/route.tsx b/packages/router-generator/tests/generator/pathless-to-index-preference/routes/livestock/$farmId/medicine/route.tsx deleted file mode 100644 index e1ef4d5afc..0000000000 --- a/packages/router-generator/tests/generator/pathless-to-index-preference/routes/livestock/$farmId/medicine/route.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/livestock/$farmId/medicine')({ - component: () => <Outlet />, -}) diff --git a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routeTree.snapshot.ts b/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routeTree.snapshot.ts deleted file mode 100644 index 7c7789143a..0000000000 --- a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routeTree.snapshot.ts +++ /dev/null @@ -1,471 +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 Char91__rootIndexChar93IndexRouteImport } from './routes/[__root-index]/index' -import { Route as _layoutRouteImport } from './routes/__layout' -import { Route as Char91__literalChar93RouteImport } from './routes/[__literal]' -import { Route as FooRouteImport } from './routes/[_]foo' -import { Route as LayoutRouteImport } from './routes/_layout' -import { Route as _layoutQuxRouteImport } from './routes/__layout/[_]qux' -import { Route as LayoutChar91__doubleChar93RouteImport } from './routes/_layout/[__double]' -import { Route as Layout_nested2RouteImport } from './routes/_layout/__nested2' -import { Route as LayoutBarRouteImport } from './routes/_layout/[_]bar' -import { Route as LayoutNestedRouteImport } from './routes/_layout/_nested' -import { Route as RootIndexIndexRouteImport } from './routes/[_]root-index/index' -import { Route as LayoutChar91__doubleIndexChar93IndexRouteImport } from './routes/_layout/[__double-index]/index' -import { Route as LayoutChar91__doubleIndexChar93IdRouteImport } from './routes/_layout/[__double-index]/$id' -import { Route as Layout_nested2DeepRouteImport } from './routes/_layout/__nested2/[_]deep' -import { Route as LayoutNestedIndexIndexRouteImport } from './routes/_layout/[_]nested-index/index' -import { Route as LayoutNestedIndexIdRouteImport } from './routes/_layout/[_]nested-index/$id' -import { Route as LayoutNestedBazRouteImport } from './routes/_layout/_nested/[_]baz' -import { Route as LayoutNestedTrailingIndexRouteImport } from './routes/_layout/nested-trailing[_]/index' -import { Route as LayoutNestedDeepIndexIndexRouteImport } from './routes/_layout/_nested/[_]deep-index/index' - -const Char91__rootIndexChar93IndexRoute = - Char91__rootIndexChar93IndexRouteImport.update({ - id: '/__root-index/', - path: '/__root-index/', - getParentRoute: () => rootRouteImport, - } as any) -const _layoutRoute = _layoutRouteImport.update({ - id: '/__layout', - getParentRoute: () => rootRouteImport, -} as any) -const Char91__literalChar93Route = Char91__literalChar93RouteImport.update({ - id: '/__literal', - path: '/__literal', - getParentRoute: () => rootRouteImport, -} as any) -const FooRoute = FooRouteImport.update({ - id: '/_foo', - path: '/_foo', - getParentRoute: () => rootRouteImport, -} as any) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', - getParentRoute: () => rootRouteImport, -} as any) -const _layoutQuxRoute = _layoutQuxRouteImport.update({ - id: '/_qux', - path: '/_qux', - getParentRoute: () => _layoutRoute, -} as any) -const LayoutChar91__doubleChar93Route = - LayoutChar91__doubleChar93RouteImport.update({ - id: '/__double', - path: '/__double', - getParentRoute: () => LayoutRoute, - } as any) -const Layout_nested2Route = Layout_nested2RouteImport.update({ - id: '/__nested2', - getParentRoute: () => LayoutRoute, -} as any) -const LayoutBarRoute = LayoutBarRouteImport.update({ - id: '/_bar', - path: '/_bar', - getParentRoute: () => LayoutRoute, -} as any) -const LayoutNestedRoute = LayoutNestedRouteImport.update({ - id: '/_nested', - getParentRoute: () => LayoutRoute, -} as any) -const RootIndexIndexRoute = RootIndexIndexRouteImport.update({ - id: '/_root-index/', - path: '/_root-index/', - getParentRoute: () => rootRouteImport, -} as any) -const LayoutChar91__doubleIndexChar93IndexRoute = - LayoutChar91__doubleIndexChar93IndexRouteImport.update({ - id: '/__double-index/', - path: '/__double-index/', - getParentRoute: () => LayoutRoute, - } as any) -const LayoutChar91__doubleIndexChar93IdRoute = - LayoutChar91__doubleIndexChar93IdRouteImport.update({ - id: '/__double-index/$id', - path: '/__double-index/$id', - getParentRoute: () => LayoutRoute, - } as any) -const Layout_nested2DeepRoute = Layout_nested2DeepRouteImport.update({ - id: '/_deep', - path: '/_deep', - getParentRoute: () => Layout_nested2Route, -} as any) -const LayoutNestedIndexIndexRoute = LayoutNestedIndexIndexRouteImport.update({ - id: '/_nested-index/', - path: '/_nested-index/', - getParentRoute: () => LayoutRoute, -} as any) -const LayoutNestedIndexIdRoute = LayoutNestedIndexIdRouteImport.update({ - id: '/_nested-index/$id', - path: '/_nested-index/$id', - getParentRoute: () => LayoutRoute, -} as any) -const LayoutNestedBazRoute = LayoutNestedBazRouteImport.update({ - id: '/_baz', - path: '/_baz', - getParentRoute: () => LayoutNestedRoute, -} as any) -const LayoutNestedTrailingIndexRoute = - LayoutNestedTrailingIndexRouteImport.update({ - id: '/nested-trailing_/', - path: '/nested-trailing_/', - getParentRoute: () => LayoutRoute, - } as any) -const LayoutNestedDeepIndexIndexRoute = - LayoutNestedDeepIndexIndexRouteImport.update({ - id: '/_deep-index/', - path: '/_deep-index/', - getParentRoute: () => LayoutNestedRoute, - } as any) - -export interface FileRoutesByFullPath { - '/': typeof LayoutNestedRouteWithChildren - '/__literal': typeof Char91__literalChar93Route - '/_foo': typeof FooRoute - '/_qux': typeof _layoutQuxRoute - '/__double': typeof LayoutChar91__doubleChar93Route - '/_bar': typeof LayoutBarRoute - '/__root-index/': typeof Char91__rootIndexChar93IndexRoute - '/_root-index/': typeof RootIndexIndexRoute - '/__double-index/$id': typeof LayoutChar91__doubleIndexChar93IdRoute - '/_deep': typeof Layout_nested2DeepRoute - '/_nested-index/$id': typeof LayoutNestedIndexIdRoute - '/_baz': typeof LayoutNestedBazRoute - '/__double-index/': typeof LayoutChar91__doubleIndexChar93IndexRoute - '/_nested-index/': typeof LayoutNestedIndexIndexRoute - '/nested-trailing_/': typeof LayoutNestedTrailingIndexRoute - '/_deep-index/': typeof LayoutNestedDeepIndexIndexRoute -} -export interface FileRoutesByTo { - '/': typeof LayoutNestedRouteWithChildren - '/__literal': typeof Char91__literalChar93Route - '/_foo': typeof FooRoute - '/_qux': typeof _layoutQuxRoute - '/__double': typeof LayoutChar91__doubleChar93Route - '/_bar': typeof LayoutBarRoute - '/__root-index': typeof Char91__rootIndexChar93IndexRoute - '/_root-index': typeof RootIndexIndexRoute - '/__double-index/$id': typeof LayoutChar91__doubleIndexChar93IdRoute - '/_deep': typeof Layout_nested2DeepRoute - '/_nested-index/$id': typeof LayoutNestedIndexIdRoute - '/_baz': typeof LayoutNestedBazRoute - '/__double-index': typeof LayoutChar91__doubleIndexChar93IndexRoute - '/_nested-index': typeof LayoutNestedIndexIndexRoute - '/nested-trailing_': typeof LayoutNestedTrailingIndexRoute - '/_deep-index': typeof LayoutNestedDeepIndexIndexRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/__layout': typeof _layoutRouteWithChildren - '/__literal': typeof Char91__literalChar93Route - '/_foo': typeof FooRoute - '/_layout': typeof LayoutRouteWithChildren - '/__layout/_qux': typeof _layoutQuxRoute - '/_layout/__double': typeof LayoutChar91__doubleChar93Route - '/_layout/__nested2': typeof Layout_nested2RouteWithChildren - '/_layout/_bar': typeof LayoutBarRoute - '/_layout/_nested': typeof LayoutNestedRouteWithChildren - '/__root-index/': typeof Char91__rootIndexChar93IndexRoute - '/_root-index/': typeof RootIndexIndexRoute - '/_layout/__double-index/$id': typeof LayoutChar91__doubleIndexChar93IdRoute - '/_layout/__nested2/_deep': typeof Layout_nested2DeepRoute - '/_layout/_nested-index/$id': typeof LayoutNestedIndexIdRoute - '/_layout/_nested/_baz': typeof LayoutNestedBazRoute - '/_layout/__double-index/': typeof LayoutChar91__doubleIndexChar93IndexRoute - '/_layout/_nested-index/': typeof LayoutNestedIndexIndexRoute - '/_layout/nested-trailing_/': typeof LayoutNestedTrailingIndexRoute - '/_layout/_nested/_deep-index/': typeof LayoutNestedDeepIndexIndexRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/__literal' - | '/_foo' - | '/_qux' - | '/__double' - | '/_bar' - | '/__root-index/' - | '/_root-index/' - | '/__double-index/$id' - | '/_deep' - | '/_nested-index/$id' - | '/_baz' - | '/__double-index/' - | '/_nested-index/' - | '/nested-trailing_/' - | '/_deep-index/' - fileRoutesByTo: FileRoutesByTo - to: - | '/' - | '/__literal' - | '/_foo' - | '/_qux' - | '/__double' - | '/_bar' - | '/__root-index' - | '/_root-index' - | '/__double-index/$id' - | '/_deep' - | '/_nested-index/$id' - | '/_baz' - | '/__double-index' - | '/_nested-index' - | '/nested-trailing_' - | '/_deep-index' - id: - | '__root__' - | '/__layout' - | '/__literal' - | '/_foo' - | '/_layout' - | '/__layout/_qux' - | '/_layout/__double' - | '/_layout/__nested2' - | '/_layout/_bar' - | '/_layout/_nested' - | '/__root-index/' - | '/_root-index/' - | '/_layout/__double-index/$id' - | '/_layout/__nested2/_deep' - | '/_layout/_nested-index/$id' - | '/_layout/_nested/_baz' - | '/_layout/__double-index/' - | '/_layout/_nested-index/' - | '/_layout/nested-trailing_/' - | '/_layout/_nested/_deep-index/' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - _layoutRoute: typeof _layoutRouteWithChildren - Char91__literalChar93Route: typeof Char91__literalChar93Route - FooRoute: typeof FooRoute - LayoutRoute: typeof LayoutRouteWithChildren - Char91__rootIndexChar93IndexRoute: typeof Char91__rootIndexChar93IndexRoute - RootIndexIndexRoute: typeof RootIndexIndexRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/__root-index/': { - id: '/__root-index/' - path: '/__root-index' - fullPath: '/__root-index/' - preLoaderRoute: typeof Char91__rootIndexChar93IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/__layout': { - id: '/__layout' - path: '' - fullPath: '/' - preLoaderRoute: typeof _layoutRouteImport - parentRoute: typeof rootRouteImport - } - '/__literal': { - id: '/__literal' - path: '/__literal' - fullPath: '/__literal' - preLoaderRoute: typeof Char91__literalChar93RouteImport - parentRoute: typeof rootRouteImport - } - '/_foo': { - id: '/_foo' - path: '/_foo' - fullPath: '/_foo' - preLoaderRoute: typeof FooRouteImport - parentRoute: typeof rootRouteImport - } - '/_layout': { - id: '/_layout' - path: '' - fullPath: '/' - preLoaderRoute: typeof LayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/__layout/_qux': { - id: '/__layout/_qux' - path: '/_qux' - fullPath: '/_qux' - preLoaderRoute: typeof _layoutQuxRouteImport - parentRoute: typeof _layoutRoute - } - '/_layout/__double': { - id: '/_layout/__double' - path: '/__double' - fullPath: '/__double' - preLoaderRoute: typeof LayoutChar91__doubleChar93RouteImport - parentRoute: typeof LayoutRoute - } - '/_layout/__nested2': { - id: '/_layout/__nested2' - path: '' - fullPath: '/' - preLoaderRoute: typeof Layout_nested2RouteImport - parentRoute: typeof LayoutRoute - } - '/_layout/_bar': { - id: '/_layout/_bar' - path: '/_bar' - fullPath: '/_bar' - preLoaderRoute: typeof LayoutBarRouteImport - parentRoute: typeof LayoutRoute - } - '/_layout/_nested': { - id: '/_layout/_nested' - path: '' - fullPath: '/' - preLoaderRoute: typeof LayoutNestedRouteImport - parentRoute: typeof LayoutRoute - } - '/_root-index/': { - id: '/_root-index/' - path: '/_root-index' - fullPath: '/_root-index/' - preLoaderRoute: typeof RootIndexIndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_layout/__double-index/': { - id: '/_layout/__double-index/' - path: '/__double-index' - fullPath: '/__double-index/' - preLoaderRoute: typeof LayoutChar91__doubleIndexChar93IndexRouteImport - parentRoute: typeof LayoutRoute - } - '/_layout/__double-index/$id': { - id: '/_layout/__double-index/$id' - path: '/__double-index/$id' - fullPath: '/__double-index/$id' - preLoaderRoute: typeof LayoutChar91__doubleIndexChar93IdRouteImport - parentRoute: typeof LayoutRoute - } - '/_layout/__nested2/_deep': { - id: '/_layout/__nested2/_deep' - path: '/_deep' - fullPath: '/_deep' - preLoaderRoute: typeof Layout_nested2DeepRouteImport - parentRoute: typeof Layout_nested2Route - } - '/_layout/_nested-index/': { - id: '/_layout/_nested-index/' - path: '/_nested-index' - fullPath: '/_nested-index/' - preLoaderRoute: typeof LayoutNestedIndexIndexRouteImport - parentRoute: typeof LayoutRoute - } - '/_layout/_nested-index/$id': { - id: '/_layout/_nested-index/$id' - path: '/_nested-index/$id' - fullPath: '/_nested-index/$id' - preLoaderRoute: typeof LayoutNestedIndexIdRouteImport - parentRoute: typeof LayoutRoute - } - '/_layout/_nested/_baz': { - id: '/_layout/_nested/_baz' - path: '/_baz' - fullPath: '/_baz' - preLoaderRoute: typeof LayoutNestedBazRouteImport - parentRoute: typeof LayoutNestedRoute - } - '/_layout/nested-trailing_/': { - id: '/_layout/nested-trailing_/' - path: '/nested-trailing_' - fullPath: '/nested-trailing_/' - preLoaderRoute: typeof LayoutNestedTrailingIndexRouteImport - parentRoute: typeof LayoutRoute - } - '/_layout/_nested/_deep-index/': { - id: '/_layout/_nested/_deep-index/' - path: '/_deep-index' - fullPath: '/_deep-index/' - preLoaderRoute: typeof LayoutNestedDeepIndexIndexRouteImport - parentRoute: typeof LayoutNestedRoute - } - } -} - -interface _layoutRouteChildren { - _layoutQuxRoute: typeof _layoutQuxRoute -} - -const _layoutRouteChildren: _layoutRouteChildren = { - _layoutQuxRoute: _layoutQuxRoute, -} - -const _layoutRouteWithChildren = - _layoutRoute._addFileChildren(_layoutRouteChildren) - -interface Layout_nested2RouteChildren { - Layout_nested2DeepRoute: typeof Layout_nested2DeepRoute -} - -const Layout_nested2RouteChildren: Layout_nested2RouteChildren = { - Layout_nested2DeepRoute: Layout_nested2DeepRoute, -} - -const Layout_nested2RouteWithChildren = Layout_nested2Route._addFileChildren( - Layout_nested2RouteChildren, -) - -interface LayoutNestedRouteChildren { - LayoutNestedBazRoute: typeof LayoutNestedBazRoute - LayoutNestedDeepIndexIndexRoute: typeof LayoutNestedDeepIndexIndexRoute -} - -const LayoutNestedRouteChildren: LayoutNestedRouteChildren = { - LayoutNestedBazRoute: LayoutNestedBazRoute, - LayoutNestedDeepIndexIndexRoute: LayoutNestedDeepIndexIndexRoute, -} - -const LayoutNestedRouteWithChildren = LayoutNestedRoute._addFileChildren( - LayoutNestedRouteChildren, -) - -interface LayoutRouteChildren { - LayoutChar91__doubleChar93Route: typeof LayoutChar91__doubleChar93Route - Layout_nested2Route: typeof Layout_nested2RouteWithChildren - LayoutBarRoute: typeof LayoutBarRoute - LayoutNestedRoute: typeof LayoutNestedRouteWithChildren - LayoutChar91__doubleIndexChar93IdRoute: typeof LayoutChar91__doubleIndexChar93IdRoute - LayoutNestedIndexIdRoute: typeof LayoutNestedIndexIdRoute - LayoutChar91__doubleIndexChar93IndexRoute: typeof LayoutChar91__doubleIndexChar93IndexRoute - LayoutNestedIndexIndexRoute: typeof LayoutNestedIndexIndexRoute - LayoutNestedTrailingIndexRoute: typeof LayoutNestedTrailingIndexRoute -} - -const LayoutRouteChildren: LayoutRouteChildren = { - LayoutChar91__doubleChar93Route: LayoutChar91__doubleChar93Route, - Layout_nested2Route: Layout_nested2RouteWithChildren, - LayoutBarRoute: LayoutBarRoute, - LayoutNestedRoute: LayoutNestedRouteWithChildren, - LayoutChar91__doubleIndexChar93IdRoute: - LayoutChar91__doubleIndexChar93IdRoute, - LayoutNestedIndexIdRoute: LayoutNestedIndexIdRoute, - LayoutChar91__doubleIndexChar93IndexRoute: - LayoutChar91__doubleIndexChar93IndexRoute, - LayoutNestedIndexIndexRoute: LayoutNestedIndexIndexRoute, - LayoutNestedTrailingIndexRoute: LayoutNestedTrailingIndexRoute, -} - -const LayoutRouteWithChildren = - LayoutRoute._addFileChildren(LayoutRouteChildren) - -const rootRouteChildren: RootRouteChildren = { - _layoutRoute: _layoutRouteWithChildren, - Char91__literalChar93Route: Char91__literalChar93Route, - FooRoute: FooRoute, - LayoutRoute: LayoutRouteWithChildren, - Char91__rootIndexChar93IndexRoute: Char91__rootIndexChar93IndexRoute, - RootIndexIndexRoute: RootIndexIndexRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes<FileRouteTypes>() diff --git a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/[_]foo.tsx b/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/[_]foo.tsx deleted file mode 100644 index e081df4ce5..0000000000 --- a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/[_]foo.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_foo')({ - component: () => 'Foo', -}) diff --git a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/[_]root-index/index.tsx b/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/[_]root-index/index.tsx deleted file mode 100644 index 39387c7250..0000000000 --- a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/[_]root-index/index.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_root-index/')({ - component: () => 'Root Index', -}) diff --git a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/[__literal].tsx b/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/[__literal].tsx deleted file mode 100644 index 3e2dece810..0000000000 --- a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/[__literal].tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/__literal')({ - component: () => 'Literal Double Underscore', -}) diff --git a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/[__root-index]/index.tsx b/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/[__root-index]/index.tsx deleted file mode 100644 index 9945c7d300..0000000000 --- a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/[__root-index]/index.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/__root-index/')({ - component: () => 'Double Root Index', -}) diff --git a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/__layout.tsx b/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/__layout.tsx deleted file mode 100644 index 82f96a7448..0000000000 --- a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/__layout.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/__layout')({ - component: () => 'Double Underscore Layout', -}) diff --git a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/__layout/[_]qux.tsx b/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/__layout/[_]qux.tsx deleted file mode 100644 index a75019e05a..0000000000 --- a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/__layout/[_]qux.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/__layout/_qux')({ - component: () => 'Qux', -}) diff --git a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/__root.tsx b/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/__root.tsx deleted file mode 100644 index 9c657c7d5b..0000000000 --- a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/__root.tsx +++ /dev/null @@ -1,3 +0,0 @@ -import { createRootRoute } from '@tanstack/react-router' - -export const Route = createRootRoute() diff --git a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/_layout.tsx b/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/_layout.tsx deleted file mode 100644 index 9c1673dafd..0000000000 --- a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/_layout.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_layout')({ - component: () => 'Layout', -}) diff --git a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/_layout/[_]bar.tsx b/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/_layout/[_]bar.tsx deleted file mode 100644 index c1c8b28c28..0000000000 --- a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/_layout/[_]bar.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_layout/_bar')({ - component: () => 'Bar', -}) diff --git a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/_layout/[_]nested-index/$id.tsx b/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/_layout/[_]nested-index/$id.tsx deleted file mode 100644 index e09396020b..0000000000 --- a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/_layout/[_]nested-index/$id.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_layout/_nested-index/$id')({ - component: () => 'Nested Id', -}) diff --git a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/_layout/[_]nested-index/index.tsx b/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/_layout/[_]nested-index/index.tsx deleted file mode 100644 index a5f8f95497..0000000000 --- a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/_layout/[_]nested-index/index.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_layout/_nested-index/')({ - component: () => 'Nested Index', -}) diff --git a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/_layout/[__double-index]/$id.tsx b/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/_layout/[__double-index]/$id.tsx deleted file mode 100644 index 2a31adf60c..0000000000 --- a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/_layout/[__double-index]/$id.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_layout/__double-index/$id')({ - component: () => 'Double Id', -}) diff --git a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/_layout/[__double-index]/index.tsx b/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/_layout/[__double-index]/index.tsx deleted file mode 100644 index 231e787df0..0000000000 --- a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/_layout/[__double-index]/index.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_layout/__double-index/')({ - component: () => 'Double Index', -}) diff --git a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/_layout/[__double].tsx b/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/_layout/[__double].tsx deleted file mode 100644 index 2cb4336d37..0000000000 --- a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/_layout/[__double].tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_layout/__double')({ - component: () => 'Double Escaped', -}) diff --git a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/_layout/__nested2.tsx b/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/_layout/__nested2.tsx deleted file mode 100644 index 802b1fc765..0000000000 --- a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/_layout/__nested2.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_layout/__nested2')({ - component: () => 'Nested Double Underscore Layout', -}) diff --git a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/_layout/__nested2/[_]deep.tsx b/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/_layout/__nested2/[_]deep.tsx deleted file mode 100644 index e36965ef42..0000000000 --- a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/_layout/__nested2/[_]deep.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_layout/__nested2/_deep')({ - component: () => 'Deep', -}) diff --git a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/_layout/_nested.tsx b/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/_layout/_nested.tsx deleted file mode 100644 index b2985c3c2e..0000000000 --- a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/_layout/_nested.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_layout/_nested')({ - component: () => 'Nested Layout', -}) diff --git a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/_layout/_nested/[_]baz.tsx b/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/_layout/_nested/[_]baz.tsx deleted file mode 100644 index 9bec9e82d4..0000000000 --- a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/_layout/_nested/[_]baz.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_layout/_nested/_baz')({ - component: () => 'Baz', -}) diff --git a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/_layout/_nested/[_]deep-index/index.tsx b/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/_layout/_nested/[_]deep-index/index.tsx deleted file mode 100644 index 4113450ea1..0000000000 --- a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/_layout/_nested/[_]deep-index/index.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_layout/_nested/_deep-index/')({ - component: () => 'Deep Index', -}) diff --git a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/_layout/nested-trailing[_]/index.tsx b/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/_layout/nested-trailing[_]/index.tsx deleted file mode 100644 index 786604a503..0000000000 --- a/packages/router-generator/tests/generator/physical-pathless-layout-escaped-underscore/routes/_layout/nested-trailing[_]/index.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_layout/nested-trailing_/')({ - component: () => 'Nested Trailing Index', -}) diff --git a/packages/router-generator/tests/generator/prefix-suffix/routeTree.snapshot.ts b/packages/router-generator/tests/generator/prefix-suffix/routeTree.snapshot.ts index 2ef38f491d..5f7f854d9f 100644 --- a/packages/router-generator/tests/generator/prefix-suffix/routeTree.snapshot.ts +++ b/packages/router-generator/tests/generator/prefix-suffix/routeTree.snapshot.ts @@ -9,20 +9,15 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as WildcardSplatRouteImport } from './routes/wildcard/$' -import { Route as WildcardPrefixChar123Char125RouteImport } from './routes/wildcard/prefix{$}' -import { Route as WildcardChar123Char125DotsuffixRouteImport } from './routes/wildcard/{$}[.]suffix' import { Route as WildcardChar123Char125suffixRouteImport } from './routes/wildcard/{$}suffix' +import { Route as WildcardChar123Char125DotsuffixRouteImport } from './routes/wildcard/{$}[.]suffix' +import { Route as WildcardPrefixChar123Char125RouteImport } from './routes/wildcard/prefix{$}' +import { Route as WildcardSplatRouteImport } from './routes/wildcard/$' -const WildcardSplatRoute = WildcardSplatRouteImport.update({ - id: '/wildcard/$', - path: '/wildcard/$', - getParentRoute: () => rootRouteImport, -} as any) -const WildcardPrefixChar123Char125Route = - WildcardPrefixChar123Char125RouteImport.update({ - id: '/wildcard/prefix{$}', - path: '/wildcard/prefix{$}', +const WildcardChar123Char125suffixRoute = + WildcardChar123Char125suffixRouteImport.update({ + id: '/wildcard/{$}suffix', + path: '/wildcard/{$}suffix', getParentRoute: () => rootRouteImport, } as any) const WildcardChar123Char125DotsuffixRoute = @@ -31,12 +26,17 @@ const WildcardChar123Char125DotsuffixRoute = path: '/wildcard/{$}.suffix', getParentRoute: () => rootRouteImport, } as any) -const WildcardChar123Char125suffixRoute = - WildcardChar123Char125suffixRouteImport.update({ - id: '/wildcard/{$}suffix', - path: '/wildcard/{$}suffix', +const WildcardPrefixChar123Char125Route = + WildcardPrefixChar123Char125RouteImport.update({ + id: '/wildcard/prefix{$}', + path: '/wildcard/prefix{$}', getParentRoute: () => rootRouteImport, } as any) +const WildcardSplatRoute = WildcardSplatRouteImport.update({ + id: '/wildcard/$', + path: '/wildcard/$', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/wildcard/$': typeof WildcardSplatRoute @@ -87,18 +87,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/wildcard/$': { - id: '/wildcard/$' - path: '/wildcard/$' - fullPath: '/wildcard/$' - preLoaderRoute: typeof WildcardSplatRouteImport - parentRoute: typeof rootRouteImport - } - '/wildcard/prefix{$}': { - id: '/wildcard/prefix{$}' - path: '/wildcard/prefix{$}' - fullPath: '/wildcard/prefix{$}' - preLoaderRoute: typeof WildcardPrefixChar123Char125RouteImport + '/wildcard/{$}suffix': { + id: '/wildcard/{$}suffix' + path: '/wildcard/{$}suffix' + fullPath: '/wildcard/{$}suffix' + preLoaderRoute: typeof WildcardChar123Char125suffixRouteImport parentRoute: typeof rootRouteImport } '/wildcard/{$}.suffix': { @@ -108,11 +101,18 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof WildcardChar123Char125DotsuffixRouteImport parentRoute: typeof rootRouteImport } - '/wildcard/{$}suffix': { - id: '/wildcard/{$}suffix' - path: '/wildcard/{$}suffix' - fullPath: '/wildcard/{$}suffix' - preLoaderRoute: typeof WildcardChar123Char125suffixRouteImport + '/wildcard/prefix{$}': { + id: '/wildcard/prefix{$}' + path: '/wildcard/prefix{$}' + fullPath: '/wildcard/prefix{$}' + preLoaderRoute: typeof WildcardPrefixChar123Char125RouteImport + parentRoute: typeof rootRouteImport + } + '/wildcard/$': { + id: '/wildcard/$' + path: '/wildcard/$' + fullPath: '/wildcard/$' + preLoaderRoute: typeof WildcardSplatRouteImport parentRoute: typeof rootRouteImport } } diff --git a/packages/router-generator/tests/generator/regex-tokens-inline/routeTree.snapshot.ts b/packages/router-generator/tests/generator/regex-tokens-inline/routeTree.snapshot.ts index 669cebaf59..3909bbe9f4 100644 --- a/packages/router-generator/tests/generator/regex-tokens-inline/routeTree.snapshot.ts +++ b/packages/router-generator/tests/generator/regex-tokens-inline/routeTree.snapshot.ts @@ -9,21 +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 IndexPageRouteImport } from './routes/index-page' import { Route as DashboardMainLayoutRouteImport } from './routes/dashboard.main-layout' +import { Route as IndexPageRouteImport } from './routes/index-page' import { Route as DashboardHomePageRouteImport } from './routes/dashboard.home-page' import { Route as DashboardSettingsRouteImport } from './routes/dashboard.settings' -const IndexPageRoute = IndexPageRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const DashboardMainLayoutRoute = DashboardMainLayoutRouteImport.update({ id: '/dashboard', path: '/dashboard', getParentRoute: () => rootRouteImport, } as any) +const IndexPageRoute = IndexPageRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const DashboardHomePageRoute = DashboardHomePageRouteImport.update({ id: '/', path: '/', @@ -68,13 +68,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexPageRouteImport - parentRoute: typeof rootRouteImport - } '/dashboard': { id: '/dashboard' path: '/dashboard' @@ -82,6 +75,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof DashboardMainLayoutRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexPageRouteImport + parentRoute: typeof rootRouteImport + } '/dashboard/': { id: '/dashboard/' path: '/' diff --git a/packages/router-generator/tests/generator/regex-tokens-json/routeTree.snapshot.ts b/packages/router-generator/tests/generator/regex-tokens-json/routeTree.snapshot.ts index 669cebaf59..3909bbe9f4 100644 --- a/packages/router-generator/tests/generator/regex-tokens-json/routeTree.snapshot.ts +++ b/packages/router-generator/tests/generator/regex-tokens-json/routeTree.snapshot.ts @@ -9,21 +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 IndexPageRouteImport } from './routes/index-page' import { Route as DashboardMainLayoutRouteImport } from './routes/dashboard.main-layout' +import { Route as IndexPageRouteImport } from './routes/index-page' import { Route as DashboardHomePageRouteImport } from './routes/dashboard.home-page' import { Route as DashboardSettingsRouteImport } from './routes/dashboard.settings' -const IndexPageRoute = IndexPageRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const DashboardMainLayoutRoute = DashboardMainLayoutRouteImport.update({ id: '/dashboard', path: '/dashboard', getParentRoute: () => rootRouteImport, } as any) +const IndexPageRoute = IndexPageRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const DashboardHomePageRoute = DashboardHomePageRouteImport.update({ id: '/', path: '/', @@ -68,13 +68,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexPageRouteImport - parentRoute: typeof rootRouteImport - } '/dashboard': { id: '/dashboard' path: '/dashboard' @@ -82,6 +75,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof DashboardMainLayoutRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexPageRouteImport + parentRoute: typeof rootRouteImport + } '/dashboard/': { id: '/dashboard/' path: '/' diff --git a/packages/router-generator/tests/generator/regex-tokens-plus-json/routeTree.snapshot.ts b/packages/router-generator/tests/generator/regex-tokens-plus-json/routeTree.snapshot.ts deleted file mode 100644 index 74c38f90ad..0000000000 --- a/packages/router-generator/tests/generator/regex-tokens-plus-json/routeTree.snapshot.ts +++ /dev/null @@ -1,123 +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 Char43pageRouteImport } from './routes/+page' -import { Route as DashboardChar43layoutRouteImport } from './routes/dashboard/+layout' -import { Route as DashboardChar43pageRouteImport } from './routes/dashboard/+page' -import { Route as DashboardSettingsRouteImport } from './routes/dashboard/settings' - -const Char43pageRoute = Char43pageRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const DashboardChar43layoutRoute = DashboardChar43layoutRouteImport.update({ - id: '/dashboard', - path: '/dashboard', - getParentRoute: () => rootRouteImport, -} as any) -const DashboardChar43pageRoute = DashboardChar43pageRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => DashboardChar43layoutRoute, -} as any) -const DashboardSettingsRoute = DashboardSettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => DashboardChar43layoutRoute, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof Char43pageRoute - '/dashboard': typeof DashboardChar43layoutRouteWithChildren - '/dashboard/settings': typeof DashboardSettingsRoute - '/dashboard/': typeof DashboardChar43pageRoute -} -export interface FileRoutesByTo { - '/': typeof Char43pageRoute - '/dashboard/settings': typeof DashboardSettingsRoute - '/dashboard': typeof DashboardChar43pageRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof Char43pageRoute - '/dashboard': typeof DashboardChar43layoutRouteWithChildren - '/dashboard/settings': typeof DashboardSettingsRoute - '/dashboard/': typeof DashboardChar43pageRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/dashboard' | '/dashboard/settings' | '/dashboard/' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/dashboard/settings' | '/dashboard' - id: '__root__' | '/' | '/dashboard' | '/dashboard/settings' | '/dashboard/' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - Char43pageRoute: typeof Char43pageRoute - DashboardChar43layoutRoute: typeof DashboardChar43layoutRouteWithChildren -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof Char43pageRouteImport - parentRoute: typeof rootRouteImport - } - '/dashboard': { - id: '/dashboard' - path: '/dashboard' - fullPath: '/dashboard' - preLoaderRoute: typeof DashboardChar43layoutRouteImport - parentRoute: typeof rootRouteImport - } - '/dashboard/': { - id: '/dashboard/' - path: '/' - fullPath: '/dashboard/' - preLoaderRoute: typeof DashboardChar43pageRouteImport - parentRoute: typeof DashboardChar43layoutRoute - } - '/dashboard/settings': { - id: '/dashboard/settings' - path: '/settings' - fullPath: '/dashboard/settings' - preLoaderRoute: typeof DashboardSettingsRouteImport - parentRoute: typeof DashboardChar43layoutRoute - } - } -} - -interface DashboardChar43layoutRouteChildren { - DashboardSettingsRoute: typeof DashboardSettingsRoute - DashboardChar43pageRoute: typeof DashboardChar43pageRoute -} - -const DashboardChar43layoutRouteChildren: DashboardChar43layoutRouteChildren = { - DashboardSettingsRoute: DashboardSettingsRoute, - DashboardChar43pageRoute: DashboardChar43pageRoute, -} - -const DashboardChar43layoutRouteWithChildren = - DashboardChar43layoutRoute._addFileChildren( - DashboardChar43layoutRouteChildren, - ) - -const rootRouteChildren: RootRouteChildren = { - Char43pageRoute: Char43pageRoute, - DashboardChar43layoutRoute: DashboardChar43layoutRouteWithChildren, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes<FileRouteTypes>() diff --git a/packages/router-generator/tests/generator/regex-tokens-plus-json/routes/+page.tsx b/packages/router-generator/tests/generator/regex-tokens-plus-json/routes/+page.tsx deleted file mode 100644 index 2f2e105077..0000000000 --- a/packages/router-generator/tests/generator/regex-tokens-plus-json/routes/+page.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/')({ - component: () => <div>Home Page</div>, -}) diff --git a/packages/router-generator/tests/generator/regex-tokens-plus-json/routes/__root.tsx b/packages/router-generator/tests/generator/regex-tokens-plus-json/routes/__root.tsx deleted file mode 100644 index 742d24a4ea..0000000000 --- a/packages/router-generator/tests/generator/regex-tokens-plus-json/routes/__root.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { Outlet, createRootRoute } from '@tanstack/react-router' - -export const Route = createRootRoute({ - component: () => <Outlet />, -}) diff --git a/packages/router-generator/tests/generator/regex-tokens-plus-json/routes/dashboard/+layout.tsx b/packages/router-generator/tests/generator/regex-tokens-plus-json/routes/dashboard/+layout.tsx deleted file mode 100644 index 5d03a657c6..0000000000 --- a/packages/router-generator/tests/generator/regex-tokens-plus-json/routes/dashboard/+layout.tsx +++ /dev/null @@ -1,10 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/dashboard')({ - component: () => ( - <div> - <h1>Dashboard Layout</h1> - <Outlet /> - </div> - ), -}) diff --git a/packages/router-generator/tests/generator/regex-tokens-plus-json/routes/dashboard/+page.tsx b/packages/router-generator/tests/generator/regex-tokens-plus-json/routes/dashboard/+page.tsx deleted file mode 100644 index 71d13d851a..0000000000 --- a/packages/router-generator/tests/generator/regex-tokens-plus-json/routes/dashboard/+page.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/dashboard/')({ - component: () => <div>Dashboard Home</div>, -}) diff --git a/packages/router-generator/tests/generator/regex-tokens-plus-json/routes/dashboard/settings.tsx b/packages/router-generator/tests/generator/regex-tokens-plus-json/routes/dashboard/settings.tsx deleted file mode 100644 index c05ef65ade..0000000000 --- a/packages/router-generator/tests/generator/regex-tokens-plus-json/routes/dashboard/settings.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/dashboard/settings')({ - component: () => <div>Dashboard Settings</div>, -}) diff --git a/packages/router-generator/tests/generator/regex-tokens-plus-json/tsr.config.json b/packages/router-generator/tests/generator/regex-tokens-plus-json/tsr.config.json deleted file mode 100644 index 54e34fc0ae..0000000000 --- a/packages/router-generator/tests/generator/regex-tokens-plus-json/tsr.config.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "indexToken": { "regex": "\\+page" }, - "routeToken": { "regex": "\\+layout" } -} diff --git a/packages/router-generator/tests/generator/root-export-specifier/routeTree.snapshot.ts b/packages/router-generator/tests/generator/root-export-specifier/routeTree.snapshot.ts deleted file mode 100644 index 12bc916ae4..0000000000 --- a/packages/router-generator/tests/generator/root-export-specifier/routeTree.snapshot.ts +++ /dev/null @@ -1,77 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as AboutRouteImport } from './routes/about' - -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 - '/about': typeof AboutRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/about': typeof AboutRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/about': typeof AboutRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/about' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/about' - id: '__root__' | '/' | '/about' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - AboutRoute: typeof AboutRoute -} - -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 - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - AboutRoute: AboutRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes<FileRouteTypes>() diff --git a/packages/router-generator/tests/generator/root-export-specifier/routes/__root.tsx b/packages/router-generator/tests/generator/root-export-specifier/routes/__root.tsx deleted file mode 100644 index 6fb0358524..0000000000 --- a/packages/router-generator/tests/generator/root-export-specifier/routes/__root.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import { createRootRoute } from '@tanstack/react-router' - -const Route = createRootRoute({ - component: RootComponent, -}) - -export { Route } - -function RootComponent() { - return null -} diff --git a/packages/router-generator/tests/generator/root-export-specifier/routes/about.tsx b/packages/router-generator/tests/generator/root-export-specifier/routes/about.tsx deleted file mode 100644 index 2ee06f6d0f..0000000000 --- a/packages/router-generator/tests/generator/root-export-specifier/routes/about.tsx +++ /dev/null @@ -1,3 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/about')() diff --git a/packages/router-generator/tests/generator/root-export-specifier/routes/index.tsx b/packages/router-generator/tests/generator/root-export-specifier/routes/index.tsx deleted file mode 100644 index fbf3caabfb..0000000000 --- a/packages/router-generator/tests/generator/root-export-specifier/routes/index.tsx +++ /dev/null @@ -1,3 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/')() diff --git a/packages/router-generator/tests/generator/route-groups/routeTree.snapshot.ts b/packages/router-generator/tests/generator/route-groups/routeTree.snapshot.ts index d3ffbba9e2..f2e84bbbb7 100644 --- a/packages/router-generator/tests/generator/route-groups/routeTree.snapshot.ts +++ b/packages/router-generator/tests/generator/route-groups/routeTree.snapshot.ts @@ -12,13 +12,13 @@ import { createFileRoute } from '@tanstack/react-router' import { Route as rootRouteImport } from './routes/__root' import { Route as barBarRouteImport } from './routes/(bar)/_bar' -import { Route as barBarHelloRouteImport } from './routes/(bar)/_bar.hello' import { Route as fooAsdfLayoutRouteImport } from './routes/(foo)/asdf/_layout' -import { Route as fooAsdfanotherGroupLayoutRouteImport } from './routes/(foo)/asdf/(another-group)/_layout' -import { Route as fooAsdfbarIdRouteImport } from './routes/(foo)/asdf/(bar)/$id' +import { Route as barBarHelloRouteImport } from './routes/(bar)/_bar.hello' import { Route as fooAsdfLayoutFooRouteImport } from './routes/(foo)/asdf/_layout.foo' -import { Route as fooAsdfanotherGroupLayoutBazRouteImport } from './routes/(foo)/asdf/(another-group)/_layout.baz' +import { Route as fooAsdfbarIdRouteImport } from './routes/(foo)/asdf/(bar)/$id' +import { Route as fooAsdfanotherGroupLayoutRouteImport } from './routes/(foo)/asdf/(another-group)/_layout' import { Route as fooAsdfbarLayoutAboutRouteImport } from './routes/(foo)/asdf/(bar)/_layout.about' +import { Route as fooAsdfanotherGroupLayoutBazRouteImport } from './routes/(foo)/asdf/(another-group)/_layout.baz' const fooAsdfbarLayoutXyzLazyRouteImport = createFileRoute( '/(foo)/asdf/(bar)/_layout/xyz', @@ -28,14 +28,24 @@ const barBarRoute = barBarRouteImport.update({ id: '/(bar)/_bar', getParentRoute: () => rootRouteImport, } as any) +const fooAsdfLayoutRoute = fooAsdfLayoutRouteImport.update({ + id: '/(foo)/asdf/_layout', + path: '/asdf', + getParentRoute: () => rootRouteImport, +} as any) const barBarHelloRoute = barBarHelloRouteImport.update({ id: '/hello', path: '/hello', getParentRoute: () => barBarRoute, } as any) -const fooAsdfLayoutRoute = fooAsdfLayoutRouteImport.update({ - id: '/(foo)/asdf/_layout', - path: '/asdf', +const fooAsdfLayoutFooRoute = fooAsdfLayoutFooRouteImport.update({ + id: '/foo', + path: '/foo', + getParentRoute: () => fooAsdfLayoutRoute, +} as any) +const fooAsdfbarIdRoute = fooAsdfbarIdRouteImport.update({ + id: '/(foo)/asdf/(bar)/$id', + path: '/asdf/$id', getParentRoute: () => rootRouteImport, } as any) const fooAsdfanotherGroupLayoutRoute = @@ -44,27 +54,6 @@ const fooAsdfanotherGroupLayoutRoute = path: '/asdf', getParentRoute: () => rootRouteImport, } as any) -const fooAsdfbarIdRoute = fooAsdfbarIdRouteImport.update({ - id: '/(foo)/asdf/(bar)/$id', - path: '/asdf/$id', - getParentRoute: () => rootRouteImport, -} as any) -const fooAsdfLayoutFooRoute = fooAsdfLayoutFooRouteImport.update({ - id: '/foo', - path: '/foo', - getParentRoute: () => fooAsdfLayoutRoute, -} as any) -const fooAsdfanotherGroupLayoutBazRoute = - fooAsdfanotherGroupLayoutBazRouteImport.update({ - id: '/baz', - path: '/baz', - getParentRoute: () => fooAsdfanotherGroupLayoutRoute, - } as any) -const fooAsdfbarLayoutAboutRoute = fooAsdfbarLayoutAboutRouteImport.update({ - id: '/(foo)/asdf/(bar)/_layout/about', - path: '/asdf/about', - getParentRoute: () => rootRouteImport, -} as any) const fooAsdfbarLayoutXyzLazyRoute = fooAsdfbarLayoutXyzLazyRouteImport .update({ id: '/(foo)/asdf/(bar)/_layout/xyz', @@ -74,9 +63,19 @@ const fooAsdfbarLayoutXyzLazyRoute = fooAsdfbarLayoutXyzLazyRouteImport .lazy(() => import('./routes/(foo)/asdf/(bar)/_layout.xyz.lazy').then((d) => d.Route), ) +const fooAsdfbarLayoutAboutRoute = fooAsdfbarLayoutAboutRouteImport.update({ + id: '/(foo)/asdf/(bar)/_layout/about', + path: '/asdf/about', + getParentRoute: () => rootRouteImport, +} as any) +const fooAsdfanotherGroupLayoutBazRoute = + fooAsdfanotherGroupLayoutBazRouteImport.update({ + id: '/baz', + path: '/baz', + getParentRoute: () => fooAsdfanotherGroupLayoutRoute, + } as any) export interface FileRoutesByFullPath { - '/': typeof barBarRouteWithChildren '/hello': typeof barBarHelloRoute '/asdf': typeof fooAsdfanotherGroupLayoutRouteWithChildren '/asdf/$id': typeof fooAsdfbarIdRoute @@ -86,7 +85,6 @@ export interface FileRoutesByFullPath { '/asdf/xyz': typeof fooAsdfbarLayoutXyzLazyRoute } export interface FileRoutesByTo { - '/': typeof barBarRouteWithChildren '/hello': typeof barBarHelloRoute '/asdf': typeof fooAsdfanotherGroupLayoutRouteWithChildren '/asdf/$id': typeof fooAsdfbarIdRoute @@ -110,7 +108,6 @@ export interface FileRoutesById { export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath fullPaths: - | '/' | '/hello' | '/asdf' | '/asdf/$id' @@ -120,7 +117,6 @@ export interface FileRouteTypes { | '/asdf/xyz' fileRoutesByTo: FileRoutesByTo to: - | '/' | '/hello' | '/asdf' | '/asdf/$id' @@ -155,10 +151,17 @@ declare module '@tanstack/react-router' { '/(bar)/_bar': { id: '/(bar)/_bar' path: '' - fullPath: '/' + fullPath: '' preLoaderRoute: typeof barBarRouteImport parentRoute: typeof rootRouteImport } + '/(foo)/asdf/_layout': { + id: '/(foo)/asdf/_layout' + path: '/asdf' + fullPath: '/asdf' + preLoaderRoute: typeof fooAsdfLayoutRouteImport + parentRoute: typeof rootRouteImport + } '/(bar)/_bar/hello': { id: '/(bar)/_bar/hello' path: '/hello' @@ -166,11 +169,18 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof barBarHelloRouteImport parentRoute: typeof barBarRoute } - '/(foo)/asdf/_layout': { - id: '/(foo)/asdf/_layout' - path: '/asdf' - fullPath: '/asdf' - preLoaderRoute: typeof fooAsdfLayoutRouteImport + '/(foo)/asdf/_layout/foo': { + id: '/(foo)/asdf/_layout/foo' + path: '/foo' + fullPath: '/asdf/foo' + preLoaderRoute: typeof fooAsdfLayoutFooRouteImport + parentRoute: typeof fooAsdfLayoutRoute + } + '/(foo)/asdf/(bar)/$id': { + id: '/(foo)/asdf/(bar)/$id' + path: '/asdf/$id' + fullPath: '/asdf/$id' + preLoaderRoute: typeof fooAsdfbarIdRouteImport parentRoute: typeof rootRouteImport } '/(foo)/asdf/(another-group)/_layout': { @@ -180,27 +190,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof fooAsdfanotherGroupLayoutRouteImport parentRoute: typeof rootRouteImport } - '/(foo)/asdf/(bar)/$id': { - id: '/(foo)/asdf/(bar)/$id' - path: '/asdf/$id' - fullPath: '/asdf/$id' - preLoaderRoute: typeof fooAsdfbarIdRouteImport + '/(foo)/asdf/(bar)/_layout/xyz': { + id: '/(foo)/asdf/(bar)/_layout/xyz' + path: '/asdf/xyz' + fullPath: '/asdf/xyz' + preLoaderRoute: typeof fooAsdfbarLayoutXyzLazyRouteImport parentRoute: typeof rootRouteImport } - '/(foo)/asdf/_layout/foo': { - id: '/(foo)/asdf/_layout/foo' - path: '/foo' - fullPath: '/asdf/foo' - preLoaderRoute: typeof fooAsdfLayoutFooRouteImport - parentRoute: typeof fooAsdfLayoutRoute - } - '/(foo)/asdf/(another-group)/_layout/baz': { - id: '/(foo)/asdf/(another-group)/_layout/baz' - path: '/baz' - fullPath: '/asdf/baz' - preLoaderRoute: typeof fooAsdfanotherGroupLayoutBazRouteImport - parentRoute: typeof fooAsdfanotherGroupLayoutRoute - } '/(foo)/asdf/(bar)/_layout/about': { id: '/(foo)/asdf/(bar)/_layout/about' path: '/asdf/about' @@ -208,12 +204,12 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof fooAsdfbarLayoutAboutRouteImport parentRoute: typeof rootRouteImport } - '/(foo)/asdf/(bar)/_layout/xyz': { - id: '/(foo)/asdf/(bar)/_layout/xyz' - path: '/asdf/xyz' - fullPath: '/asdf/xyz' - preLoaderRoute: typeof fooAsdfbarLayoutXyzLazyRouteImport - parentRoute: typeof rootRouteImport + '/(foo)/asdf/(another-group)/_layout/baz': { + id: '/(foo)/asdf/(another-group)/_layout/baz' + path: '/baz' + fullPath: '/asdf/baz' + preLoaderRoute: typeof fooAsdfanotherGroupLayoutBazRouteImport + parentRoute: typeof fooAsdfanotherGroupLayoutRoute } } } diff --git a/packages/router-generator/tests/generator/routeFileIgnore/routeTree.snapshot.ts b/packages/router-generator/tests/generator/routeFileIgnore/routeTree.snapshot.ts index ceb6811cf7..33a4093b9e 100644 --- a/packages/router-generator/tests/generator/routeFileIgnore/routeTree.snapshot.ts +++ b/packages/router-generator/tests/generator/routeFileIgnore/routeTree.snapshot.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 IndexRouteImport } from './routes/index' import { Route as BlogRouteRouteImport } from './routes/blog.route' +import { Route as IndexRouteImport } from './routes/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const BlogRouteRoute = BlogRouteRouteImport.update({ id: '/blog', path: '/blog', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/blog': { id: '/blog' path: '/blog' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof BlogRouteRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/packages/router-generator/tests/generator/routeFilePrefix/routeTree.snapshot.ts b/packages/router-generator/tests/generator/routeFilePrefix/routeTree.snapshot.ts index 9805633c47..46ee215c03 100644 --- a/packages/router-generator/tests/generator/routeFilePrefix/routeTree.snapshot.ts +++ b/packages/router-generator/tests/generator/routeFilePrefix/routeTree.snapshot.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/r&__root' -import { Route as IndexRouteImport } from './routes/r&index' import { Route as BlogRouteRouteImport } from './routes/r&blog.route' +import { Route as IndexRouteImport } from './routes/r&index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const BlogRouteRoute = BlogRouteRouteImport.update({ id: '/blog', path: '/blog', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/blog': { id: '/blog' path: '/blog' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof BlogRouteRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/packages/router-generator/tests/generator/single-level/routeTree.snapshot.ts b/packages/router-generator/tests/generator/single-level/routeTree.snapshot.ts index 12b48f052a..b60f0b934f 100644 --- a/packages/router-generator/tests/generator/single-level/routeTree.snapshot.ts +++ b/packages/router-generator/tests/generator/single-level/routeTree.snapshot.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 IndexRouteImport } from './routes/index' import { Route as PostsRouteImport } from './routes/posts' +import { Route as IndexRouteImport } from './routes/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const PostsRoute = PostsRouteImport.update({ id: '/posts', path: '/posts', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/posts': { id: '/posts' path: '/posts' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/packages/router-generator/tests/generator/types-disabled/routeTree.snapshot.js b/packages/router-generator/tests/generator/types-disabled/routeTree.snapshot.js index 4dc8f12ad7..9c410eea0f 100644 --- a/packages/router-generator/tests/generator/types-disabled/routeTree.snapshot.js +++ b/packages/router-generator/tests/generator/types-disabled/routeTree.snapshot.js @@ -9,19 +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 IndexRouteImport } from './routes/index' import { Route as PostsRouteImport } from './routes/posts' -import { Route as PostsPostIdRouteImport } from './routes/posts/$postId' +import { Route as IndexRouteImport } from './routes/index' import { Route as UsersUserIdRouteImport } from './routes/users.$userId' +import { Route as PostsPostIdRouteImport } from './routes/posts/$postId' +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', + getParentRoute: () => rootRouteImport, +}) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, }) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const UsersUserIdRoute = UsersUserIdRouteImport.update({ + id: '/users/$userId', + path: '/users/$userId', getParentRoute: () => rootRouteImport, }) const PostsPostIdRoute = PostsPostIdRouteImport.update({ @@ -29,11 +34,6 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ path: '/$postId', getParentRoute: () => PostsRoute, }) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/users/$userId', - path: '/users/$userId', - getParentRoute: () => rootRouteImport, -}) const PostsRouteChildren = { PostsPostIdRoute: PostsPostIdRoute, diff --git a/packages/router-generator/tests/generator/virtual-config-file-default-export/routeTree.snapshot.ts b/packages/router-generator/tests/generator/virtual-config-file-default-export/routeTree.snapshot.ts index 6b16924d5b..3d3c2de9d5 100644 --- a/packages/router-generator/tests/generator/virtual-config-file-default-export/routeTree.snapshot.ts +++ b/packages/router-generator/tests/generator/virtual-config-file-default-export/routeTree.snapshot.ts @@ -9,30 +9,25 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/root' -import { Route as indexRouteImport } from './routes/index' import { Route as layoutRouteImport } from './routes/layout' -import { Route as pagesRouteImport } from './routes/pages' +import { Route as indexRouteImport } from './routes/index' import { Route as dbDashboardRouteImport } from './routes/db/dashboard' -import { Route as dbDashboardIndexRouteImport } from './routes/db/dashboard-index' -import { Route as dbDashboardInvoicesRouteImport } from './routes/db/dashboard-invoices' +import { Route as pagesRouteImport } from './routes/pages' import { Route as HelloIndexRouteImport } from './routes/subtree/index' -import { Route as dbInvoicesIndexRouteImport } from './routes/db/invoices-index' -import { Route as dbInvoiceDetailRouteImport } from './routes/db/invoice-detail' +import { Route as dbDashboardInvoicesRouteImport } from './routes/db/dashboard-invoices' +import { Route as dbDashboardIndexRouteImport } from './routes/db/dashboard-index' import { Route as HelloFooIndexRouteImport } from './routes/subtree/foo/index' import { Route as HelloFooIdRouteImport } from './routes/subtree/foo/$id' +import { Route as dbInvoiceDetailRouteImport } from './routes/db/invoice-detail' +import { Route as dbInvoicesIndexRouteImport } from './routes/db/invoices-index' -const indexRoute = indexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const layoutRoute = layoutRouteImport.update({ id: '/_layout', getParentRoute: () => rootRouteImport, } as any) -const pagesRoute = pagesRouteImport.update({ - id: '/$lang/', - path: '/$lang/', +const indexRoute = indexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const dbDashboardRoute = dbDashboardRouteImport.update({ @@ -40,30 +35,25 @@ const dbDashboardRoute = dbDashboardRouteImport.update({ path: '/dashboard', getParentRoute: () => layoutRoute, } as any) -const dbDashboardIndexRoute = dbDashboardIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => dbDashboardRoute, -} as any) -const dbDashboardInvoicesRoute = dbDashboardInvoicesRouteImport.update({ - id: '/invoices', - path: '/invoices', - getParentRoute: () => dbDashboardRoute, +const pagesRoute = pagesRouteImport.update({ + id: '/$lang/', + path: '/$lang/', + getParentRoute: () => rootRouteImport, } as any) const HelloIndexRoute = HelloIndexRouteImport.update({ id: '/hello/', path: '/hello/', getParentRoute: () => layoutRoute, } as any) -const dbInvoicesIndexRoute = dbInvoicesIndexRouteImport.update({ +const dbDashboardInvoicesRoute = dbDashboardInvoicesRouteImport.update({ + id: '/invoices', + path: '/invoices', + getParentRoute: () => dbDashboardRoute, +} as any) +const dbDashboardIndexRoute = dbDashboardIndexRouteImport.update({ id: '/', path: '/', - getParentRoute: () => dbDashboardInvoicesRoute, -} as any) -const dbInvoiceDetailRoute = dbInvoiceDetailRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => dbDashboardInvoicesRoute, + getParentRoute: () => dbDashboardRoute, } as any) const HelloFooIndexRoute = HelloFooIndexRouteImport.update({ id: '/hello/foo/', @@ -75,6 +65,16 @@ const HelloFooIdRoute = HelloFooIdRouteImport.update({ path: '/hello/foo/$id', getParentRoute: () => layoutRoute, } as any) +const dbInvoiceDetailRoute = dbInvoiceDetailRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => dbDashboardInvoicesRoute, +} as any) +const dbInvoicesIndexRoute = dbInvoicesIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => dbDashboardInvoicesRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof indexRoute @@ -158,13 +158,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof indexRouteImport - parentRoute: typeof rootRouteImport - } '/_layout': { id: '/_layout' path: '' @@ -172,11 +165,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof layoutRouteImport parentRoute: typeof rootRouteImport } - '/$lang/': { - id: '/$lang/' - path: '/$lang' - fullPath: '/$lang/' - preLoaderRoute: typeof pagesRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof indexRouteImport parentRoute: typeof rootRouteImport } '/_layout/dashboard': { @@ -186,19 +179,12 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof dbDashboardRouteImport parentRoute: typeof layoutRoute } - '/_layout/dashboard/': { - id: '/_layout/dashboard/' - path: '/' - fullPath: '/dashboard/' - preLoaderRoute: typeof dbDashboardIndexRouteImport - parentRoute: typeof dbDashboardRoute - } - '/_layout/dashboard/invoices': { - id: '/_layout/dashboard/invoices' - path: '/invoices' - fullPath: '/dashboard/invoices' - preLoaderRoute: typeof dbDashboardInvoicesRouteImport - parentRoute: typeof dbDashboardRoute + '/$lang/': { + id: '/$lang/' + path: '/$lang' + fullPath: '/$lang/' + preLoaderRoute: typeof pagesRouteImport + parentRoute: typeof rootRouteImport } '/_layout/hello/': { id: '/_layout/hello/' @@ -207,19 +193,19 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof HelloIndexRouteImport parentRoute: typeof layoutRoute } - '/_layout/dashboard/invoices/': { - id: '/_layout/dashboard/invoices/' - path: '/' - fullPath: '/dashboard/invoices/' - preLoaderRoute: typeof dbInvoicesIndexRouteImport - parentRoute: typeof dbDashboardInvoicesRoute + '/_layout/dashboard/invoices': { + id: '/_layout/dashboard/invoices' + path: '/invoices' + fullPath: '/dashboard/invoices' + preLoaderRoute: typeof dbDashboardInvoicesRouteImport + parentRoute: typeof dbDashboardRoute } - '/_layout/dashboard/invoices/$id': { - id: '/_layout/dashboard/invoices/$id' - path: '/$id' - fullPath: '/dashboard/invoices/$id' - preLoaderRoute: typeof dbInvoiceDetailRouteImport - parentRoute: typeof dbDashboardInvoicesRoute + '/_layout/dashboard/': { + id: '/_layout/dashboard/' + path: '/' + fullPath: '/dashboard/' + preLoaderRoute: typeof dbDashboardIndexRouteImport + parentRoute: typeof dbDashboardRoute } '/_layout/hello/foo/': { id: '/_layout/hello/foo/' @@ -235,6 +221,20 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof HelloFooIdRouteImport parentRoute: typeof layoutRoute } + '/_layout/dashboard/invoices/$id': { + id: '/_layout/dashboard/invoices/$id' + path: '/$id' + fullPath: '/dashboard/invoices/$id' + preLoaderRoute: typeof dbInvoiceDetailRouteImport + parentRoute: typeof dbDashboardInvoicesRoute + } + '/_layout/dashboard/invoices/': { + id: '/_layout/dashboard/invoices/' + path: '/' + fullPath: '/dashboard/invoices/' + preLoaderRoute: typeof dbInvoicesIndexRouteImport + parentRoute: typeof dbDashboardInvoicesRoute + } } } diff --git a/packages/router-generator/tests/generator/virtual-config-file-named-export/routeTree.snapshot.ts b/packages/router-generator/tests/generator/virtual-config-file-named-export/routeTree.snapshot.ts index 6b16924d5b..3d3c2de9d5 100644 --- a/packages/router-generator/tests/generator/virtual-config-file-named-export/routeTree.snapshot.ts +++ b/packages/router-generator/tests/generator/virtual-config-file-named-export/routeTree.snapshot.ts @@ -9,30 +9,25 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/root' -import { Route as indexRouteImport } from './routes/index' import { Route as layoutRouteImport } from './routes/layout' -import { Route as pagesRouteImport } from './routes/pages' +import { Route as indexRouteImport } from './routes/index' import { Route as dbDashboardRouteImport } from './routes/db/dashboard' -import { Route as dbDashboardIndexRouteImport } from './routes/db/dashboard-index' -import { Route as dbDashboardInvoicesRouteImport } from './routes/db/dashboard-invoices' +import { Route as pagesRouteImport } from './routes/pages' import { Route as HelloIndexRouteImport } from './routes/subtree/index' -import { Route as dbInvoicesIndexRouteImport } from './routes/db/invoices-index' -import { Route as dbInvoiceDetailRouteImport } from './routes/db/invoice-detail' +import { Route as dbDashboardInvoicesRouteImport } from './routes/db/dashboard-invoices' +import { Route as dbDashboardIndexRouteImport } from './routes/db/dashboard-index' import { Route as HelloFooIndexRouteImport } from './routes/subtree/foo/index' import { Route as HelloFooIdRouteImport } from './routes/subtree/foo/$id' +import { Route as dbInvoiceDetailRouteImport } from './routes/db/invoice-detail' +import { Route as dbInvoicesIndexRouteImport } from './routes/db/invoices-index' -const indexRoute = indexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const layoutRoute = layoutRouteImport.update({ id: '/_layout', getParentRoute: () => rootRouteImport, } as any) -const pagesRoute = pagesRouteImport.update({ - id: '/$lang/', - path: '/$lang/', +const indexRoute = indexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const dbDashboardRoute = dbDashboardRouteImport.update({ @@ -40,30 +35,25 @@ const dbDashboardRoute = dbDashboardRouteImport.update({ path: '/dashboard', getParentRoute: () => layoutRoute, } as any) -const dbDashboardIndexRoute = dbDashboardIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => dbDashboardRoute, -} as any) -const dbDashboardInvoicesRoute = dbDashboardInvoicesRouteImport.update({ - id: '/invoices', - path: '/invoices', - getParentRoute: () => dbDashboardRoute, +const pagesRoute = pagesRouteImport.update({ + id: '/$lang/', + path: '/$lang/', + getParentRoute: () => rootRouteImport, } as any) const HelloIndexRoute = HelloIndexRouteImport.update({ id: '/hello/', path: '/hello/', getParentRoute: () => layoutRoute, } as any) -const dbInvoicesIndexRoute = dbInvoicesIndexRouteImport.update({ +const dbDashboardInvoicesRoute = dbDashboardInvoicesRouteImport.update({ + id: '/invoices', + path: '/invoices', + getParentRoute: () => dbDashboardRoute, +} as any) +const dbDashboardIndexRoute = dbDashboardIndexRouteImport.update({ id: '/', path: '/', - getParentRoute: () => dbDashboardInvoicesRoute, -} as any) -const dbInvoiceDetailRoute = dbInvoiceDetailRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => dbDashboardInvoicesRoute, + getParentRoute: () => dbDashboardRoute, } as any) const HelloFooIndexRoute = HelloFooIndexRouteImport.update({ id: '/hello/foo/', @@ -75,6 +65,16 @@ const HelloFooIdRoute = HelloFooIdRouteImport.update({ path: '/hello/foo/$id', getParentRoute: () => layoutRoute, } as any) +const dbInvoiceDetailRoute = dbInvoiceDetailRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => dbDashboardInvoicesRoute, +} as any) +const dbInvoicesIndexRoute = dbInvoicesIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => dbDashboardInvoicesRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof indexRoute @@ -158,13 +158,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof indexRouteImport - parentRoute: typeof rootRouteImport - } '/_layout': { id: '/_layout' path: '' @@ -172,11 +165,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof layoutRouteImport parentRoute: typeof rootRouteImport } - '/$lang/': { - id: '/$lang/' - path: '/$lang' - fullPath: '/$lang/' - preLoaderRoute: typeof pagesRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof indexRouteImport parentRoute: typeof rootRouteImport } '/_layout/dashboard': { @@ -186,19 +179,12 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof dbDashboardRouteImport parentRoute: typeof layoutRoute } - '/_layout/dashboard/': { - id: '/_layout/dashboard/' - path: '/' - fullPath: '/dashboard/' - preLoaderRoute: typeof dbDashboardIndexRouteImport - parentRoute: typeof dbDashboardRoute - } - '/_layout/dashboard/invoices': { - id: '/_layout/dashboard/invoices' - path: '/invoices' - fullPath: '/dashboard/invoices' - preLoaderRoute: typeof dbDashboardInvoicesRouteImport - parentRoute: typeof dbDashboardRoute + '/$lang/': { + id: '/$lang/' + path: '/$lang' + fullPath: '/$lang/' + preLoaderRoute: typeof pagesRouteImport + parentRoute: typeof rootRouteImport } '/_layout/hello/': { id: '/_layout/hello/' @@ -207,19 +193,19 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof HelloIndexRouteImport parentRoute: typeof layoutRoute } - '/_layout/dashboard/invoices/': { - id: '/_layout/dashboard/invoices/' - path: '/' - fullPath: '/dashboard/invoices/' - preLoaderRoute: typeof dbInvoicesIndexRouteImport - parentRoute: typeof dbDashboardInvoicesRoute + '/_layout/dashboard/invoices': { + id: '/_layout/dashboard/invoices' + path: '/invoices' + fullPath: '/dashboard/invoices' + preLoaderRoute: typeof dbDashboardInvoicesRouteImport + parentRoute: typeof dbDashboardRoute } - '/_layout/dashboard/invoices/$id': { - id: '/_layout/dashboard/invoices/$id' - path: '/$id' - fullPath: '/dashboard/invoices/$id' - preLoaderRoute: typeof dbInvoiceDetailRouteImport - parentRoute: typeof dbDashboardInvoicesRoute + '/_layout/dashboard/': { + id: '/_layout/dashboard/' + path: '/' + fullPath: '/dashboard/' + preLoaderRoute: typeof dbDashboardIndexRouteImport + parentRoute: typeof dbDashboardRoute } '/_layout/hello/foo/': { id: '/_layout/hello/foo/' @@ -235,6 +221,20 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof HelloFooIdRouteImport parentRoute: typeof layoutRoute } + '/_layout/dashboard/invoices/$id': { + id: '/_layout/dashboard/invoices/$id' + path: '/$id' + fullPath: '/dashboard/invoices/$id' + preLoaderRoute: typeof dbInvoiceDetailRouteImport + parentRoute: typeof dbDashboardInvoicesRoute + } + '/_layout/dashboard/invoices/': { + id: '/_layout/dashboard/invoices/' + path: '/' + fullPath: '/dashboard/invoices/' + preLoaderRoute: typeof dbInvoicesIndexRouteImport + parentRoute: typeof dbDashboardInvoicesRoute + } } } diff --git a/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/aliased/virtual-routes.ts b/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/aliased/virtual-routes.ts deleted file mode 100644 index ed71a051e8..0000000000 --- a/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/aliased/virtual-routes.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { physical } from '@tanstack/virtual-file-routes' - -export const helloSubtree = physical('/hello', 'subtree') diff --git a/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routeTree.snapshot.ts b/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routeTree.snapshot.ts deleted file mode 100644 index 6b16924d5b..0000000000 --- a/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routeTree.snapshot.ts +++ /dev/null @@ -1,292 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/root' -import { Route as indexRouteImport } from './routes/index' -import { Route as layoutRouteImport } from './routes/layout' -import { Route as pagesRouteImport } from './routes/pages' -import { Route as dbDashboardRouteImport } from './routes/db/dashboard' -import { Route as dbDashboardIndexRouteImport } from './routes/db/dashboard-index' -import { Route as dbDashboardInvoicesRouteImport } from './routes/db/dashboard-invoices' -import { Route as HelloIndexRouteImport } from './routes/subtree/index' -import { Route as dbInvoicesIndexRouteImport } from './routes/db/invoices-index' -import { Route as dbInvoiceDetailRouteImport } from './routes/db/invoice-detail' -import { Route as HelloFooIndexRouteImport } from './routes/subtree/foo/index' -import { Route as HelloFooIdRouteImport } from './routes/subtree/foo/$id' - -const indexRoute = indexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const layoutRoute = layoutRouteImport.update({ - id: '/_layout', - getParentRoute: () => rootRouteImport, -} as any) -const pagesRoute = pagesRouteImport.update({ - id: '/$lang/', - path: '/$lang/', - getParentRoute: () => rootRouteImport, -} as any) -const dbDashboardRoute = dbDashboardRouteImport.update({ - id: '/dashboard', - path: '/dashboard', - getParentRoute: () => layoutRoute, -} as any) -const dbDashboardIndexRoute = dbDashboardIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => dbDashboardRoute, -} as any) -const dbDashboardInvoicesRoute = dbDashboardInvoicesRouteImport.update({ - id: '/invoices', - path: '/invoices', - getParentRoute: () => dbDashboardRoute, -} as any) -const HelloIndexRoute = HelloIndexRouteImport.update({ - id: '/hello/', - path: '/hello/', - getParentRoute: () => layoutRoute, -} as any) -const dbInvoicesIndexRoute = dbInvoicesIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => dbDashboardInvoicesRoute, -} as any) -const dbInvoiceDetailRoute = dbInvoiceDetailRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => dbDashboardInvoicesRoute, -} as any) -const HelloFooIndexRoute = HelloFooIndexRouteImport.update({ - id: '/hello/foo/', - path: '/hello/foo/', - getParentRoute: () => layoutRoute, -} as any) -const HelloFooIdRoute = HelloFooIdRouteImport.update({ - id: '/hello/foo/$id', - path: '/hello/foo/$id', - getParentRoute: () => layoutRoute, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof indexRoute - '/$lang/': typeof pagesRoute - '/dashboard': typeof dbDashboardRouteWithChildren - '/dashboard/': typeof dbDashboardIndexRoute - '/dashboard/invoices': typeof dbDashboardInvoicesRouteWithChildren - '/hello/': typeof HelloIndexRoute - '/dashboard/invoices/': typeof dbInvoicesIndexRoute - '/dashboard/invoices/$id': typeof dbInvoiceDetailRoute - '/hello/foo/$id': typeof HelloFooIdRoute - '/hello/foo/': typeof HelloFooIndexRoute -} -export interface FileRoutesByTo { - '/': typeof indexRoute - '/$lang': typeof pagesRoute - '/dashboard': typeof dbDashboardIndexRoute - '/hello': typeof HelloIndexRoute - '/dashboard/invoices': typeof dbInvoicesIndexRoute - '/dashboard/invoices/$id': typeof dbInvoiceDetailRoute - '/hello/foo/$id': typeof HelloFooIdRoute - '/hello/foo': typeof HelloFooIndexRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof indexRoute - '/_layout': typeof layoutRouteWithChildren - '/$lang/': typeof pagesRoute - '/_layout/dashboard': typeof dbDashboardRouteWithChildren - '/_layout/dashboard/': typeof dbDashboardIndexRoute - '/_layout/dashboard/invoices': typeof dbDashboardInvoicesRouteWithChildren - '/_layout/hello/': typeof HelloIndexRoute - '/_layout/dashboard/invoices/': typeof dbInvoicesIndexRoute - '/_layout/dashboard/invoices/$id': typeof dbInvoiceDetailRoute - '/_layout/hello/foo/$id': typeof HelloFooIdRoute - '/_layout/hello/foo/': typeof HelloFooIndexRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/$lang/' - | '/dashboard' - | '/dashboard/' - | '/dashboard/invoices' - | '/hello/' - | '/dashboard/invoices/' - | '/dashboard/invoices/$id' - | '/hello/foo/$id' - | '/hello/foo/' - fileRoutesByTo: FileRoutesByTo - to: - | '/' - | '/$lang' - | '/dashboard' - | '/hello' - | '/dashboard/invoices' - | '/dashboard/invoices/$id' - | '/hello/foo/$id' - | '/hello/foo' - id: - | '__root__' - | '/' - | '/_layout' - | '/$lang/' - | '/_layout/dashboard' - | '/_layout/dashboard/' - | '/_layout/dashboard/invoices' - | '/_layout/hello/' - | '/_layout/dashboard/invoices/' - | '/_layout/dashboard/invoices/$id' - | '/_layout/hello/foo/$id' - | '/_layout/hello/foo/' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - indexRoute: typeof indexRoute - layoutRoute: typeof layoutRouteWithChildren - pagesRoute: typeof pagesRoute -} - -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 - } - '/$lang/': { - id: '/$lang/' - path: '/$lang' - fullPath: '/$lang/' - preLoaderRoute: typeof pagesRouteImport - parentRoute: typeof rootRouteImport - } - '/_layout/dashboard': { - id: '/_layout/dashboard' - path: '/dashboard' - fullPath: '/dashboard' - preLoaderRoute: typeof dbDashboardRouteImport - parentRoute: typeof layoutRoute - } - '/_layout/dashboard/': { - id: '/_layout/dashboard/' - path: '/' - fullPath: '/dashboard/' - preLoaderRoute: typeof dbDashboardIndexRouteImport - parentRoute: typeof dbDashboardRoute - } - '/_layout/dashboard/invoices': { - id: '/_layout/dashboard/invoices' - path: '/invoices' - fullPath: '/dashboard/invoices' - preLoaderRoute: typeof dbDashboardInvoicesRouteImport - parentRoute: typeof dbDashboardRoute - } - '/_layout/hello/': { - id: '/_layout/hello/' - path: '/hello' - fullPath: '/hello/' - preLoaderRoute: typeof HelloIndexRouteImport - parentRoute: typeof layoutRoute - } - '/_layout/dashboard/invoices/': { - id: '/_layout/dashboard/invoices/' - path: '/' - fullPath: '/dashboard/invoices/' - preLoaderRoute: typeof dbInvoicesIndexRouteImport - parentRoute: typeof dbDashboardInvoicesRoute - } - '/_layout/dashboard/invoices/$id': { - id: '/_layout/dashboard/invoices/$id' - path: '/$id' - fullPath: '/dashboard/invoices/$id' - preLoaderRoute: typeof dbInvoiceDetailRouteImport - parentRoute: typeof dbDashboardInvoicesRoute - } - '/_layout/hello/foo/': { - id: '/_layout/hello/foo/' - path: '/hello/foo' - fullPath: '/hello/foo/' - preLoaderRoute: typeof HelloFooIndexRouteImport - parentRoute: typeof layoutRoute - } - '/_layout/hello/foo/$id': { - id: '/_layout/hello/foo/$id' - path: '/hello/foo/$id' - fullPath: '/hello/foo/$id' - preLoaderRoute: typeof HelloFooIdRouteImport - parentRoute: typeof layoutRoute - } - } -} - -interface dbDashboardInvoicesRouteChildren { - dbInvoicesIndexRoute: typeof dbInvoicesIndexRoute - dbInvoiceDetailRoute: typeof dbInvoiceDetailRoute -} - -const dbDashboardInvoicesRouteChildren: dbDashboardInvoicesRouteChildren = { - dbInvoicesIndexRoute: dbInvoicesIndexRoute, - dbInvoiceDetailRoute: dbInvoiceDetailRoute, -} - -const dbDashboardInvoicesRouteWithChildren = - dbDashboardInvoicesRoute._addFileChildren(dbDashboardInvoicesRouteChildren) - -interface dbDashboardRouteChildren { - dbDashboardIndexRoute: typeof dbDashboardIndexRoute - dbDashboardInvoicesRoute: typeof dbDashboardInvoicesRouteWithChildren -} - -const dbDashboardRouteChildren: dbDashboardRouteChildren = { - dbDashboardIndexRoute: dbDashboardIndexRoute, - dbDashboardInvoicesRoute: dbDashboardInvoicesRouteWithChildren, -} - -const dbDashboardRouteWithChildren = dbDashboardRoute._addFileChildren( - dbDashboardRouteChildren, -) - -interface layoutRouteChildren { - dbDashboardRoute: typeof dbDashboardRouteWithChildren - HelloIndexRoute: typeof HelloIndexRoute - HelloFooIdRoute: typeof HelloFooIdRoute - HelloFooIndexRoute: typeof HelloFooIndexRoute -} - -const layoutRouteChildren: layoutRouteChildren = { - dbDashboardRoute: dbDashboardRouteWithChildren, - HelloIndexRoute: HelloIndexRoute, - HelloFooIdRoute: HelloFooIdRoute, - HelloFooIndexRoute: HelloFooIndexRoute, -} - -const layoutRouteWithChildren = - layoutRoute._addFileChildren(layoutRouteChildren) - -const rootRouteChildren: RootRouteChildren = { - indexRoute: indexRoute, - layoutRoute: layoutRouteWithChildren, - pagesRoute: pagesRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes<FileRouteTypes>() diff --git a/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routes.ts b/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routes.ts deleted file mode 100644 index 149e6ae4c1..0000000000 --- a/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routes.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @ts-nocheck - -import { index, layout, rootRoute, route } from '@tanstack/virtual-file-routes' -import { helloSubtree } from '@/virtual-routes' - -export default rootRoute('root.tsx', [ - index('index.tsx'), - route('$lang', [index('pages.tsx')]), - layout('layout.tsx', [ - route('/dashboard', 'db/dashboard.tsx', [ - index('db/dashboard-index.tsx'), - route('/invoices', 'db/dashboard-invoices.tsx', [ - index('db/invoices-index.tsx'), - route('$id', 'db/invoice-detail.tsx'), - ]), - ]), - helloSubtree, - ]), -]) diff --git a/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routes/db/dashboard-index.tsx b/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routes/db/dashboard-index.tsx deleted file mode 100644 index ecd8cce943..0000000000 --- a/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routes/db/dashboard-index.tsx +++ /dev/null @@ -1,4 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/_layout/dashboard/')({ - component: () => <div>Hello !</div>, -}) diff --git a/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routes/db/dashboard-invoices.tsx b/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routes/db/dashboard-invoices.tsx deleted file mode 100644 index 0997d6d9f5..0000000000 --- a/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routes/db/dashboard-invoices.tsx +++ /dev/null @@ -1,4 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/_layout/dashboard/invoices')({ - component: () => <div>Hello !</div>, -}) diff --git a/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routes/db/dashboard.tsx b/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routes/db/dashboard.tsx deleted file mode 100644 index 5963d884c6..0000000000 --- a/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routes/db/dashboard.tsx +++ /dev/null @@ -1,4 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/_layout/dashboard')({ - component: () => <div>Hello !</div>, -}) diff --git a/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routes/db/invoice-detail.tsx b/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routes/db/invoice-detail.tsx deleted file mode 100644 index 5226e399a4..0000000000 --- a/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routes/db/invoice-detail.tsx +++ /dev/null @@ -1,4 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/_layout/dashboard/invoices/$id')({ - component: () => <div>Hello /_layout/dashboard/invoices/$id!</div>, -}) diff --git a/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routes/db/invoices-index.tsx b/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routes/db/invoices-index.tsx deleted file mode 100644 index c2024685a8..0000000000 --- a/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routes/db/invoices-index.tsx +++ /dev/null @@ -1,4 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/_layout/dashboard/invoices/')({ - component: () => <div>Hello /_layout/dashboard/invoices/!</div>, -}) diff --git a/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routes/index.tsx b/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routes/index.tsx deleted file mode 100644 index 2f80221276..0000000000 --- a/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routes/index.tsx +++ /dev/null @@ -1,4 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/')({ - component: () => <div>Hello !</div>, -}) diff --git a/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routes/layout.tsx b/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routes/layout.tsx deleted file mode 100644 index 268d6c5c7d..0000000000 --- a/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routes/layout.tsx +++ /dev/null @@ -1,4 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/_layout')({ - component: () => <div>Hello !</div>, -}) diff --git a/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routes/pages.tsx b/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routes/pages.tsx deleted file mode 100644 index 5e4d543b3e..0000000000 --- a/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routes/pages.tsx +++ /dev/null @@ -1,10 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import * as React from 'react' - -export const Route = createFileRoute('/$lang/')({ - component: RouteComponent, -}) - -function RouteComponent() { - return <div>Hello "/$lang/"!</div> -} diff --git a/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routes/root.tsx b/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routes/root.tsx deleted file mode 100644 index a294139860..0000000000 --- a/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routes/root.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/')({ - component: () => <div>Hello !</div>, -}) diff --git a/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routes/subtree/foo/$id.tsx b/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routes/subtree/foo/$id.tsx deleted file mode 100644 index 62bf75cc7f..0000000000 --- a/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routes/subtree/foo/$id.tsx +++ /dev/null @@ -1,4 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/_layout/hello/foo/$id')({ - component: () => <div>Hello /foo/$id!</div>, -}) diff --git a/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routes/subtree/foo/index.tsx b/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routes/subtree/foo/index.tsx deleted file mode 100644 index b2355f12fd..0000000000 --- a/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routes/subtree/foo/index.tsx +++ /dev/null @@ -1,4 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/_layout/hello/foo/')({ - component: () => <div>Hello /foo/!</div>, -}) diff --git a/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routes/subtree/index.tsx b/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routes/subtree/index.tsx deleted file mode 100644 index c85f0fb295..0000000000 --- a/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/routes/subtree/index.tsx +++ /dev/null @@ -1,4 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/_layout/hello/')({ - component: () => <div>Hello /!</div>, -}) diff --git a/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/tsconfig.json b/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/tsconfig.json deleted file mode 100644 index 7426947cc5..0000000000 --- a/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/tsconfig.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "compilerOptions": { - "paths": { - "@/*": ["./aliased/*"] - } - } -} diff --git a/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/tsr.config.json b/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/tsr.config.json deleted file mode 100644 index 4d587108e3..0000000000 --- a/packages/router-generator/tests/generator/virtual-config-file-tsconfig-paths/tsr.config.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "routesDirectory": "./routes", - "generatedRouteTree": "./routeTree.gen.ts", - "virtualRouteConfig": "./routes.ts" -} diff --git a/packages/router-generator/tests/generator/virtual-explicit-dotted-paths/routeTree.snapshot.ts b/packages/router-generator/tests/generator/virtual-explicit-dotted-paths/routeTree.snapshot.ts deleted file mode 100644 index 6a5263d55b..0000000000 --- a/packages/router-generator/tests/generator/virtual-explicit-dotted-paths/routeTree.snapshot.ts +++ /dev/null @@ -1,77 +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 directRouteImport } from './routes/direct' -import { Route as MountedDotpathIndexRouteImport } from './routes/physical-routes/index' - -const directRoute = directRouteImport.update({ - id: '/direct.path', - path: '/direct.path', - getParentRoute: () => rootRouteImport, -} as any) -const MountedDotpathIndexRoute = MountedDotpathIndexRouteImport.update({ - id: '/mounted.path/', - path: '/mounted.path/', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/direct.path': typeof directRoute - '/mounted.path/': typeof MountedDotpathIndexRoute -} -export interface FileRoutesByTo { - '/direct.path': typeof directRoute - '/mounted.path': typeof MountedDotpathIndexRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/direct.path': typeof directRoute - '/mounted.path/': typeof MountedDotpathIndexRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/direct.path' | '/mounted.path/' - fileRoutesByTo: FileRoutesByTo - to: '/direct.path' | '/mounted.path' - id: '__root__' | '/direct.path' | '/mounted.path/' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - directRoute: typeof directRoute - MountedDotpathIndexRoute: typeof MountedDotpathIndexRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/direct.path': { - id: '/direct.path' - path: '/direct.path' - fullPath: '/direct.path' - preLoaderRoute: typeof directRouteImport - parentRoute: typeof rootRouteImport - } - '/mounted.path/': { - id: '/mounted.path/' - path: '/mounted.path' - fullPath: '/mounted.path/' - preLoaderRoute: typeof MountedDotpathIndexRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - directRoute: directRoute, - MountedDotpathIndexRoute: MountedDotpathIndexRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes<FileRouteTypes>() diff --git a/packages/router-generator/tests/generator/virtual-explicit-dotted-paths/routes/direct.tsx b/packages/router-generator/tests/generator/virtual-explicit-dotted-paths/routes/direct.tsx deleted file mode 100644 index e56ad97d40..0000000000 --- a/packages/router-generator/tests/generator/virtual-explicit-dotted-paths/routes/direct.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/direct.path')({ - component: () => 'Direct', -}) diff --git a/packages/router-generator/tests/generator/virtual-explicit-dotted-paths/routes/physical-routes/index.tsx b/packages/router-generator/tests/generator/virtual-explicit-dotted-paths/routes/physical-routes/index.tsx deleted file mode 100644 index 2e768e44ac..0000000000 --- a/packages/router-generator/tests/generator/virtual-explicit-dotted-paths/routes/physical-routes/index.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/mounted.path/')({ - component: () => 'Mounted index', -}) diff --git a/packages/router-generator/tests/generator/virtual-explicit-dotted-paths/routes/root.tsx b/packages/router-generator/tests/generator/virtual-explicit-dotted-paths/routes/root.tsx deleted file mode 100644 index 9c657c7d5b..0000000000 --- a/packages/router-generator/tests/generator/virtual-explicit-dotted-paths/routes/root.tsx +++ /dev/null @@ -1,3 +0,0 @@ -import { createRootRoute } from '@tanstack/react-router' - -export const Route = createRootRoute() diff --git a/packages/router-generator/tests/generator/virtual-inside-nested/routeTree.snapshot.ts b/packages/router-generator/tests/generator/virtual-inside-nested/routeTree.snapshot.ts index 37de7dc290..174f18465b 100644 --- a/packages/router-generator/tests/generator/virtual-inside-nested/routeTree.snapshot.ts +++ b/packages/router-generator/tests/generator/virtual-inside-nested/routeTree.snapshot.ts @@ -11,8 +11,8 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' import { Route as FooBarRouteImport } from './routes/foo/bar' -import { Route as FooBarHomeRouteImport } from './routes/foo/bar/home' -import { Route as FooBarDetailsRouteImport } from './routes/foo/bar/details' +import { Route as fooBarDetailsRouteImport } from './routes/foo/bar/details' +import { Route as fooBarHomeRouteImport } from './routes/foo/bar/home' const IndexRoute = IndexRouteImport.update({ id: '/', @@ -24,34 +24,34 @@ const FooBarRoute = FooBarRouteImport.update({ path: '/foo/bar', getParentRoute: () => rootRouteImport, } as any) -const FooBarHomeRoute = FooBarHomeRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => FooBarRoute, -} as any) -const FooBarDetailsRoute = FooBarDetailsRouteImport.update({ +const fooBarDetailsRoute = fooBarDetailsRouteImport.update({ id: '/$id', path: '/$id', getParentRoute: () => FooBarRoute, } as any) +const fooBarHomeRoute = fooBarHomeRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => FooBarRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute '/foo/bar': typeof FooBarRouteWithChildren - '/foo/bar/': typeof FooBarHomeRoute - '/foo/bar/$id': typeof FooBarDetailsRoute + '/foo/bar/': typeof fooBarHomeRoute + '/foo/bar/$id': typeof fooBarDetailsRoute } export interface FileRoutesByTo { '/': typeof IndexRoute - '/foo/bar': typeof FooBarHomeRoute - '/foo/bar/$id': typeof FooBarDetailsRoute + '/foo/bar': typeof fooBarHomeRoute + '/foo/bar/$id': typeof fooBarDetailsRoute } export interface FileRoutesById { __root__: typeof rootRouteImport '/': typeof IndexRoute '/foo/bar': typeof FooBarRouteWithChildren - '/foo/bar/': typeof FooBarHomeRoute - '/foo/bar/$id': typeof FooBarDetailsRoute + '/foo/bar/': typeof fooBarHomeRoute + '/foo/bar/$id': typeof fooBarDetailsRoute } export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath @@ -82,31 +82,31 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof FooBarRouteImport parentRoute: typeof rootRouteImport } - '/foo/bar/': { - id: '/foo/bar/' - path: '/' - fullPath: '/foo/bar/' - preLoaderRoute: typeof FooBarHomeRouteImport - parentRoute: typeof FooBarRoute - } '/foo/bar/$id': { id: '/foo/bar/$id' path: '/$id' fullPath: '/foo/bar/$id' - preLoaderRoute: typeof FooBarDetailsRouteImport + preLoaderRoute: typeof fooBarDetailsRouteImport + parentRoute: typeof FooBarRoute + } + '/foo/bar/': { + id: '/foo/bar/' + path: '/' + fullPath: '/foo/bar/' + preLoaderRoute: typeof fooBarHomeRouteImport parentRoute: typeof FooBarRoute } } } interface FooBarRouteChildren { - FooBarHomeRoute: typeof FooBarHomeRoute - FooBarDetailsRoute: typeof FooBarDetailsRoute + fooBarHomeRoute: typeof fooBarHomeRoute + fooBarDetailsRoute: typeof fooBarDetailsRoute } const FooBarRouteChildren: FooBarRouteChildren = { - FooBarHomeRoute: FooBarHomeRoute, - FooBarDetailsRoute: FooBarDetailsRoute, + fooBarHomeRoute: fooBarHomeRoute, + fooBarDetailsRoute: fooBarDetailsRoute, } const FooBarRouteWithChildren = diff --git a/packages/router-generator/tests/generator/virtual-inside-with-escaped-underscore/routeTree.snapshot.ts b/packages/router-generator/tests/generator/virtual-inside-with-escaped-underscore/routeTree.snapshot.ts index 340a1f0f5e..28aebc0aad 100644 --- a/packages/router-generator/tests/generator/virtual-inside-with-escaped-underscore/routeTree.snapshot.ts +++ b/packages/router-generator/tests/generator/virtual-inside-with-escaped-underscore/routeTree.snapshot.ts @@ -10,49 +10,49 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' -import { Route as NestedHomeRouteImport } from './routes/nested/home' -import { Route as NestedAuthRouteImport } from './routes/nested/auth' -import { Route as NestedCallbackRouteImport } from './routes/nested/callback' +import { Route as nestedCallbackRouteImport } from './routes/nested/callback' +import { Route as nestedAuthRouteImport } from './routes/nested/auth' +import { Route as nestedHomeRouteImport } from './routes/nested/home' const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const NestedHomeRoute = NestedHomeRouteImport.update({ - id: '/nested/', - path: '/nested/', +const nestedCallbackRoute = nestedCallbackRouteImport.update({ + id: '/nested/_callback', + path: '/nested/_callback', getParentRoute: () => rootRouteImport, } as any) -const NestedAuthRoute = NestedAuthRouteImport.update({ +const nestedAuthRoute = nestedAuthRouteImport.update({ id: '/nested/_auth', path: '/nested/_auth', getParentRoute: () => rootRouteImport, } as any) -const NestedCallbackRoute = NestedCallbackRouteImport.update({ - id: '/nested/_callback', - path: '/nested/_callback', +const nestedHomeRoute = nestedHomeRouteImport.update({ + id: '/nested/', + path: '/nested/', getParentRoute: () => rootRouteImport, } as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute - '/nested/': typeof NestedHomeRoute - '/nested/_auth': typeof NestedAuthRoute - '/nested/_callback': typeof NestedCallbackRoute + '/nested/': typeof nestedHomeRoute + '/nested/_auth': typeof nestedAuthRoute + '/nested/_callback': typeof nestedCallbackRoute } export interface FileRoutesByTo { '/': typeof IndexRoute - '/nested': typeof NestedHomeRoute - '/nested/_auth': typeof NestedAuthRoute - '/nested/_callback': typeof NestedCallbackRoute + '/nested': typeof nestedHomeRoute + '/nested/_auth': typeof nestedAuthRoute + '/nested/_callback': typeof nestedCallbackRoute } export interface FileRoutesById { __root__: typeof rootRouteImport '/': typeof IndexRoute - '/nested/': typeof NestedHomeRoute - '/nested/_auth': typeof NestedAuthRoute - '/nested/_callback': typeof NestedCallbackRoute + '/nested/': typeof nestedHomeRoute + '/nested/_auth': typeof nestedAuthRoute + '/nested/_callback': typeof nestedCallbackRoute } export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath @@ -64,9 +64,9 @@ export interface FileRouteTypes { } export interface RootRouteChildren { IndexRoute: typeof IndexRoute - NestedHomeRoute: typeof NestedHomeRoute - NestedAuthRoute: typeof NestedAuthRoute - NestedCallbackRoute: typeof NestedCallbackRoute + nestedHomeRoute: typeof nestedHomeRoute + nestedAuthRoute: typeof nestedAuthRoute + nestedCallbackRoute: typeof nestedCallbackRoute } declare module '@tanstack/react-router' { @@ -78,25 +78,25 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/nested/': { - id: '/nested/' - path: '/nested' - fullPath: '/nested/' - preLoaderRoute: typeof NestedHomeRouteImport + '/nested/_callback': { + id: '/nested/_callback' + path: '/nested/_callback' + fullPath: '/nested/_callback' + preLoaderRoute: typeof nestedCallbackRouteImport parentRoute: typeof rootRouteImport } '/nested/_auth': { id: '/nested/_auth' path: '/nested/_auth' fullPath: '/nested/_auth' - preLoaderRoute: typeof NestedAuthRouteImport + preLoaderRoute: typeof nestedAuthRouteImport parentRoute: typeof rootRouteImport } - '/nested/_callback': { - id: '/nested/_callback' - path: '/nested/_callback' - fullPath: '/nested/_callback' - preLoaderRoute: typeof NestedCallbackRouteImport + '/nested/': { + id: '/nested/' + path: '/nested' + fullPath: '/nested/' + preLoaderRoute: typeof nestedHomeRouteImport parentRoute: typeof rootRouteImport } } @@ -104,9 +104,9 @@ declare module '@tanstack/react-router' { const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, - NestedHomeRoute: NestedHomeRoute, - NestedAuthRoute: NestedAuthRoute, - NestedCallbackRoute: NestedCallbackRoute, + nestedHomeRoute: nestedHomeRoute, + nestedAuthRoute: nestedAuthRoute, + nestedCallbackRoute: nestedCallbackRoute, } export const routeTree = rootRouteImport ._addFileChildren(rootRouteChildren) diff --git a/packages/router-generator/tests/generator/virtual-nested-layouts-with-virtual-route/routeTree.snapshot.ts b/packages/router-generator/tests/generator/virtual-nested-layouts-with-virtual-route/routeTree.snapshot.ts index f4970bd003..e991cd3964 100644 --- a/packages/router-generator/tests/generator/virtual-nested-layouts-with-virtual-route/routeTree.snapshot.ts +++ b/packages/router-generator/tests/generator/virtual-nested-layouts-with-virtual-route/routeTree.snapshot.ts @@ -9,35 +9,35 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as homeRouteImport } from './routes/home' import { Route as layoutFirstLayoutRouteImport } from './routes/layout/first-layout' +import { Route as homeRouteImport } from './routes/home' import { Route as layoutSecondLayoutRouteImport } from './routes/layout/second-layout' -import { Route as aRouteImport } from './routes/a' import { Route as bRouteImport } from './routes/b' +import { Route as aRouteImport } from './routes/a' +const layoutFirstLayoutRoute = layoutFirstLayoutRouteImport.update({ + id: '/_first', + getParentRoute: () => rootRouteImport, +} as any) const homeRoute = homeRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const layoutFirstLayoutRoute = layoutFirstLayoutRouteImport.update({ - id: '/_first', - getParentRoute: () => rootRouteImport, -} as any) const layoutSecondLayoutRoute = layoutSecondLayoutRouteImport.update({ id: '/_second-layout', getParentRoute: () => layoutFirstLayoutRoute, } 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) +const aRoute = aRouteImport.update({ + id: '/route-without-file/layout-a', + path: '/route-without-file/layout-a', + getParentRoute: () => layoutSecondLayoutRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof homeRoute @@ -60,7 +60,9 @@ export interface FileRoutesById { export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath fullPaths: - '/' | '/route-without-file/layout-a' | '/route-without-file/layout-b' + | '/' + | '/route-without-file/layout-a' + | '/route-without-file/layout-b' fileRoutesByTo: FileRoutesByTo to: '/' | '/route-without-file/layout-a' | '/route-without-file/layout-b' id: @@ -79,13 +81,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof homeRouteImport - parentRoute: typeof rootRouteImport - } '/_first': { id: '/_first' path: '' @@ -93,6 +88,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof layoutFirstLayoutRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof homeRouteImport + parentRoute: typeof rootRouteImport + } '/_first/_second-layout': { id: '/_first/_second-layout' path: '' @@ -100,13 +102,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof layoutSecondLayoutRouteImport parentRoute: typeof layoutFirstLayoutRoute } - '/_first/_second-layout/route-without-file/layout-a': { - id: '/_first/_second-layout/route-without-file/layout-a' - path: '/route-without-file/layout-a' - fullPath: '/route-without-file/layout-a' - 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' @@ -114,6 +109,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof bRouteImport parentRoute: typeof layoutSecondLayoutRoute } + '/_first/_second-layout/route-without-file/layout-a': { + id: '/_first/_second-layout/route-without-file/layout-a' + path: '/route-without-file/layout-a' + fullPath: '/route-without-file/layout-a' + preLoaderRoute: typeof aRouteImport + parentRoute: typeof layoutSecondLayoutRoute + } } } diff --git a/packages/router-generator/tests/generator/virtual-pathless-layout-dotted-filename/routeTree.snapshot.ts b/packages/router-generator/tests/generator/virtual-pathless-layout-dotted-filename/routeTree.snapshot.ts deleted file mode 100644 index e9d9980378..0000000000 --- a/packages/router-generator/tests/generator/virtual-pathless-layout-dotted-filename/routeTree.snapshot.ts +++ /dev/null @@ -1,101 +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.route' -import { Route as indexDotrouteRouteImport } from './routes/index.route' -import { Route as pathlessDotlayoutRouteImport } from './routes/pathless.layout' -import { Route as subpathDotrouteRouteImport } from './routes/subpath.route' - -const indexDotrouteRoute = indexDotrouteRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const pathlessDotlayoutRoute = pathlessDotlayoutRouteImport.update({ - id: '/_pathless.layout', - getParentRoute: () => rootRouteImport, -} as any) -const subpathDotrouteRoute = subpathDotrouteRouteImport.update({ - id: '/subpath', - path: '/subpath', - getParentRoute: () => pathlessDotlayoutRoute, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof indexDotrouteRoute - '/subpath': typeof subpathDotrouteRoute -} -export interface FileRoutesByTo { - '/': typeof indexDotrouteRoute - '/subpath': typeof subpathDotrouteRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof indexDotrouteRoute - '/_pathless.layout': typeof pathlessDotlayoutRouteWithChildren - '/_pathless.layout/subpath': typeof subpathDotrouteRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/subpath' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/subpath' - id: '__root__' | '/' | '/_pathless.layout' | '/_pathless.layout/subpath' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - indexDotrouteRoute: typeof indexDotrouteRoute - pathlessDotlayoutRoute: typeof pathlessDotlayoutRouteWithChildren -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof indexDotrouteRouteImport - parentRoute: typeof rootRouteImport - } - '/_pathless.layout': { - id: '/_pathless.layout' - path: '' - fullPath: '/' - preLoaderRoute: typeof pathlessDotlayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/_pathless.layout/subpath': { - id: '/_pathless.layout/subpath' - path: '/subpath' - fullPath: '/subpath' - preLoaderRoute: typeof subpathDotrouteRouteImport - parentRoute: typeof pathlessDotlayoutRoute - } - } -} - -interface pathlessDotlayoutRouteChildren { - subpathDotrouteRoute: typeof subpathDotrouteRoute -} - -const pathlessDotlayoutRouteChildren: pathlessDotlayoutRouteChildren = { - subpathDotrouteRoute: subpathDotrouteRoute, -} - -const pathlessDotlayoutRouteWithChildren = - pathlessDotlayoutRoute._addFileChildren(pathlessDotlayoutRouteChildren) - -const rootRouteChildren: RootRouteChildren = { - indexDotrouteRoute: indexDotrouteRoute, - pathlessDotlayoutRoute: pathlessDotlayoutRouteWithChildren, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes<FileRouteTypes>() diff --git a/packages/router-generator/tests/generator/virtual-pathless-layout-dotted-filename/routes/index.route.tsx b/packages/router-generator/tests/generator/virtual-pathless-layout-dotted-filename/routes/index.route.tsx deleted file mode 100644 index 379428d7b2..0000000000 --- a/packages/router-generator/tests/generator/virtual-pathless-layout-dotted-filename/routes/index.route.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/')({ - component: () => 'Index', -}) diff --git a/packages/router-generator/tests/generator/virtual-pathless-layout-dotted-filename/routes/pathless.layout.tsx b/packages/router-generator/tests/generator/virtual-pathless-layout-dotted-filename/routes/pathless.layout.tsx deleted file mode 100644 index 03c79de0aa..0000000000 --- a/packages/router-generator/tests/generator/virtual-pathless-layout-dotted-filename/routes/pathless.layout.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_pathless.layout')({ - component: () => 'Pathless Layout', -}) diff --git a/packages/router-generator/tests/generator/virtual-pathless-layout-dotted-filename/routes/root.route.tsx b/packages/router-generator/tests/generator/virtual-pathless-layout-dotted-filename/routes/root.route.tsx deleted file mode 100644 index 9c657c7d5b..0000000000 --- a/packages/router-generator/tests/generator/virtual-pathless-layout-dotted-filename/routes/root.route.tsx +++ /dev/null @@ -1,3 +0,0 @@ -import { createRootRoute } from '@tanstack/react-router' - -export const Route = createRootRoute() diff --git a/packages/router-generator/tests/generator/virtual-pathless-layout-dotted-filename/routes/subpath.route.tsx b/packages/router-generator/tests/generator/virtual-pathless-layout-dotted-filename/routes/subpath.route.tsx deleted file mode 100644 index 6c28fa210f..0000000000 --- a/packages/router-generator/tests/generator/virtual-pathless-layout-dotted-filename/routes/subpath.route.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_pathless.layout/subpath')({ - component: () => 'Subpath', -}) diff --git a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routeTree.snapshot.ts b/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routeTree.snapshot.ts deleted file mode 100644 index ec20742d1e..0000000000 --- a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routeTree.snapshot.ts +++ /dev/null @@ -1,480 +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 doubleRouteImport } from './routes/double' -import { Route as escapedRouteImport } from './routes/escaped' -import { Route as fooRouteImport } from './routes/foo' -import { Route as layoutRouteImport } from './routes/layout' -import { Route as doubleBarRouteImport } from './routes/double-bar' -import { Route as barRouteImport } from './routes/bar' -import { Route as escapedBarRouteImport } from './routes/escaped-bar' -import { Route as innerLayoutRouteImport } from './routes/inner-layout' -import { Route as nestedLayoutRouteImport } from './routes/nested-layout' -import { Route as rootIndexRouteImport } from './routes/root-index' -import { Route as rootIdRouteImport } from './routes/root-id' -import { Route as doubleIndexRouteImport } from './routes/double-index' -import { Route as doubleIdRouteImport } from './routes/double-id' -import { Route as escapedIndexRouteImport } from './routes/escaped-index' -import { Route as escapedIdRouteImport } from './routes/escaped-id' -import { Route as nestedIndexRouteImport } from './routes/nested-index' -import { Route as nestedIdRouteImport } from './routes/nested-id' -import { Route as bazRouteImport } from './routes/baz' -import { Route as trailIndexRouteImport } from './routes/trail-index' -import { Route as deepIndexRouteImport } from './routes/deep-index' - -const doubleRoute = doubleRouteImport.update({ - id: '/__double', - path: '/__double', - getParentRoute: () => rootRouteImport, -} as any) -const escapedRoute = escapedRouteImport.update({ - id: '/_escaped', - path: '/_escaped', - getParentRoute: () => rootRouteImport, -} as any) -const fooRoute = fooRouteImport.update({ - id: '/_foo', - path: '/_foo', - getParentRoute: () => rootRouteImport, -} as any) -const layoutRoute = layoutRouteImport.update({ - id: '/_layout', - getParentRoute: () => rootRouteImport, -} as any) -const doubleBarRoute = doubleBarRouteImport.update({ - id: '/__double-bar', - path: '/__double-bar', - getParentRoute: () => layoutRoute, -} as any) -const barRoute = barRouteImport.update({ - id: '/_bar', - path: '/_bar', - getParentRoute: () => layoutRoute, -} as any) -const escapedBarRoute = escapedBarRouteImport.update({ - id: '/_escaped-bar', - path: '/_escaped-bar', - getParentRoute: () => layoutRoute, -} as any) -const innerLayoutRoute = innerLayoutRouteImport.update({ - id: '/_inner', - getParentRoute: () => layoutRoute, -} as any) -const nestedLayoutRoute = nestedLayoutRouteImport.update({ - id: '/_nested', - getParentRoute: () => layoutRoute, -} as any) -const rootIndexRoute = rootIndexRouteImport.update({ - id: '/_root-index/', - path: '/_root-index/', - getParentRoute: () => rootRouteImport, -} as any) -const rootIdRoute = rootIdRouteImport.update({ - id: '/_root-index/$id', - path: '/_root-index/$id', - getParentRoute: () => rootRouteImport, -} as any) -const doubleIndexRoute = doubleIndexRouteImport.update({ - id: '/__double-index/', - path: '/__double-index/', - getParentRoute: () => layoutRoute, -} as any) -const doubleIdRoute = doubleIdRouteImport.update({ - id: '/__double-index/$id', - path: '/__double-index/$id', - getParentRoute: () => layoutRoute, -} as any) -const escapedIndexRoute = escapedIndexRouteImport.update({ - id: '/_escaped-index/', - path: '/_escaped-index/', - getParentRoute: () => layoutRoute, -} as any) -const escapedIdRoute = escapedIdRouteImport.update({ - id: '/_escaped-index/$id', - path: '/_escaped-index/$id', - getParentRoute: () => layoutRoute, -} as any) -const nestedIndexRoute = nestedIndexRouteImport.update({ - id: '/_nested-index/', - path: '/_nested-index/', - getParentRoute: () => layoutRoute, -} as any) -const nestedIdRoute = nestedIdRouteImport.update({ - id: '/_nested-index/$id', - path: '/_nested-index/$id', - getParentRoute: () => layoutRoute, -} as any) -const bazRoute = bazRouteImport.update({ - id: '/_baz', - path: '/_baz', - getParentRoute: () => nestedLayoutRoute, -} as any) -const trailIndexRoute = trailIndexRouteImport.update({ - id: '/trail_/', - path: '/trail_/', - getParentRoute: () => layoutRoute, -} as any) -const deepIndexRoute = deepIndexRouteImport.update({ - id: '/_deep-index/', - path: '/_deep-index/', - getParentRoute: () => innerLayoutRoute, -} as any) - -export interface FileRoutesByFullPath { - '/__double': typeof doubleRoute - '/_escaped': typeof escapedRoute - '/_foo': typeof fooRoute - '/': typeof nestedLayoutRouteWithChildren - '/_root-index/': typeof rootIndexRoute - '/__double-bar': typeof doubleBarRoute - '/_bar': typeof barRoute - '/_escaped-bar': typeof escapedBarRoute - '/_root-index/$id': typeof rootIdRoute - '/__double-index/': typeof doubleIndexRoute - '/_escaped-index/': typeof escapedIndexRoute - '/_nested-index/': typeof nestedIndexRoute - '/trail_/': typeof trailIndexRoute - '/__double-index/$id': typeof doubleIdRoute - '/_escaped-index/$id': typeof escapedIdRoute - '/_nested-index/$id': typeof nestedIdRoute - '/_baz': typeof bazRoute - '/_deep-index/': typeof deepIndexRoute -} -export interface FileRoutesByTo { - '/__double': typeof doubleRoute - '/_escaped': typeof escapedRoute - '/_foo': typeof fooRoute - '/': typeof nestedLayoutRouteWithChildren - '/_root-index': typeof rootIndexRoute - '/__double-bar': typeof doubleBarRoute - '/_bar': typeof barRoute - '/_escaped-bar': typeof escapedBarRoute - '/_root-index/$id': typeof rootIdRoute - '/__double-index': typeof doubleIndexRoute - '/_escaped-index': typeof escapedIndexRoute - '/_nested-index': typeof nestedIndexRoute - '/trail_': typeof trailIndexRoute - '/__double-index/$id': typeof doubleIdRoute - '/_escaped-index/$id': typeof escapedIdRoute - '/_nested-index/$id': typeof nestedIdRoute - '/_baz': typeof bazRoute - '/_deep-index': typeof deepIndexRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/__double': typeof doubleRoute - '/_escaped': typeof escapedRoute - '/_foo': typeof fooRoute - '/_layout': typeof layoutRouteWithChildren - '/_root-index/': typeof rootIndexRoute - '/_layout/__double-bar': typeof doubleBarRoute - '/_layout/_bar': typeof barRoute - '/_layout/_escaped-bar': typeof escapedBarRoute - '/_layout/_inner': typeof innerLayoutRouteWithChildren - '/_layout/_nested': typeof nestedLayoutRouteWithChildren - '/_root-index/$id': typeof rootIdRoute - '/_layout/__double-index/': typeof doubleIndexRoute - '/_layout/_escaped-index/': typeof escapedIndexRoute - '/_layout/_nested-index/': typeof nestedIndexRoute - '/_layout/trail_/': typeof trailIndexRoute - '/_layout/__double-index/$id': typeof doubleIdRoute - '/_layout/_escaped-index/$id': typeof escapedIdRoute - '/_layout/_nested-index/$id': typeof nestedIdRoute - '/_layout/_nested/_baz': typeof bazRoute - '/_layout/_inner/_deep-index/': typeof deepIndexRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/__double' - | '/_escaped' - | '/_foo' - | '/' - | '/_root-index/' - | '/__double-bar' - | '/_bar' - | '/_escaped-bar' - | '/_root-index/$id' - | '/__double-index/' - | '/_escaped-index/' - | '/_nested-index/' - | '/trail_/' - | '/__double-index/$id' - | '/_escaped-index/$id' - | '/_nested-index/$id' - | '/_baz' - | '/_deep-index/' - fileRoutesByTo: FileRoutesByTo - to: - | '/__double' - | '/_escaped' - | '/_foo' - | '/' - | '/_root-index' - | '/__double-bar' - | '/_bar' - | '/_escaped-bar' - | '/_root-index/$id' - | '/__double-index' - | '/_escaped-index' - | '/_nested-index' - | '/trail_' - | '/__double-index/$id' - | '/_escaped-index/$id' - | '/_nested-index/$id' - | '/_baz' - | '/_deep-index' - id: - | '__root__' - | '/__double' - | '/_escaped' - | '/_foo' - | '/_layout' - | '/_root-index/' - | '/_layout/__double-bar' - | '/_layout/_bar' - | '/_layout/_escaped-bar' - | '/_layout/_inner' - | '/_layout/_nested' - | '/_root-index/$id' - | '/_layout/__double-index/' - | '/_layout/_escaped-index/' - | '/_layout/_nested-index/' - | '/_layout/trail_/' - | '/_layout/__double-index/$id' - | '/_layout/_escaped-index/$id' - | '/_layout/_nested-index/$id' - | '/_layout/_nested/_baz' - | '/_layout/_inner/_deep-index/' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - doubleRoute: typeof doubleRoute - escapedRoute: typeof escapedRoute - fooRoute: typeof fooRoute - layoutRoute: typeof layoutRouteWithChildren - rootIndexRoute: typeof rootIndexRoute - rootIdRoute: typeof rootIdRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/__double': { - id: '/__double' - path: '/__double' - fullPath: '/__double' - preLoaderRoute: typeof doubleRouteImport - parentRoute: typeof rootRouteImport - } - '/_escaped': { - id: '/_escaped' - path: '/_escaped' - fullPath: '/_escaped' - preLoaderRoute: typeof escapedRouteImport - parentRoute: typeof rootRouteImport - } - '/_foo': { - id: '/_foo' - path: '/_foo' - fullPath: '/_foo' - preLoaderRoute: typeof fooRouteImport - parentRoute: typeof rootRouteImport - } - '/_layout': { - id: '/_layout' - path: '' - fullPath: '/' - preLoaderRoute: typeof layoutRouteImport - parentRoute: typeof rootRouteImport - } - '/_layout/__double-bar': { - id: '/_layout/__double-bar' - path: '/__double-bar' - fullPath: '/__double-bar' - preLoaderRoute: typeof doubleBarRouteImport - parentRoute: typeof layoutRoute - } - '/_layout/_bar': { - id: '/_layout/_bar' - path: '/_bar' - fullPath: '/_bar' - preLoaderRoute: typeof barRouteImport - parentRoute: typeof layoutRoute - } - '/_layout/_escaped-bar': { - id: '/_layout/_escaped-bar' - path: '/_escaped-bar' - fullPath: '/_escaped-bar' - preLoaderRoute: typeof escapedBarRouteImport - parentRoute: typeof layoutRoute - } - '/_layout/_inner': { - id: '/_layout/_inner' - path: '' - fullPath: '/' - preLoaderRoute: typeof innerLayoutRouteImport - parentRoute: typeof layoutRoute - } - '/_layout/_nested': { - id: '/_layout/_nested' - path: '' - fullPath: '/' - preLoaderRoute: typeof nestedLayoutRouteImport - parentRoute: typeof layoutRoute - } - '/_root-index/': { - id: '/_root-index/' - path: '/_root-index' - fullPath: '/_root-index/' - preLoaderRoute: typeof rootIndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_root-index/$id': { - id: '/_root-index/$id' - path: '/_root-index/$id' - fullPath: '/_root-index/$id' - preLoaderRoute: typeof rootIdRouteImport - parentRoute: typeof rootRouteImport - } - '/_layout/__double-index/': { - id: '/_layout/__double-index/' - path: '/__double-index' - fullPath: '/__double-index/' - preLoaderRoute: typeof doubleIndexRouteImport - parentRoute: typeof layoutRoute - } - '/_layout/__double-index/$id': { - id: '/_layout/__double-index/$id' - path: '/__double-index/$id' - fullPath: '/__double-index/$id' - preLoaderRoute: typeof doubleIdRouteImport - parentRoute: typeof layoutRoute - } - '/_layout/_escaped-index/': { - id: '/_layout/_escaped-index/' - path: '/_escaped-index' - fullPath: '/_escaped-index/' - preLoaderRoute: typeof escapedIndexRouteImport - parentRoute: typeof layoutRoute - } - '/_layout/_escaped-index/$id': { - id: '/_layout/_escaped-index/$id' - path: '/_escaped-index/$id' - fullPath: '/_escaped-index/$id' - preLoaderRoute: typeof escapedIdRouteImport - parentRoute: typeof layoutRoute - } - '/_layout/_nested-index/': { - id: '/_layout/_nested-index/' - path: '/_nested-index' - fullPath: '/_nested-index/' - preLoaderRoute: typeof nestedIndexRouteImport - parentRoute: typeof layoutRoute - } - '/_layout/_nested-index/$id': { - id: '/_layout/_nested-index/$id' - path: '/_nested-index/$id' - fullPath: '/_nested-index/$id' - preLoaderRoute: typeof nestedIdRouteImport - parentRoute: typeof layoutRoute - } - '/_layout/_nested/_baz': { - id: '/_layout/_nested/_baz' - path: '/_baz' - fullPath: '/_baz' - preLoaderRoute: typeof bazRouteImport - parentRoute: typeof nestedLayoutRoute - } - '/_layout/trail_/': { - id: '/_layout/trail_/' - path: '/trail_' - fullPath: '/trail_/' - preLoaderRoute: typeof trailIndexRouteImport - parentRoute: typeof layoutRoute - } - '/_layout/_inner/_deep-index/': { - id: '/_layout/_inner/_deep-index/' - path: '/_deep-index' - fullPath: '/_deep-index/' - preLoaderRoute: typeof deepIndexRouteImport - parentRoute: typeof innerLayoutRoute - } - } -} - -interface innerLayoutRouteChildren { - deepIndexRoute: typeof deepIndexRoute -} - -const innerLayoutRouteChildren: innerLayoutRouteChildren = { - deepIndexRoute: deepIndexRoute, -} - -const innerLayoutRouteWithChildren = innerLayoutRoute._addFileChildren( - innerLayoutRouteChildren, -) - -interface nestedLayoutRouteChildren { - bazRoute: typeof bazRoute -} - -const nestedLayoutRouteChildren: nestedLayoutRouteChildren = { - bazRoute: bazRoute, -} - -const nestedLayoutRouteWithChildren = nestedLayoutRoute._addFileChildren( - nestedLayoutRouteChildren, -) - -interface layoutRouteChildren { - doubleBarRoute: typeof doubleBarRoute - barRoute: typeof barRoute - escapedBarRoute: typeof escapedBarRoute - innerLayoutRoute: typeof innerLayoutRouteWithChildren - nestedLayoutRoute: typeof nestedLayoutRouteWithChildren - doubleIndexRoute: typeof doubleIndexRoute - escapedIndexRoute: typeof escapedIndexRoute - nestedIndexRoute: typeof nestedIndexRoute - trailIndexRoute: typeof trailIndexRoute - doubleIdRoute: typeof doubleIdRoute - escapedIdRoute: typeof escapedIdRoute - nestedIdRoute: typeof nestedIdRoute -} - -const layoutRouteChildren: layoutRouteChildren = { - doubleBarRoute: doubleBarRoute, - barRoute: barRoute, - escapedBarRoute: escapedBarRoute, - innerLayoutRoute: innerLayoutRouteWithChildren, - nestedLayoutRoute: nestedLayoutRouteWithChildren, - doubleIndexRoute: doubleIndexRoute, - escapedIndexRoute: escapedIndexRoute, - nestedIndexRoute: nestedIndexRoute, - trailIndexRoute: trailIndexRoute, - doubleIdRoute: doubleIdRoute, - escapedIdRoute: escapedIdRoute, - nestedIdRoute: nestedIdRoute, -} - -const layoutRouteWithChildren = - layoutRoute._addFileChildren(layoutRouteChildren) - -const rootRouteChildren: RootRouteChildren = { - doubleRoute: doubleRoute, - escapedRoute: escapedRoute, - fooRoute: fooRoute, - layoutRoute: layoutRouteWithChildren, - rootIndexRoute: rootIndexRoute, - rootIdRoute: rootIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes<FileRouteTypes>() diff --git a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes.ts b/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes.ts deleted file mode 100644 index 34ebbc111e..0000000000 --- a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { index, layout, rootRoute, route } from '@tanstack/virtual-file-routes' - -export const routes = rootRoute('__root.tsx', [ - route('/_foo', 'foo.tsx'), - route('/[_]escaped', 'escaped.tsx'), - route('/__double', 'double.tsx'), - route('/_root-index', [index('root-index.tsx'), route('$id', 'root-id.tsx')]), - layout('_layout', 'layout.tsx', [ - route('/_bar', 'bar.tsx'), - route('/[_]escaped-bar', 'escaped-bar.tsx'), - route('/__double-bar', 'double-bar.tsx'), - route('/_nested-index', [ - index('nested-index.tsx'), - route('$id', 'nested-id.tsx'), - ]), - route('/[_]escaped-index', [ - index('escaped-index.tsx'), - route('$id', 'escaped-id.tsx'), - ]), - route('/__double-index', [ - index('double-index.tsx'), - route('$id', 'double-id.tsx'), - ]), - route('/trail_', [index('trail-index.tsx')]), - layout('_nested', 'nested-layout.tsx', [route('/_baz', 'baz.tsx')]), - layout('_inner', 'inner-layout.tsx', [ - route('/_deep-index', [index('deep-index.tsx')]), - ]), - ]), -]) diff --git a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/__root.tsx b/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/__root.tsx deleted file mode 100644 index 9c657c7d5b..0000000000 --- a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/__root.tsx +++ /dev/null @@ -1,3 +0,0 @@ -import { createRootRoute } from '@tanstack/react-router' - -export const Route = createRootRoute() diff --git a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/bar.tsx b/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/bar.tsx deleted file mode 100644 index c1c8b28c28..0000000000 --- a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/bar.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_layout/_bar')({ - component: () => 'Bar', -}) diff --git a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/baz.tsx b/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/baz.tsx deleted file mode 100644 index 9bec9e82d4..0000000000 --- a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/baz.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_layout/_nested/_baz')({ - component: () => 'Baz', -}) diff --git a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/deep-index.tsx b/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/deep-index.tsx deleted file mode 100644 index 1952b00184..0000000000 --- a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/deep-index.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_layout/_inner/_deep-index/')({ - component: () => 'Deep Index', -}) diff --git a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/double-bar.tsx b/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/double-bar.tsx deleted file mode 100644 index fcda37434e..0000000000 --- a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/double-bar.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_layout/__double-bar')({ - component: () => 'Double Bar', -}) diff --git a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/double-id.tsx b/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/double-id.tsx deleted file mode 100644 index 2a31adf60c..0000000000 --- a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/double-id.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_layout/__double-index/$id')({ - component: () => 'Double Id', -}) diff --git a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/double-index.tsx b/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/double-index.tsx deleted file mode 100644 index 231e787df0..0000000000 --- a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/double-index.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_layout/__double-index/')({ - component: () => 'Double Index', -}) diff --git a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/double.tsx b/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/double.tsx deleted file mode 100644 index 041f035a8b..0000000000 --- a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/double.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/__double')({ - component: () => 'Double', -}) diff --git a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/escaped-bar.tsx b/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/escaped-bar.tsx deleted file mode 100644 index f3f5afce8d..0000000000 --- a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/escaped-bar.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_layout/_escaped-bar')({ - component: () => 'Escaped Bar', -}) diff --git a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/escaped-id.tsx b/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/escaped-id.tsx deleted file mode 100644 index a9fad62448..0000000000 --- a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/escaped-id.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_layout/_escaped-index/$id')({ - component: () => 'Escaped Id', -}) diff --git a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/escaped-index.tsx b/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/escaped-index.tsx deleted file mode 100644 index 9b81fcbadd..0000000000 --- a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/escaped-index.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_layout/_escaped-index/')({ - component: () => 'Escaped Index', -}) diff --git a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/escaped.tsx b/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/escaped.tsx deleted file mode 100644 index efe4c1fbef..0000000000 --- a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/escaped.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_escaped')({ - component: () => 'Escaped', -}) diff --git a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/foo.tsx b/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/foo.tsx deleted file mode 100644 index e081df4ce5..0000000000 --- a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/foo.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_foo')({ - component: () => 'Foo', -}) diff --git a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/inner-layout.tsx b/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/inner-layout.tsx deleted file mode 100644 index 5266c32a7c..0000000000 --- a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/inner-layout.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_layout/_inner')({ - component: () => 'Inner Layout', -}) diff --git a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/layout.tsx b/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/layout.tsx deleted file mode 100644 index 9c1673dafd..0000000000 --- a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/layout.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_layout')({ - component: () => 'Layout', -}) diff --git a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/nested-id.tsx b/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/nested-id.tsx deleted file mode 100644 index e09396020b..0000000000 --- a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/nested-id.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_layout/_nested-index/$id')({ - component: () => 'Nested Id', -}) diff --git a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/nested-index.tsx b/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/nested-index.tsx deleted file mode 100644 index a5f8f95497..0000000000 --- a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/nested-index.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_layout/_nested-index/')({ - component: () => 'Nested Index', -}) diff --git a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/nested-layout.tsx b/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/nested-layout.tsx deleted file mode 100644 index b2985c3c2e..0000000000 --- a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/nested-layout.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_layout/_nested')({ - component: () => 'Nested Layout', -}) diff --git a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/root-id.tsx b/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/root-id.tsx deleted file mode 100644 index ec329adfd3..0000000000 --- a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/root-id.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_root-index/$id')({ - component: () => 'Root Id', -}) diff --git a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/root-index.tsx b/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/root-index.tsx deleted file mode 100644 index 39387c7250..0000000000 --- a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/root-index.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_root-index/')({ - component: () => 'Root Index', -}) diff --git a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/trail-index.tsx b/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/trail-index.tsx deleted file mode 100644 index 7794e8f0b3..0000000000 --- a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/routes/trail-index.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_layout/trail_/')({ - component: () => 'Trail Index', -}) diff --git a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/tsr.config.json b/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/tsr.config.json deleted file mode 100644 index 4d587108e3..0000000000 --- a/packages/router-generator/tests/generator/virtual-pathless-layout-escaped-underscore/tsr.config.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "routesDirectory": "./routes", - "generatedRouteTree": "./routeTree.gen.ts", - "virtualRouteConfig": "./routes.ts" -} diff --git a/packages/router-generator/tests/generator/virtual-physical-empty-path-merge/routeTree.snapshot.ts b/packages/router-generator/tests/generator/virtual-physical-empty-path-merge/routeTree.snapshot.ts index eeb3c71359..6de1ed6975 100644 --- a/packages/router-generator/tests/generator/virtual-physical-empty-path-merge/routeTree.snapshot.ts +++ b/packages/router-generator/tests/generator/virtual-physical-empty-path-merge/routeTree.snapshot.ts @@ -9,13 +9,13 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/merged/index' -import { Route as aboutRouteImport } from './routes/about' import { Route as ContactRouteImport } from './routes/merged/contact' +import { Route as aboutRouteImport } from './routes/about' +import { Route as IndexRouteImport } from './routes/merged/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const ContactRoute = ContactRouteImport.update({ + id: '/contact', + path: '/contact', getParentRoute: () => rootRouteImport, } as any) const aboutRoute = aboutRouteImport.update({ @@ -23,9 +23,9 @@ const aboutRoute = aboutRouteImport.update({ path: '/about', getParentRoute: () => rootRouteImport, } as any) -const ContactRoute = ContactRouteImport.update({ - id: '/contact', - path: '/contact', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) @@ -61,11 +61,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/contact': { + id: '/contact' + path: '/contact' + fullPath: '/contact' + preLoaderRoute: typeof ContactRouteImport parentRoute: typeof rootRouteImport } '/about': { @@ -75,11 +75,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof aboutRouteImport parentRoute: typeof rootRouteImport } - '/contact': { - id: '/contact' - path: '/contact' - fullPath: '/contact' - preLoaderRoute: typeof ContactRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } } diff --git a/packages/router-generator/tests/generator/virtual-physical-inside-nested/routeTree.snapshot.ts b/packages/router-generator/tests/generator/virtual-physical-inside-nested/routeTree.snapshot.ts deleted file mode 100644 index 94d84fb790..0000000000 --- a/packages/router-generator/tests/generator/virtual-physical-inside-nested/routeTree.snapshot.ts +++ /dev/null @@ -1,134 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as indexRouteImport } from './routes/index' -import { Route as S1LayoutRouteImport } from './subtree/routes/_layout' -import { Route as S1DotDotFooRoutesRouteRouteImport } from './subtree/foo/routes/route' -import { Route as S1DotDotFooRoutesIndexRouteImport } from './subtree/foo/routes/index' - -const indexRoute = indexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const S1LayoutRoute = S1LayoutRouteImport.update({ - id: '/s1/_layout', - path: '/s1', - getParentRoute: () => rootRouteImport, -} as any) -const S1DotDotFooRoutesRouteRoute = S1DotDotFooRoutesRouteRouteImport.update({ - id: '/foo', - path: '/foo', - getParentRoute: () => S1LayoutRoute, -} as any) -const S1DotDotFooRoutesIndexRoute = S1DotDotFooRoutesIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => S1DotDotFooRoutesRouteRoute, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof indexRoute - '/s1': typeof S1LayoutRouteWithChildren - '/s1/foo': typeof S1DotDotFooRoutesRouteRouteWithChildren - '/s1/foo/': typeof S1DotDotFooRoutesIndexRoute -} -export interface FileRoutesByTo { - '/': typeof indexRoute - '/s1': typeof S1LayoutRouteWithChildren - '/s1/foo': typeof S1DotDotFooRoutesIndexRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof indexRoute - '/s1/_layout': typeof S1LayoutRouteWithChildren - '/s1/_layout/foo': typeof S1DotDotFooRoutesRouteRouteWithChildren - '/s1/_layout/foo/': typeof S1DotDotFooRoutesIndexRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/s1' | '/s1/foo' | '/s1/foo/' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/s1' | '/s1/foo' - id: '__root__' | '/' | '/s1/_layout' | '/s1/_layout/foo' | '/s1/_layout/foo/' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - indexRoute: typeof indexRoute - S1LayoutRoute: typeof S1LayoutRouteWithChildren -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof indexRouteImport - parentRoute: typeof rootRouteImport - } - '/s1/_layout': { - id: '/s1/_layout' - path: '/s1' - fullPath: '/s1' - preLoaderRoute: typeof S1LayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/s1/_layout/foo': { - id: '/s1/_layout/foo' - path: '/foo' - fullPath: '/s1/foo' - preLoaderRoute: typeof S1DotDotFooRoutesRouteRouteImport - parentRoute: typeof S1LayoutRoute - } - '/s1/_layout/foo/': { - id: '/s1/_layout/foo/' - path: '/' - fullPath: '/s1/foo/' - preLoaderRoute: typeof S1DotDotFooRoutesIndexRouteImport - parentRoute: typeof S1DotDotFooRoutesRouteRoute - } - } -} - -interface S1DotDotFooRoutesRouteRouteChildren { - S1DotDotFooRoutesIndexRoute: typeof S1DotDotFooRoutesIndexRoute -} - -const S1DotDotFooRoutesRouteRouteChildren: S1DotDotFooRoutesRouteRouteChildren = - { - S1DotDotFooRoutesIndexRoute: S1DotDotFooRoutesIndexRoute, - } - -const S1DotDotFooRoutesRouteRouteWithChildren = - S1DotDotFooRoutesRouteRoute._addFileChildren( - S1DotDotFooRoutesRouteRouteChildren, - ) - -interface S1LayoutRouteChildren { - S1DotDotFooRoutesRouteRoute: typeof S1DotDotFooRoutesRouteRouteWithChildren -} - -const S1LayoutRouteChildren: S1LayoutRouteChildren = { - S1DotDotFooRoutesRouteRoute: S1DotDotFooRoutesRouteRouteWithChildren, -} - -const S1LayoutRouteWithChildren = S1LayoutRoute._addFileChildren( - S1LayoutRouteChildren, -) - -const rootRouteChildren: RootRouteChildren = { - indexRoute: indexRoute, - S1LayoutRoute: S1LayoutRouteWithChildren, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes<FileRouteTypes>() diff --git a/packages/router-generator/tests/generator/virtual-physical-inside-nested/routes.ts b/packages/router-generator/tests/generator/virtual-physical-inside-nested/routes.ts deleted file mode 100644 index c12b588011..0000000000 --- a/packages/router-generator/tests/generator/virtual-physical-inside-nested/routes.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { index, physical, rootRoute } from '@tanstack/virtual-file-routes' - -export const routes = rootRoute('__root.tsx', [ - index('index.tsx'), - physical('/s1', '../subtree/routes'), -]) diff --git a/packages/router-generator/tests/generator/virtual-physical-inside-nested/routes/__root.tsx b/packages/router-generator/tests/generator/virtual-physical-inside-nested/routes/__root.tsx deleted file mode 100644 index f463b796b4..0000000000 --- a/packages/router-generator/tests/generator/virtual-physical-inside-nested/routes/__root.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createRootRoute, Outlet } from '@tanstack/react-router' - -export const Route = createRootRoute({ - component: () => <Outlet />, -}) diff --git a/packages/router-generator/tests/generator/virtual-physical-inside-nested/routes/index.tsx b/packages/router-generator/tests/generator/virtual-physical-inside-nested/routes/index.tsx deleted file mode 100644 index fa6ed84966..0000000000 --- a/packages/router-generator/tests/generator/virtual-physical-inside-nested/routes/index.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/')({ - component: () => <div>Home</div>, -}) diff --git a/packages/router-generator/tests/generator/virtual-physical-inside-nested/subtree/foo/routes/index.tsx b/packages/router-generator/tests/generator/virtual-physical-inside-nested/subtree/foo/routes/index.tsx deleted file mode 100644 index 0afeadc25e..0000000000 --- a/packages/router-generator/tests/generator/virtual-physical-inside-nested/subtree/foo/routes/index.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/s1/_layout/foo/')({ - component: () => <div>Nested home</div>, -}) diff --git a/packages/router-generator/tests/generator/virtual-physical-inside-nested/subtree/foo/routes/route.tsx b/packages/router-generator/tests/generator/virtual-physical-inside-nested/subtree/foo/routes/route.tsx deleted file mode 100644 index 31746ba258..0000000000 --- a/packages/router-generator/tests/generator/virtual-physical-inside-nested/subtree/foo/routes/route.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/s1/_layout/foo')({ - component: () => <Outlet />, -}) diff --git a/packages/router-generator/tests/generator/virtual-physical-inside-nested/subtree/routes/__virtual.ts b/packages/router-generator/tests/generator/virtual-physical-inside-nested/subtree/routes/__virtual.ts deleted file mode 100644 index 28ca02884c..0000000000 --- a/packages/router-generator/tests/generator/virtual-physical-inside-nested/subtree/routes/__virtual.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { - defineVirtualSubtreeConfig, - layout, - physical, -} from '@tanstack/virtual-file-routes' - -export default defineVirtualSubtreeConfig([ - layout('./_layout.tsx', [physical('/foo', '../foo/routes')]), -]) diff --git a/packages/router-generator/tests/generator/virtual-physical-inside-nested/subtree/routes/_layout.tsx b/packages/router-generator/tests/generator/virtual-physical-inside-nested/subtree/routes/_layout.tsx deleted file mode 100644 index 4740cb1263..0000000000 --- a/packages/router-generator/tests/generator/virtual-physical-inside-nested/subtree/routes/_layout.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/s1/_layout')({ - component: () => <Outlet />, -}) diff --git a/packages/router-generator/tests/generator/virtual-physical-inside-nested/tsr.config.json b/packages/router-generator/tests/generator/virtual-physical-inside-nested/tsr.config.json deleted file mode 100644 index 4d587108e3..0000000000 --- a/packages/router-generator/tests/generator/virtual-physical-inside-nested/tsr.config.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "routesDirectory": "./routes", - "generatedRouteTree": "./routeTree.gen.ts", - "virtualRouteConfig": "./routes.ts" -} diff --git a/packages/router-generator/tests/generator/virtual-physical-layout-and-index/routeTree.snapshot.ts b/packages/router-generator/tests/generator/virtual-physical-layout-and-index/routeTree.snapshot.ts index e8cddcbc9c..bade75773c 100644 --- a/packages/router-generator/tests/generator/virtual-physical-layout-and-index/routeTree.snapshot.ts +++ b/packages/router-generator/tests/generator/virtual-physical-layout-and-index/routeTree.snapshot.ts @@ -9,20 +9,20 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as indexRouteImport } from './routes/index' import { Route as FeatureRouteRouteImport } from './routes/feature/route' +import { Route as indexRouteImport } from './routes/index' import { Route as FeatureIndexRouteImport } from './routes/feature/index' -const indexRoute = indexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const FeatureRouteRoute = FeatureRouteRouteImport.update({ id: '/feature', path: '/feature', getParentRoute: () => rootRouteImport, } as any) +const indexRoute = indexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const FeatureIndexRoute = FeatureIndexRouteImport.update({ id: '/', path: '/', @@ -59,13 +59,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof indexRouteImport - parentRoute: typeof rootRouteImport - } '/feature': { id: '/feature' path: '/feature' @@ -73,6 +66,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof FeatureRouteRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof indexRouteImport + parentRoute: typeof rootRouteImport + } '/feature/': { id: '/feature/' path: '/' diff --git a/packages/router-generator/tests/generator/virtual-physical-no-prefix/routeTree.snapshot.ts b/packages/router-generator/tests/generator/virtual-physical-no-prefix/routeTree.snapshot.ts index eeb3c71359..6de1ed6975 100644 --- a/packages/router-generator/tests/generator/virtual-physical-no-prefix/routeTree.snapshot.ts +++ b/packages/router-generator/tests/generator/virtual-physical-no-prefix/routeTree.snapshot.ts @@ -9,13 +9,13 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/merged/index' -import { Route as aboutRouteImport } from './routes/about' import { Route as ContactRouteImport } from './routes/merged/contact' +import { Route as aboutRouteImport } from './routes/about' +import { Route as IndexRouteImport } from './routes/merged/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const ContactRoute = ContactRouteImport.update({ + id: '/contact', + path: '/contact', getParentRoute: () => rootRouteImport, } as any) const aboutRoute = aboutRouteImport.update({ @@ -23,9 +23,9 @@ const aboutRoute = aboutRouteImport.update({ path: '/about', getParentRoute: () => rootRouteImport, } as any) -const ContactRoute = ContactRouteImport.update({ - id: '/contact', - path: '/contact', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) @@ -61,11 +61,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/contact': { + id: '/contact' + path: '/contact' + fullPath: '/contact' + preLoaderRoute: typeof ContactRouteImport parentRoute: typeof rootRouteImport } '/about': { @@ -75,11 +75,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof aboutRouteImport parentRoute: typeof rootRouteImport } - '/contact': { - id: '/contact' - path: '/contact' - fullPath: '/contact' - preLoaderRoute: typeof ContactRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } } diff --git a/packages/router-generator/tests/generator/virtual-physical-pathless-layout-literal-index/routeTree.snapshot.ts b/packages/router-generator/tests/generator/virtual-physical-pathless-layout-literal-index/routeTree.snapshot.ts deleted file mode 100644 index b0fd76d1ef..0000000000 --- a/packages/router-generator/tests/generator/virtual-physical-pathless-layout-literal-index/routeTree.snapshot.ts +++ /dev/null @@ -1,104 +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 layoutRouteImport } from './routes/layout' -import { Route as Char91_Char93nestedIndexRouteImport } from './routes/physical-routes/[_]nested/index' -import { Route as Char91_Char93nestedIdRouteImport } from './routes/physical-routes/[_]nested/$id' - -const layoutRoute = layoutRouteImport.update({ - id: '/_layout', - getParentRoute: () => rootRouteImport, -} as any) -const Char91_Char93nestedIndexRoute = - Char91_Char93nestedIndexRouteImport.update({ - id: '/_nested/', - path: '/_nested/', - getParentRoute: () => layoutRoute, - } as any) -const Char91_Char93nestedIdRoute = Char91_Char93nestedIdRouteImport.update({ - id: '/_nested/$id', - path: '/_nested/$id', - getParentRoute: () => layoutRoute, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof layoutRouteWithChildren - '/_nested/$id': typeof Char91_Char93nestedIdRoute - '/_nested/': typeof Char91_Char93nestedIndexRoute -} -export interface FileRoutesByTo { - '/': typeof layoutRouteWithChildren - '/_nested/$id': typeof Char91_Char93nestedIdRoute - '/_nested': typeof Char91_Char93nestedIndexRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/_layout': typeof layoutRouteWithChildren - '/_layout/_nested/$id': typeof Char91_Char93nestedIdRoute - '/_layout/_nested/': typeof Char91_Char93nestedIndexRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/_nested/$id' | '/_nested/' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/_nested/$id' | '/_nested' - id: '__root__' | '/_layout' | '/_layout/_nested/$id' | '/_layout/_nested/' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - layoutRoute: typeof layoutRouteWithChildren -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/_layout': { - id: '/_layout' - path: '' - fullPath: '/' - preLoaderRoute: typeof layoutRouteImport - parentRoute: typeof rootRouteImport - } - '/_layout/_nested/': { - id: '/_layout/_nested/' - path: '/_nested' - fullPath: '/_nested/' - preLoaderRoute: typeof Char91_Char93nestedIndexRouteImport - parentRoute: typeof layoutRoute - } - '/_layout/_nested/$id': { - id: '/_layout/_nested/$id' - path: '/_nested/$id' - fullPath: '/_nested/$id' - preLoaderRoute: typeof Char91_Char93nestedIdRouteImport - parentRoute: typeof layoutRoute - } - } -} - -interface layoutRouteChildren { - Char91_Char93nestedIdRoute: typeof Char91_Char93nestedIdRoute - Char91_Char93nestedIndexRoute: typeof Char91_Char93nestedIndexRoute -} - -const layoutRouteChildren: layoutRouteChildren = { - Char91_Char93nestedIdRoute: Char91_Char93nestedIdRoute, - Char91_Char93nestedIndexRoute: Char91_Char93nestedIndexRoute, -} - -const layoutRouteWithChildren = - layoutRoute._addFileChildren(layoutRouteChildren) - -const rootRouteChildren: RootRouteChildren = { - layoutRoute: layoutRouteWithChildren, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes<FileRouteTypes>() diff --git a/packages/router-generator/tests/generator/virtual-physical-pathless-layout-literal-index/routes.ts b/packages/router-generator/tests/generator/virtual-physical-pathless-layout-literal-index/routes.ts deleted file mode 100644 index 8cd9a3a353..0000000000 --- a/packages/router-generator/tests/generator/virtual-physical-pathless-layout-literal-index/routes.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { layout, physical, rootRoute } from '@tanstack/virtual-file-routes' - -export const routes = rootRoute('__root.tsx', [ - layout('_layout', 'layout.tsx', [physical('', 'physical-routes')]), -]) diff --git a/packages/router-generator/tests/generator/virtual-physical-pathless-layout-literal-index/routes/__root.tsx b/packages/router-generator/tests/generator/virtual-physical-pathless-layout-literal-index/routes/__root.tsx deleted file mode 100644 index 9c657c7d5b..0000000000 --- a/packages/router-generator/tests/generator/virtual-physical-pathless-layout-literal-index/routes/__root.tsx +++ /dev/null @@ -1,3 +0,0 @@ -import { createRootRoute } from '@tanstack/react-router' - -export const Route = createRootRoute() diff --git a/packages/router-generator/tests/generator/virtual-physical-pathless-layout-literal-index/routes/layout.tsx b/packages/router-generator/tests/generator/virtual-physical-pathless-layout-literal-index/routes/layout.tsx deleted file mode 100644 index 9c1673dafd..0000000000 --- a/packages/router-generator/tests/generator/virtual-physical-pathless-layout-literal-index/routes/layout.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_layout')({ - component: () => 'Layout', -}) diff --git a/packages/router-generator/tests/generator/virtual-physical-pathless-layout-literal-index/routes/physical-routes/[_]nested/$id.tsx b/packages/router-generator/tests/generator/virtual-physical-pathless-layout-literal-index/routes/physical-routes/[_]nested/$id.tsx deleted file mode 100644 index 4b06b8799e..0000000000 --- a/packages/router-generator/tests/generator/virtual-physical-pathless-layout-literal-index/routes/physical-routes/[_]nested/$id.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_layout/_nested/$id')({ - component: () => 'Nested Id', -}) diff --git a/packages/router-generator/tests/generator/virtual-physical-pathless-layout-literal-index/routes/physical-routes/[_]nested/index.tsx b/packages/router-generator/tests/generator/virtual-physical-pathless-layout-literal-index/routes/physical-routes/[_]nested/index.tsx deleted file mode 100644 index b8eca0e427..0000000000 --- a/packages/router-generator/tests/generator/virtual-physical-pathless-layout-literal-index/routes/physical-routes/[_]nested/index.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_layout/_nested/')({ - component: () => 'Nested Index', -}) diff --git a/packages/router-generator/tests/generator/virtual-physical-pathless-layout-literal-index/tsr.config.json b/packages/router-generator/tests/generator/virtual-physical-pathless-layout-literal-index/tsr.config.json deleted file mode 100644 index 4d587108e3..0000000000 --- a/packages/router-generator/tests/generator/virtual-physical-pathless-layout-literal-index/tsr.config.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "routesDirectory": "./routes", - "generatedRouteTree": "./routeTree.gen.ts", - "virtualRouteConfig": "./routes.ts" -} diff --git a/packages/router-generator/tests/generator/virtual-physical-prefix-escaped-underscore/routeTree.snapshot.ts b/packages/router-generator/tests/generator/virtual-physical-prefix-escaped-underscore/routeTree.snapshot.ts deleted file mode 100644 index 63b1df0f40..0000000000 --- a/packages/router-generator/tests/generator/virtual-physical-prefix-escaped-underscore/routeTree.snapshot.ts +++ /dev/null @@ -1,77 +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 ApiIndexRouteImport } from './routes/physical-routes/index' -import { Route as ApiIdRouteImport } from './routes/physical-routes/$id' - -const ApiIndexRoute = ApiIndexRouteImport.update({ - id: '/_api/', - path: '/_api/', - getParentRoute: () => rootRouteImport, -} as any) -const ApiIdRoute = ApiIdRouteImport.update({ - id: '/_api/$id', - path: '/_api/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/_api/$id': typeof ApiIdRoute - '/_api/': typeof ApiIndexRoute -} -export interface FileRoutesByTo { - '/_api/$id': typeof ApiIdRoute - '/_api': typeof ApiIndexRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/_api/$id': typeof ApiIdRoute - '/_api/': typeof ApiIndexRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/_api/$id' | '/_api/' - fileRoutesByTo: FileRoutesByTo - to: '/_api/$id' | '/_api' - id: '__root__' | '/_api/$id' | '/_api/' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - ApiIdRoute: typeof ApiIdRoute - ApiIndexRoute: typeof ApiIndexRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/_api/': { - id: '/_api/' - path: '/_api' - fullPath: '/_api/' - preLoaderRoute: typeof ApiIndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_api/$id': { - id: '/_api/$id' - path: '/_api/$id' - fullPath: '/_api/$id' - preLoaderRoute: typeof ApiIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - ApiIdRoute: ApiIdRoute, - ApiIndexRoute: ApiIndexRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes<FileRouteTypes>() diff --git a/packages/router-generator/tests/generator/virtual-physical-prefix-escaped-underscore/routes.ts b/packages/router-generator/tests/generator/virtual-physical-prefix-escaped-underscore/routes.ts deleted file mode 100644 index 8e3883cec6..0000000000 --- a/packages/router-generator/tests/generator/virtual-physical-prefix-escaped-underscore/routes.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { physical, rootRoute } from '@tanstack/virtual-file-routes' - -export const routes = rootRoute('__root.tsx', [ - physical('/[_]api', 'physical-routes'), -]) diff --git a/packages/router-generator/tests/generator/virtual-physical-prefix-escaped-underscore/routes/__root.tsx b/packages/router-generator/tests/generator/virtual-physical-prefix-escaped-underscore/routes/__root.tsx deleted file mode 100644 index 9c657c7d5b..0000000000 --- a/packages/router-generator/tests/generator/virtual-physical-prefix-escaped-underscore/routes/__root.tsx +++ /dev/null @@ -1,3 +0,0 @@ -import { createRootRoute } from '@tanstack/react-router' - -export const Route = createRootRoute() diff --git a/packages/router-generator/tests/generator/virtual-physical-prefix-escaped-underscore/routes/physical-routes/$id.tsx b/packages/router-generator/tests/generator/virtual-physical-prefix-escaped-underscore/routes/physical-routes/$id.tsx deleted file mode 100644 index e45ad32d5d..0000000000 --- a/packages/router-generator/tests/generator/virtual-physical-prefix-escaped-underscore/routes/physical-routes/$id.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_api/$id')({ - component: () => 'API Id', -}) diff --git a/packages/router-generator/tests/generator/virtual-physical-prefix-escaped-underscore/routes/physical-routes/index.tsx b/packages/router-generator/tests/generator/virtual-physical-prefix-escaped-underscore/routes/physical-routes/index.tsx deleted file mode 100644 index ac44aee10d..0000000000 --- a/packages/router-generator/tests/generator/virtual-physical-prefix-escaped-underscore/routes/physical-routes/index.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_api/')({ - component: () => 'API Index', -}) diff --git a/packages/router-generator/tests/generator/virtual-physical-prefix-escaped-underscore/tsr.config.json b/packages/router-generator/tests/generator/virtual-physical-prefix-escaped-underscore/tsr.config.json deleted file mode 100644 index 4d587108e3..0000000000 --- a/packages/router-generator/tests/generator/virtual-physical-prefix-escaped-underscore/tsr.config.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "routesDirectory": "./routes", - "generatedRouteTree": "./routeTree.gen.ts", - "virtualRouteConfig": "./routes.ts" -} diff --git a/packages/router-generator/tests/generator/virtual-subtree-in-escaped-physical-directory/routeTree.snapshot.ts b/packages/router-generator/tests/generator/virtual-subtree-in-escaped-physical-directory/routeTree.snapshot.ts deleted file mode 100644 index bb8b39ad4a..0000000000 --- a/packages/router-generator/tests/generator/virtual-subtree-in-escaped-physical-directory/routeTree.snapshot.ts +++ /dev/null @@ -1,77 +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 AreaIndexRouteImport } from './routes/[_]area/index' -import { Route as AreaChildRouteImport } from './routes/[_]area/child' - -const AreaIndexRoute = AreaIndexRouteImport.update({ - id: '/_area/', - path: '/_area/', - getParentRoute: () => rootRouteImport, -} as any) -const AreaChildRoute = AreaChildRouteImport.update({ - id: '/_area/child', - path: '/_area/child', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/_area/child': typeof AreaChildRoute - '/_area/': typeof AreaIndexRoute -} -export interface FileRoutesByTo { - '/_area/child': typeof AreaChildRoute - '/_area': typeof AreaIndexRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/_area/child': typeof AreaChildRoute - '/_area/': typeof AreaIndexRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/_area/child' | '/_area/' - fileRoutesByTo: FileRoutesByTo - to: '/_area/child' | '/_area' - id: '__root__' | '/_area/child' | '/_area/' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - AreaChildRoute: typeof AreaChildRoute - AreaIndexRoute: typeof AreaIndexRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/_area/': { - id: '/_area/' - path: '/_area' - fullPath: '/_area/' - preLoaderRoute: typeof AreaIndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_area/child': { - id: '/_area/child' - path: '/_area/child' - fullPath: '/_area/child' - preLoaderRoute: typeof AreaChildRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - AreaChildRoute: AreaChildRoute, - AreaIndexRoute: AreaIndexRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes<FileRouteTypes>() diff --git a/packages/router-generator/tests/generator/virtual-subtree-in-escaped-physical-directory/routes/[_]area/__virtual.ts b/packages/router-generator/tests/generator/virtual-subtree-in-escaped-physical-directory/routes/[_]area/__virtual.ts deleted file mode 100644 index fd1baf16be..0000000000 --- a/packages/router-generator/tests/generator/virtual-subtree-in-escaped-physical-directory/routes/[_]area/__virtual.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { - defineVirtualSubtreeConfig, - index, - route, -} from '@tanstack/virtual-file-routes' - -export default defineVirtualSubtreeConfig([ - index('index.tsx'), - route('/child', 'child.tsx'), -]) diff --git a/packages/router-generator/tests/generator/virtual-subtree-in-escaped-physical-directory/routes/[_]area/child.tsx b/packages/router-generator/tests/generator/virtual-subtree-in-escaped-physical-directory/routes/[_]area/child.tsx deleted file mode 100644 index f3af7057cb..0000000000 --- a/packages/router-generator/tests/generator/virtual-subtree-in-escaped-physical-directory/routes/[_]area/child.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_area/child')({ - component: () => 'Area Child', -}) diff --git a/packages/router-generator/tests/generator/virtual-subtree-in-escaped-physical-directory/routes/[_]area/index.tsx b/packages/router-generator/tests/generator/virtual-subtree-in-escaped-physical-directory/routes/[_]area/index.tsx deleted file mode 100644 index 90b81675e6..0000000000 --- a/packages/router-generator/tests/generator/virtual-subtree-in-escaped-physical-directory/routes/[_]area/index.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_area/')({ - component: () => 'Area Index', -}) diff --git a/packages/router-generator/tests/generator/virtual-subtree-in-escaped-physical-directory/routes/__root.tsx b/packages/router-generator/tests/generator/virtual-subtree-in-escaped-physical-directory/routes/__root.tsx deleted file mode 100644 index 9c657c7d5b..0000000000 --- a/packages/router-generator/tests/generator/virtual-subtree-in-escaped-physical-directory/routes/__root.tsx +++ /dev/null @@ -1,3 +0,0 @@ -import { createRootRoute } from '@tanstack/react-router' - -export const Route = createRootRoute() diff --git a/packages/router-generator/tests/generator/virtual-with-escaped-underscore/routeTree.snapshot.ts b/packages/router-generator/tests/generator/virtual-with-escaped-underscore/routeTree.snapshot.ts index 18d7439610..8eed55a7fe 100644 --- a/packages/router-generator/tests/generator/virtual-with-escaped-underscore/routeTree.snapshot.ts +++ b/packages/router-generator/tests/generator/virtual-with-escaped-underscore/routeTree.snapshot.ts @@ -11,8 +11,8 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as indexRouteImport } from './routes/index' import { Route as ApiIndexRouteImport } from './routes/physical-routes/index' -import { Route as ApiChar91_Char93authDotrouteRouteImport } from './routes/physical-routes/[_]auth.route' import { Route as ApiChar91_Char93helloRouteImport } from './routes/physical-routes/[_]hello' +import { Route as ApiChar91_Char93authDotrouteRouteImport } from './routes/physical-routes/[_]auth.route' const indexRoute = indexRouteImport.update({ id: '/', @@ -24,17 +24,17 @@ const ApiIndexRoute = ApiIndexRouteImport.update({ path: '/api/', getParentRoute: () => rootRouteImport, } as any) +const ApiChar91_Char93helloRoute = ApiChar91_Char93helloRouteImport.update({ + id: '/api/_hello', + path: '/api/_hello', + getParentRoute: () => rootRouteImport, +} as any) const ApiChar91_Char93authDotrouteRoute = ApiChar91_Char93authDotrouteRouteImport.update({ id: '/api/_auth', path: '/api/_auth', getParentRoute: () => rootRouteImport, } as any) -const ApiChar91_Char93helloRoute = ApiChar91_Char93helloRouteImport.update({ - id: '/api/_hello', - path: '/api/_hello', - getParentRoute: () => rootRouteImport, -} as any) export interface FileRoutesByFullPath { '/': typeof indexRoute @@ -86,13 +86,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ApiIndexRouteImport parentRoute: typeof rootRouteImport } - '/api/_auth': { - id: '/api/_auth' - path: '/api/_auth' - fullPath: '/api/_auth' - preLoaderRoute: typeof ApiChar91_Char93authDotrouteRouteImport - parentRoute: typeof rootRouteImport - } '/api/_hello': { id: '/api/_hello' path: '/api/_hello' @@ -100,6 +93,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ApiChar91_Char93helloRouteImport parentRoute: typeof rootRouteImport } + '/api/_auth': { + id: '/api/_auth' + path: '/api/_auth' + fullPath: '/api/_auth' + preLoaderRoute: typeof ApiChar91_Char93authDotrouteRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/packages/router-generator/tests/generator/virtual/routeTree.snapshot.ts b/packages/router-generator/tests/generator/virtual/routeTree.snapshot.ts index 6b16924d5b..3d3c2de9d5 100644 --- a/packages/router-generator/tests/generator/virtual/routeTree.snapshot.ts +++ b/packages/router-generator/tests/generator/virtual/routeTree.snapshot.ts @@ -9,30 +9,25 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/root' -import { Route as indexRouteImport } from './routes/index' import { Route as layoutRouteImport } from './routes/layout' -import { Route as pagesRouteImport } from './routes/pages' +import { Route as indexRouteImport } from './routes/index' import { Route as dbDashboardRouteImport } from './routes/db/dashboard' -import { Route as dbDashboardIndexRouteImport } from './routes/db/dashboard-index' -import { Route as dbDashboardInvoicesRouteImport } from './routes/db/dashboard-invoices' +import { Route as pagesRouteImport } from './routes/pages' import { Route as HelloIndexRouteImport } from './routes/subtree/index' -import { Route as dbInvoicesIndexRouteImport } from './routes/db/invoices-index' -import { Route as dbInvoiceDetailRouteImport } from './routes/db/invoice-detail' +import { Route as dbDashboardInvoicesRouteImport } from './routes/db/dashboard-invoices' +import { Route as dbDashboardIndexRouteImport } from './routes/db/dashboard-index' import { Route as HelloFooIndexRouteImport } from './routes/subtree/foo/index' import { Route as HelloFooIdRouteImport } from './routes/subtree/foo/$id' +import { Route as dbInvoiceDetailRouteImport } from './routes/db/invoice-detail' +import { Route as dbInvoicesIndexRouteImport } from './routes/db/invoices-index' -const indexRoute = indexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const layoutRoute = layoutRouteImport.update({ id: '/_layout', getParentRoute: () => rootRouteImport, } as any) -const pagesRoute = pagesRouteImport.update({ - id: '/$lang/', - path: '/$lang/', +const indexRoute = indexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const dbDashboardRoute = dbDashboardRouteImport.update({ @@ -40,30 +35,25 @@ const dbDashboardRoute = dbDashboardRouteImport.update({ path: '/dashboard', getParentRoute: () => layoutRoute, } as any) -const dbDashboardIndexRoute = dbDashboardIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => dbDashboardRoute, -} as any) -const dbDashboardInvoicesRoute = dbDashboardInvoicesRouteImport.update({ - id: '/invoices', - path: '/invoices', - getParentRoute: () => dbDashboardRoute, +const pagesRoute = pagesRouteImport.update({ + id: '/$lang/', + path: '/$lang/', + getParentRoute: () => rootRouteImport, } as any) const HelloIndexRoute = HelloIndexRouteImport.update({ id: '/hello/', path: '/hello/', getParentRoute: () => layoutRoute, } as any) -const dbInvoicesIndexRoute = dbInvoicesIndexRouteImport.update({ +const dbDashboardInvoicesRoute = dbDashboardInvoicesRouteImport.update({ + id: '/invoices', + path: '/invoices', + getParentRoute: () => dbDashboardRoute, +} as any) +const dbDashboardIndexRoute = dbDashboardIndexRouteImport.update({ id: '/', path: '/', - getParentRoute: () => dbDashboardInvoicesRoute, -} as any) -const dbInvoiceDetailRoute = dbInvoiceDetailRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => dbDashboardInvoicesRoute, + getParentRoute: () => dbDashboardRoute, } as any) const HelloFooIndexRoute = HelloFooIndexRouteImport.update({ id: '/hello/foo/', @@ -75,6 +65,16 @@ const HelloFooIdRoute = HelloFooIdRouteImport.update({ path: '/hello/foo/$id', getParentRoute: () => layoutRoute, } as any) +const dbInvoiceDetailRoute = dbInvoiceDetailRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => dbDashboardInvoicesRoute, +} as any) +const dbInvoicesIndexRoute = dbInvoicesIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => dbDashboardInvoicesRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof indexRoute @@ -158,13 +158,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof indexRouteImport - parentRoute: typeof rootRouteImport - } '/_layout': { id: '/_layout' path: '' @@ -172,11 +165,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof layoutRouteImport parentRoute: typeof rootRouteImport } - '/$lang/': { - id: '/$lang/' - path: '/$lang' - fullPath: '/$lang/' - preLoaderRoute: typeof pagesRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof indexRouteImport parentRoute: typeof rootRouteImport } '/_layout/dashboard': { @@ -186,19 +179,12 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof dbDashboardRouteImport parentRoute: typeof layoutRoute } - '/_layout/dashboard/': { - id: '/_layout/dashboard/' - path: '/' - fullPath: '/dashboard/' - preLoaderRoute: typeof dbDashboardIndexRouteImport - parentRoute: typeof dbDashboardRoute - } - '/_layout/dashboard/invoices': { - id: '/_layout/dashboard/invoices' - path: '/invoices' - fullPath: '/dashboard/invoices' - preLoaderRoute: typeof dbDashboardInvoicesRouteImport - parentRoute: typeof dbDashboardRoute + '/$lang/': { + id: '/$lang/' + path: '/$lang' + fullPath: '/$lang/' + preLoaderRoute: typeof pagesRouteImport + parentRoute: typeof rootRouteImport } '/_layout/hello/': { id: '/_layout/hello/' @@ -207,19 +193,19 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof HelloIndexRouteImport parentRoute: typeof layoutRoute } - '/_layout/dashboard/invoices/': { - id: '/_layout/dashboard/invoices/' - path: '/' - fullPath: '/dashboard/invoices/' - preLoaderRoute: typeof dbInvoicesIndexRouteImport - parentRoute: typeof dbDashboardInvoicesRoute + '/_layout/dashboard/invoices': { + id: '/_layout/dashboard/invoices' + path: '/invoices' + fullPath: '/dashboard/invoices' + preLoaderRoute: typeof dbDashboardInvoicesRouteImport + parentRoute: typeof dbDashboardRoute } - '/_layout/dashboard/invoices/$id': { - id: '/_layout/dashboard/invoices/$id' - path: '/$id' - fullPath: '/dashboard/invoices/$id' - preLoaderRoute: typeof dbInvoiceDetailRouteImport - parentRoute: typeof dbDashboardInvoicesRoute + '/_layout/dashboard/': { + id: '/_layout/dashboard/' + path: '/' + fullPath: '/dashboard/' + preLoaderRoute: typeof dbDashboardIndexRouteImport + parentRoute: typeof dbDashboardRoute } '/_layout/hello/foo/': { id: '/_layout/hello/foo/' @@ -235,6 +221,20 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof HelloFooIdRouteImport parentRoute: typeof layoutRoute } + '/_layout/dashboard/invoices/$id': { + id: '/_layout/dashboard/invoices/$id' + path: '/$id' + fullPath: '/dashboard/invoices/$id' + preLoaderRoute: typeof dbInvoiceDetailRouteImport + parentRoute: typeof dbDashboardInvoicesRoute + } + '/_layout/dashboard/invoices/': { + id: '/_layout/dashboard/invoices/' + path: '/' + fullPath: '/dashboard/invoices/' + preLoaderRoute: typeof dbInvoicesIndexRouteImport + parentRoute: typeof dbDashboardInvoicesRoute + } } } diff --git a/packages/router-generator/tests/template.test.ts b/packages/router-generator/tests/template.test.ts deleted file mode 100644 index 745604b4ec..0000000000 --- a/packages/router-generator/tests/template.test.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { getTargetTemplate } from '../src/template' - -describe('template', () => { - it('escapes quoted route paths in React route templates', () => { - const template = getTargetTemplate({ target: 'react' } as never) - - expect(template.route.imports.tsrExportStart(`/say-"hi"`)).toBe( - `export const Route = createFileRoute(${JSON.stringify('/say-"hi"')})(`, - ) - expect(template.lazyRoute.imports.tsrExportStart(`/say-"hi"`)).toBe( - `export const Route = createLazyFileRoute(${JSON.stringify('/say-"hi"')})(`, - ) - }) - - it('escapes quoted route paths in Solid route templates', () => { - const template = getTargetTemplate({ target: 'solid' } as never) - - expect(template.route.imports.tsrExportStart(`/say-"hi"`)).toBe( - `export const Route = createFileRoute(${JSON.stringify('/say-"hi"')})(`, - ) - expect(template.lazyRoute.imports.tsrExportStart(`/say-"hi"`)).toBe( - `export const Route = createLazyFileRoute(${JSON.stringify('/say-"hi"')})(`, - ) - }) - - it('escapes quoted route paths in Vue route templates', () => { - const template = getTargetTemplate({ target: 'vue' } as never) - - expect(template.route.imports.tsrExportStart(`/say-"hi"`)).toBe( - `export const Route = createFileRoute(${JSON.stringify('/say-"hi"')})(`, - ) - expect(template.lazyRoute.imports.tsrExportStart(`/say-"hi"`)).toBe( - `export const Route = createLazyFileRoute(${JSON.stringify('/say-"hi"')})(`, - ) - }) -}) diff --git a/packages/router-generator/tests/transform.test.ts b/packages/router-generator/tests/transform.test.ts deleted file mode 100644 index 2267599c15..0000000000 --- a/packages/router-generator/tests/transform.test.ts +++ /dev/null @@ -1,657 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { transform } from '../src/transform/transform' -import type { RouteNode } from '../src/types' - -function makeNode( - fsRouteType: RouteNode['_fsRouteType'] = 'static', -): RouteNode { - return { - filePath: '/test.tsx', - fullPath: '/test.tsx', - variableName: 'TestRoute', - _fsRouteType: fsRouteType, - } -} - -function transformToNewRoute(source: string, node = makeNode()) { - return transform({ - source, - ctx: { target: 'react', routeId: '/new', lazy: false }, - node, - }) -} - -describe('transform', () => { - it('reads and rewrites the route constructor, id and options through parentheses', () => { - const node = makeNode() - const result = transformToNewRoute( - [ - "import { createLazyFileRoute } from '@tanstack/react-router'", - "export const Route = (createLazyFileRoute)(('/old'))(({ component: Page, server: {} }))", - ].join('\n'), - node, - ) - - expect(result).toEqual({ - result: 'modified', - output: [ - "import { createFileRoute } from '@tanstack/react-router'", - "export const Route = (createFileRoute)(('/new'))(({ component: Page, server: {} }))", - ].join('\n'), - }) - expect(node.createFileRouteProps).toEqual(new Set(['component', 'server'])) - }) - - it('updates parenthesized route calls without changing their surrounding source', () => { - const result = transform({ - source: - "import { createFileRoute } from '@tanstack/react-router'; export const Route = ((createFileRoute('/old'))({}));", - ctx: { target: 'react', routeId: '/new', lazy: false }, - node: makeNode(), - }) - expect(result.result).toBe('modified') - if (result.result === 'modified') { - expect(result.output).toContain("((createFileRoute('/new'))({}))") - } - }) - - it('does not treat root route exports as missing Route exports', async () => { - const result = await transform({ - source: [ - "import { createRootRoute } from '@tanstack/react-router'", - '', - 'export const Route = createRootRoute()({})', - ].join('\n'), - ctx: { - target: 'react', - routeId: '/', - lazy: false, - }, - node: makeNode('__root'), - }) - - expect(result.result).toBe('not-modified') - }) - - it('does not treat createRootRouteWithContext exports as missing Route exports', async () => { - const result = await transform({ - source: [ - "import { createRootRouteWithContext } from '@tanstack/react-router'", - '', - 'interface RouterContext {}', - '', - 'export const Route = createRootRouteWithContext<RouterContext>()({})', - ].join('\n'), - ctx: { - target: 'react', - routeId: '/', - lazy: false, - }, - node: makeNode('__root'), - }) - - expect(result.result).toBe('not-modified') - }) - - it('does not treat createRootRoute exported via export { Route } as missing Route exports', async () => { - const result = await transform({ - source: [ - "import { createRootRoute } from '@tanstack/react-router'", - '', - 'const Route = createRootRoute()({})', - '', - 'export { Route }', - ].join('\n'), - ctx: { - target: 'react', - routeId: '/', - lazy: false, - }, - node: makeNode('__root'), - }) - - expect(result.result).toBe('not-modified') - }) - - it('returns an error result for parse failures', async () => { - const result = await transform({ - source: "export const Route = createFileRoute('/broken')(", - ctx: { - target: 'react', - routeId: '/broken', - lazy: false, - }, - node: makeNode(), - }) - - expect(result.result).toBe('error') - }) - - it('rewrites an aliased exported Route binding', async () => { - const node = makeNode() - const result = await transform({ - source: [ - "import { createFileRoute } from '@tanstack/react-router'", - '', - "const MyRoute = createFileRoute('/old')({ component: Component })", - '', - 'export { MyRoute as Route }', - '', - 'function Component() {', - ' return null', - '}', - ].join('\n'), - ctx: { - target: 'react', - routeId: '/new', - lazy: false, - }, - node, - }) - - expect(result.result).toBe('modified') - if (result.result !== 'modified') { - throw new Error(`expected modified result, got ${result.result}`) - } - expect(result.output).toContain("createFileRoute('/new')") - expect(node.createFileRouteProps).toEqual(new Set(['component'])) - }) - - it('removes imports cleanly with CRLF line endings', async () => { - const result = await transform({ - source: [ - "import { createFileRoute } from '@tanstack/react-router'", - "import { createLazyFileRoute } from '@tanstack/react-router'", - '', - "export const Route = createFileRoute('/old')({})", - ].join('\r\n'), - ctx: { - target: 'react', - routeId: '/new', - lazy: false, - }, - node: makeNode(), - }) - - expect(result.result).toBe('modified') - if (result.result !== 'modified') { - throw new Error(`expected modified result, got ${result.result}`) - } - expect(result.output).toBe( - [ - "import { createFileRoute } from '@tanstack/react-router'", - '', - "export const Route = createFileRoute('/new')({})", - ].join('\r\n'), - ) - }) - - it('preserves import formatting when only renaming the route constructor', async () => { - const result = await transform({ - source: [ - 'import {', - ' Link,', - ' createFileRoute,', - `} from '@tanstack/react-router'`, - '', - "export const Route = createFileRoute('/old')({})", - ].join('\n'), - ctx: { - target: 'react', - routeId: '/new', - lazy: true, - }, - node: makeNode('lazy'), - }) - - expect(result.result).toBe('modified') - if (result.result !== 'modified') { - throw new Error(`expected modified result, got ${result.result}`) - } - expect(result.output).toBe( - [ - 'import {', - ' Link,', - ' createLazyFileRoute,', - `} from '@tanstack/react-router'`, - '', - "export const Route = createLazyFileRoute('/new')({})", - ].join('\n'), - ) - }) - - it('adds the missing constructor import with the file line ending', async () => { - const result = await transform({ - source: [ - "import { Link } from '@tanstack/react-router'", - '', - "export const Route = createFileRoute('/old')({})", - ].join('\r\n'), - ctx: { - target: 'react', - routeId: '/new', - lazy: false, - }, - node: makeNode(), - }) - - expect(result.result).toBe('modified') - if (result.result !== 'modified') { - throw new Error(`expected modified result, got ${result.result}`) - } - expect(result.output).toBe( - [ - "import { Link, createFileRoute } from '@tanstack/react-router'", - '', - "export const Route = createFileRoute('/new')({})", - ].join('\r\n'), - ) - }) - - it('ignores non-exported route constructor calls in the same file', async () => { - const result = await transform({ - source: [ - "import { createFileRoute } from '@tanstack/react-router'", - '', - "const OtherRoute = createFileRoute('/other')({})", - "export const Route = createFileRoute('/old')({})", - ].join('\n'), - ctx: { - target: 'react', - routeId: '/new', - lazy: false, - }, - node: makeNode(), - }) - - expect(result.result).toBe('modified') - if (result.result !== 'modified') { - throw new Error(`expected modified result, got ${result.result}`) - } - expect(result.output).toContain( - "const OtherRoute = createFileRoute('/other')({})", - ) - expect(result.output).toContain( - "export const Route = createFileRoute('/new')({})", - ) - }) - - it('returns an error for unsupported route id expressions', async () => { - const result = await transform({ - source: [ - "import { createFileRoute } from '@tanstack/react-router'", - '', - 'const routeId = getRouteId()', - 'export const Route = createFileRoute(routeId)({})', - ].join('\n'), - ctx: { - target: 'react', - routeId: '/new', - lazy: false, - }, - node: makeNode(), - }) - - expect(result.result).toBe('error') - if (result.result !== 'error') { - throw new Error(`expected error result, got ${result.result}`) - } - expect(String(result.error)).toContain( - 'expected route id to be a string literal or plain template literal', - ) - }) - - it('returns a distinct error for malformed direct createFileRoute calls', async () => { - const result = await transform({ - source: [ - "import { createFileRoute } from '@tanstack/react-router'", - '', - 'export const Route = createFileRoute({ component: Home })', - ].join('\n'), - ctx: { - target: 'react', - routeId: '/new', - lazy: false, - }, - node: makeNode(), - }) - - expect(result.result).toBe('error') - if (result.result !== 'error') { - throw new Error(`expected error result, got ${result.result}`) - } - expect(String(result.error)).toContain( - "expected Route export in /new to use createFileRoute('/path')({...}) or createLazyFileRoute('/path')({...})", - ) - }) - - it('returns a distinct error for malformed direct createLazyFileRoute calls', async () => { - const result = await transform({ - source: [ - "import { createLazyFileRoute } from '@tanstack/react-router'", - '', - 'export const Route = createLazyFileRoute({ component: Home })', - ].join('\n'), - ctx: { - target: 'react', - routeId: '/new', - lazy: true, - }, - node: makeNode('lazy'), - }) - - expect(result.result).toBe('error') - if (result.result !== 'error') { - throw new Error(`expected error result, got ${result.result}`) - } - expect(String(result.error)).toContain( - "expected Route export in /new to use createFileRoute('/path')({...}) or createLazyFileRoute('/path')({...})", - ) - }) - - it('preserves double-quote route IDs', async () => { - const result = await transform({ - source: [ - "import { createFileRoute } from '@tanstack/react-router'", - '', - 'export const Route = createFileRoute("/old")({})', - ].join('\n'), - ctx: { - target: 'react', - routeId: '/new', - lazy: false, - }, - node: makeNode(), - }) - - expect(result.result).toBe('modified') - if (result.result !== 'modified') { - throw new Error(`expected modified result, got ${result.result}`) - } - expect(result.output).toContain('createFileRoute("/new")') - }) - - it('preserves template-literal route IDs', async () => { - const result = await transform({ - source: [ - "import { createFileRoute } from '@tanstack/react-router'", - '', - 'export const Route = createFileRoute(`/old`)({})', - ].join('\n'), - ctx: { - target: 'react', - routeId: '/new', - lazy: false, - }, - node: makeNode(), - }) - - expect(result.result).toBe('modified') - if (result.result !== 'modified') { - throw new Error(`expected modified result, got ${result.result}`) - } - expect(result.output).toContain('createFileRoute(`/new`)') - }) - - it('rewrites createLazyFileRoute to createFileRoute when lazy changes', async () => { - const result = await transform({ - source: [ - "import { createLazyFileRoute } from '@tanstack/react-router'", - '', - "export const Route = createLazyFileRoute('/test')({})", - ].join('\n'), - ctx: { - target: 'react', - routeId: '/test', - lazy: false, - }, - node: makeNode(), - }) - - expect(result.result).toBe('modified') - if (result.result !== 'modified') { - throw new Error(`expected modified result, got ${result.result}`) - } - expect(result.output).toContain("createFileRoute('/test')") - expect(result.output).not.toContain('createLazyFileRoute') - }) - - it('handles export { Route } with a separate const declaration', async () => { - const result = await transform({ - source: [ - "import { createFileRoute } from '@tanstack/react-router'", - '', - "const Route = createFileRoute('/old')({})", - '', - 'export { Route }', - ].join('\n'), - ctx: { - target: 'react', - routeId: '/new', - lazy: false, - }, - node: makeNode(), - }) - - expect(result.result).toBe('modified') - if (result.result !== 'modified') { - throw new Error(`expected modified result, got ${result.result}`) - } - expect(result.output).toContain("createFileRoute('/new')") - }) - - it('returns an error for multiple exported route calls', async () => { - const result = await transform({ - source: [ - "import { createFileRoute } from '@tanstack/react-router'", - '', - "export const Route = createFileRoute('/a')({})", - '', - "const AltRoute = createFileRoute('/b')({})", - 'export { AltRoute as Route }', - ].join('\n'), - ctx: { - target: 'react', - routeId: '/new', - lazy: false, - }, - node: makeNode(), - }) - - expect(result.result).toBe('error') - if (result.result !== 'error') { - throw new Error(`expected error result, got ${result.result}`) - } - expect(String(result.error)).toContain( - 'expected exactly one createFileRoute/createLazyFileRoute call', - ) - }) - - it('prepends a new import when no target-module import exists', async () => { - const result = await transform({ - source: [ - "import { useState } from 'react'", - '', - "export const Route = createFileRoute('/old')({})", - ].join('\n'), - ctx: { - target: 'react', - routeId: '/new', - lazy: false, - }, - node: makeNode(), - }) - - expect(result.result).toBe('modified') - if (result.result !== 'modified') { - throw new Error(`expected modified result, got ${result.result}`) - } - expect(result.output).toBe( - [ - "import { createFileRoute } from '@tanstack/react-router'", - "import { useState } from 'react'", - '', - "export const Route = createFileRoute('/new')({})", - ].join('\n'), - ) - }) - - it('returns not-modified for a non-route-constructor call', async () => { - const result = await transform({ - source: [ - "import { createFileRoute } from '@tanstack/react-router'", - '', - 'export const Route = someOtherFactory()({})', - ].join('\n'), - ctx: { - target: 'react', - routeId: '/test', - lazy: false, - }, - node: makeNode(), - }) - - expect(result.result).toBe('not-modified') - }) - - it('preserves semicolons in normalized imports', async () => { - const result = await transform({ - source: [ - "import { createLazyFileRoute } from '@tanstack/react-router';", - '', - "export const Route = createLazyFileRoute('/old')({});", - ].join('\n'), - ctx: { - target: 'react', - routeId: '/new', - lazy: false, - }, - node: makeNode(), - }) - - expect(result.result).toBe('modified') - if (result.result !== 'modified') { - throw new Error(`expected modified result, got ${result.result}`) - } - expect(result.output).toContain( - "import { createFileRoute } from '@tanstack/react-router';", - ) - expect(result.output).not.toContain('createLazyFileRoute') - }) - - it('preserves type import specifiers when normalizing route imports', async () => { - const result = await transform({ - source: [ - "import { type LinkProps, createLazyFileRoute } from '@tanstack/react-router'", - '', - "export const Route = createLazyFileRoute('/old')({})", - ].join('\n'), - ctx: { - target: 'react', - routeId: '/new', - lazy: false, - }, - node: makeNode(), - }) - - expect(result.result).toBe('modified') - if (result.result !== 'modified') { - throw new Error(`expected modified result, got ${result.result}`) - } - expect(result.output).toContain( - "import { type LinkProps, createFileRoute } from '@tanstack/react-router'", - ) - expect(result.output).not.toContain('createLazyFileRoute') - }) - - // The recorded option keys drive prerendering and server-only route pruning. - it('records identifier and string-literal option keys, not computed or spread ones', () => { - const node = makeNode() - const result = transformToNewRoute( - [ - "import { createFileRoute } from '@tanstack/react-router'", - "export const Route = createFileRoute('/new')({ 'component': Page, [key]: load, ...rest, server: {} })", - ].join('\n'), - node, - ) - - expect(result).toEqual({ result: 'not-modified' }) - expect(node.createFileRouteProps).toEqual(new Set(['component', 'server'])) - }) -}) - -// The generator writes its output back over the user's route file, so every -// byte outside the route id and the router import must survive unchanged. -describe('transform preserves the rest of the route file', () => { - it('edits the right spans after a BOM and astral characters', () => { - const result = transformToNewRoute( - [ - '\uFEFF// 😀', - "import { createLazyFileRoute } from '@tanstack/react-router'", - "import { createFileRoute } from '@tanstack/react-router'", - "export const Route = createFileRoute(/* 🚀 */ '/old')({})", - ].join('\n'), - ) - - expect(result).toEqual({ - result: 'modified', - output: [ - '\uFEFF// 😀', - "import { createFileRoute } from '@tanstack/react-router'", - "export const Route = createFileRoute(/* 🚀 */ '/new')({})", - ].join('\n'), - }) - }) - - it.each([ - { - name: 'a default import', - imports: "import Router from '@tanstack/react-router'", - expected: - "import Router, { createFileRoute } from '@tanstack/react-router'", - }, - { - name: 'an aliased import of the constructor', - imports: - "import { createFileRoute as cfr } from '@tanstack/react-router'", - expected: - "import { createFileRoute as cfr, createFileRoute } from '@tanstack/react-router'", - }, - { - // The constructor goes into the named import, never the namespace one. - name: 'a namespace import', - imports: [ - "import * as Router from '@tanstack/react-router'", - "import { Link } from '@tanstack/react-router'", - ].join('\n'), - expected: [ - "import * as Router from '@tanstack/react-router'", - "import { Link, createFileRoute } from '@tanstack/react-router'", - ].join('\n'), - }, - ])('adds the missing constructor next to $name', ({ imports, expected }) => { - const route = "export const Route = createFileRoute('/old')({})" - - expect(transformToNewRoute(`${imports}\n${route}`)).toEqual({ - result: 'modified', - output: `${expected}\n${route.replace('/old', '/new')}`, - }) - }) - - it('updates only the Route declarator of a multi-declarator export', () => { - const result = transformToNewRoute( - [ - "import { createFileRoute } from '@tanstack/react-router'", - "export const Route = createFileRoute('/old')({}), path = '/old'", - ].join('\n'), - ) - - expect(result).toEqual({ - result: 'modified', - output: [ - "import { createFileRoute } from '@tanstack/react-router'", - "export const Route = createFileRoute('/new')({}), path = '/old'", - ].join('\n'), - }) - }) -}) diff --git a/packages/router-generator/tests/utils.test.ts b/packages/router-generator/tests/utils.test.ts index 504dacc0e6..b52bcbba31 100644 --- a/packages/router-generator/tests/utils.test.ts +++ b/packages/router-generator/tests/utils.test.ts @@ -2,13 +2,7 @@ import { describe, expect, it, vi } from 'vitest' import { RoutePrefixMap, cleanPath, - createLiteralRoutePathSegmentMetadata, - createRoutePathSegmentMetadata, - createRouteNodesByFullPath, - createRouteNodesByTo, - createTokenRegex, determineInitialRoutePath, - determineInitialRoutePathFromExplicitPath, hasEscapedLeadingUnderscore, hasEscapedTrailingUnderscore, inferFullPath, @@ -16,14 +10,12 @@ import { mergeImportDeclarations, multiSortBy, removeExt, - removeLayoutSegmentsAndUnderscoresWithEscape, removeLayoutSegmentsWithEscape, removeLeadingUnderscores, removeTrailingUnderscores, removeUnderscores, removeUnderscoresWithEscape, routePathToVariable, - sortRouteNodes, } from '../src/utils' import type { ImportDeclaration, RouteNode } from '../src/types' @@ -45,169 +37,6 @@ describe('inferFullPath', () => { // This avoids inferred fullPath "" which breaks match.fullPath unions expect(inferFullPath(node)).toBe('/') }) - - it('preserves escaped leading underscores after removing pathless ancestors', () => { - const node = { - routePath: '/_layout/_foo', - originalRoutePath: '/_layout/[_]foo', - } as unknown as RouteNode - - expect(inferFullPath(node)).toBe('/_foo') - }) - - it('preserves multiple escaped leading underscores after removing pathless ancestors', () => { - const node = { - routePath: '/_layout/__foo', - originalRoutePath: '/_layout/[__foo]', - } as unknown as RouteNode - - expect(inferFullPath(node)).toBe('/__foo') - }) - - it('preserves explicit literal leading underscores on index routes after removing pathless ancestors', () => { - const parent = { - routePath: '/_layout', - } as unknown as RouteNode - const node = { - routePath: '/_layout/_nested/', - originalRoutePath: '/_layout/_nested/', - _routePathSegmentMetadata: createLiteralRoutePathSegmentMetadata( - '/_layout/_nested', - parent, - true, - ), - } as unknown as RouteNode - - expect(inferFullPath(node)).toBe('/_nested/') - }) - - it('removes pathless index route segments when they are not marked literal', () => { - const node = { - routePath: '/_layout/_nested/', - originalRoutePath: '/_layout/_nested/', - } as unknown as RouteNode - - expect(inferFullPath(node)).toBe('/') - }) - - it('preserves escaped trailing underscores on index routes', () => { - const node = { - routePath: '/_layout/foo_/', - originalRoutePath: '/_layout/foo[_]/', - _routePathSegmentMetadata: createRoutePathSegmentMetadata( - '/_layout/foo_/', - '/_layout/foo[_]/', - ), - } as unknown as RouteNode - - expect(inferFullPath(node)).toBe('/foo_/') - }) - - it('removes unescaped trailing underscores on index routes', () => { - const node = { - routePath: '/_layout/foo_/', - originalRoutePath: '/_layout/foo_/', - } as unknown as RouteNode - - expect(inferFullPath(node)).toBe('/foo/') - }) -}) - -describe('createRoutePathSegmentMetadata', () => { - it('preserves escaped trailing underscores on index routes', () => { - const metadata = createRoutePathSegmentMetadata('/foo_/', '/foo[_]/') - - expect(metadata).toHaveLength(3) - expect(metadata?.[1]).toEqual({ literalTrailingUnderscore: true }) - }) - - it('preserves mixed escaped leading and trailing underscores', () => { - const metadata = createRoutePathSegmentMetadata('/_foo_/', '/[_]foo[_]/') - - expect(metadata).toHaveLength(3) - expect(metadata?.[1]).toEqual({ - literalLeadingUnderscore: true, - literalTrailingUnderscore: true, - }) - }) - - it('tracks multiple literal underscore segments independently', () => { - const metadata = createRoutePathSegmentMetadata( - '/_foo/bar_/_baz_/', - '/[_]foo/bar[_]/[_baz_]/', - ) - - expect(metadata).toHaveLength(5) - expect(metadata?.[1]).toEqual({ literalLeadingUnderscore: true }) - expect(metadata?.[2]).toEqual({ literalTrailingUnderscore: true }) - expect(metadata?.[3]).toEqual({ - literalLeadingUnderscore: true, - literalTrailingUnderscore: true, - }) - }) -}) - -describe('createRouteNodesByTo', () => { - const createRoute = ( - overrides: Partial<RouteNode> & { routePath: string }, - ): RouteNode => ({ - filePath: 'test.tsx', - fullPath: overrides.routePath, - variableName: 'Test', - _fsRouteType: 'static', - cleanedPath: overrides.routePath.endsWith('/') - ? '/' - : overrides.routePath.split('/').at(-1), - ...overrides, - }) - - it('prefers index routes over pathless layouts for duplicate public to paths', () => { - const pathlessRoute = createRoute({ - routePath: '/livestock/$farmId/medicine/_form', - _fsRouteType: 'pathless_layout', - variableName: 'Pathless', - }) - const indexRoute = createRoute({ - routePath: '/livestock/$farmId/medicine/', - cleanedPath: '/', - variableName: 'Index', - }) - - const map = createRouteNodesByTo([pathlessRoute, indexRoute]) - - expect(map.get('/livestock/$farmId/medicine')).toBe(indexRoute) - }) -}) - -describe('createRouteNodesByFullPath', () => { - const createRoute = ( - overrides: Partial<RouteNode> & { routePath: string }, - ): RouteNode => ({ - filePath: 'test.tsx', - fullPath: overrides.routePath, - variableName: 'Test', - _fsRouteType: 'static', - cleanedPath: overrides.routePath.endsWith('/') - ? '/' - : overrides.routePath.split('/').at(-1), - ...overrides, - }) - - it('prefers concrete routes over pathless layouts for duplicate full paths', () => { - const concreteRoute = createRoute({ - routePath: '/livestock/$farmId/medicine', - variableName: 'Concrete', - }) - const pathlessRoute = createRoute({ - routePath: '/livestock/$farmId/medicine/_form', - _fsRouteType: 'pathless_layout', - variableName: 'Pathless', - }) - - const map = createRouteNodesByFullPath([concreteRoute, pathlessRoute]) - - expect(map.get('/livestock/$farmId/medicine')).toBe(concreteRoute) - }) }) describe('determineInitialRoutePath', () => { @@ -309,26 +138,6 @@ describe('determineInitialRoutePath', () => { }) }) -describe('determineInitialRoutePathFromExplicitPath', () => { - it('preserves dots as literal route path characters', () => { - expect( - determineInitialRoutePathFromExplicitPath('pathless.layout'), - ).toStrictEqual({ - routePath: '/pathless.layout', - originalRoutePath: '/pathless.layout', - }) - }) - - it('resolves bracket escapes without applying file-route separators', () => { - expect( - determineInitialRoutePathFromExplicitPath('pathless[.]layout'), - ).toStrictEqual({ - routePath: '/pathless.layout', - originalRoutePath: '/pathless[.]layout', - }) - }) -}) - describe('multiSortBy', () => { it('sorts by single accessor', () => { const arr = [{ v: 3 }, { v: 1 }, { v: 2 }] @@ -541,7 +350,6 @@ describe('hasEscapedLeadingUnderscore', () => { it('returns true for fully escaped segment starting with underscore', () => { expect(hasEscapedLeadingUnderscore('[_layout]')).toBe(true) expect(hasEscapedLeadingUnderscore('[_foo]')).toBe(true) - expect(hasEscapedLeadingUnderscore('[__foo]')).toBe(true) expect(hasEscapedLeadingUnderscore('[_1nd3x]')).toBe(true) expect(hasEscapedLeadingUnderscore('[_]')).toBe(true) }) @@ -573,7 +381,6 @@ describe('hasEscapedTrailingUnderscore', () => { it('returns true for fully escaped segment ending with underscore', () => { expect(hasEscapedTrailingUnderscore('[blog_]')).toBe(true) expect(hasEscapedTrailingUnderscore('[foo_]')).toBe(true) - expect(hasEscapedTrailingUnderscore('[foo__]')).toBe(true) expect(hasEscapedTrailingUnderscore('[_r0ut3_]')).toBe(true) expect(hasEscapedTrailingUnderscore('[_]')).toBe(true) }) @@ -608,7 +415,6 @@ describe('isSegmentPathless', () => { it('returns false for fully escaped segment', () => { expect(isSegmentPathless('_layout', '[_layout]')).toBe(false) - expect(isSegmentPathless('__layout', '[__layout]')).toBe(false) expect(isSegmentPathless('_1nd3x', '[_1nd3x]')).toBe(false) }) @@ -727,69 +533,6 @@ describe('removeLayoutSegmentsWithEscape', () => { }) }) -describe('removeLayoutSegmentsAndUnderscoresWithEscape', () => { - it('removes layout segments and preserves escaped underscores in remaining segments', () => { - expect( - removeLayoutSegmentsAndUnderscoresWithEscape( - '/_layout/_foo', - '/_layout/[_]foo', - ), - ).toBe('/_foo') - }) - - it('removes multiple layout segments before escaped underscores', () => { - expect( - removeLayoutSegmentsAndUnderscoresWithEscape( - '/_layout/_nested/_foo', - '/_layout/_nested/[_]foo', - ), - ).toBe('/_foo') - }) - - it('preserves multiple escaped leading underscores in remaining segments', () => { - expect( - removeLayoutSegmentsAndUnderscoresWithEscape( - '/_layout/__foo', - '/_layout/[__foo]', - ), - ).toBe('/__foo') - - expect( - removeLayoutSegmentsAndUnderscoresWithEscape( - '/_layout/__foo', - '/_layout/[_][_]foo', - ), - ).toBe('/__foo') - }) - - it('removes non-escaped underscores from remaining segments', () => { - expect( - removeLayoutSegmentsAndUnderscoresWithEscape( - '/_layout/foo_/bar_', - '/_layout/foo_/bar_', - ), - ).toBe('/foo/bar') - }) - - it('preserves escaped trailing underscores after removing pathless ancestors', () => { - expect( - removeLayoutSegmentsAndUnderscoresWithEscape( - '/_layout/foo_/', - '/_layout/foo[_]/', - ), - ).toBe('/foo_/') - }) - - it('preserves mixed escaped leading and trailing underscores after removing pathless ancestors', () => { - expect( - removeLayoutSegmentsAndUnderscoresWithEscape( - '/_layout/_foo_/', - '/_layout/[_]foo[_]/', - ), - ).toBe('/_foo_/') - }) -}) - describe('routePathToVariable', () => { it.each([ ['/test/$/index', 'TestSplatIndex'], @@ -988,85 +731,3 @@ describe('RoutePrefixMap', () => { }) }) }) - -describe('sortRouteNodes', () => { - const indexTokenSegmentRegex = createTokenRegex('index', { type: 'segment' }) - - const node = (routePath: string): RouteNode => - ({ routePath }) as unknown as RouteNode - - const sortPaths = (routePaths: Array<string>): Array<string | undefined> => - sortRouteNodes(routePaths.map(node), indexTokenSegmentRegex).map( - (n) => n.routePath, - ) - - /** Every distinct ordering of `arr` (Heap-free recursive permutation). */ - function permutations<T>(arr: Array<T>): Array<Array<T>> { - if (arr.length <= 1) { - return [arr] - } - const result: Array<Array<T>> = [] - arr.forEach((item, i) => { - const rest = [...arr.slice(0, i), ...arr.slice(i + 1)] - for (const perm of permutations(rest)) { - result.push([item, ...perm]) - } - }) - return result - } - - it('orders tied siblings by routePath', () => { - // Same segment count, both non-index: they tie on every key before routePath. - const expected = ['/account/beta-features', '/account/busy-guard'] - expect( - sortPaths(['/account/busy-guard', '/account/beta-features']), - ).toEqual(expected) - expect( - sortPaths(['/account/beta-features', '/account/busy-guard']), - ).toEqual(expected) - }) - - it('applies root, segment-count and index precedence before the routePath tiebreaker', () => { - const sorted = sortPaths([ - '/posts', - '/account/busy-guard', - '/index', - '/__root', - '/account/beta-features', - '/about', - '/posts/index', - ]) - - expect(sorted).toEqual([ - '/__root', // root always first - '/index', // depth 1, index segment before non-index - '/about', // depth 1, non-index, routePath tiebreak - '/posts', // depth 1, non-index, routePath tiebreak - '/posts/index', // depth 2, index segment before non-index - '/account/beta-features', // depth 2, non-index, routePath tiebreak - '/account/busy-guard', // depth 2, non-index, routePath tiebreak - ]) - }) - - it('is deterministic for every input permutation (stable sort)', () => { - // Includes several sets that tie on all keys before routePath (the two - // `/account/*` leaves, `/about` vs `/posts`) — exactly the case that the - // former whole-object tiebreaker left in an engine- and input-order- - // dependent order. `sortRouteNodes` must map every permutation to the - // same output. - const routePaths = [ - '/__root', - '/index', - '/about', - '/posts', - '/account/beta-features', - '/account/busy-guard', - ] - - const reference = sortPaths(routePaths) - - for (const permutation of permutations(routePaths)) { - expect(sortPaths(permutation)).toEqual(reference) - } - }) -}) diff --git a/packages/router-generator/tsconfig.build.json b/packages/router-generator/tsconfig.build.json deleted file mode 100644 index 92be18587f..0000000000 --- a/packages/router-generator/tsconfig.build.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "rootDir": "./src" - }, - "include": ["src"] -} diff --git a/packages/router-generator/tsconfig.json b/packages/router-generator/tsconfig.json index d1334dff90..9a37e6d506 100644 --- a/packages/router-generator/tsconfig.json +++ b/packages/router-generator/tsconfig.json @@ -1,8 +1,7 @@ { "extends": "../../tsconfig.json", "compilerOptions": { - "jsx": "react-jsx", - "types": ["node"] + "jsx": "react-jsx" }, "include": [ "src", diff --git a/packages/router-generator/vite.config.ts b/packages/router-generator/vite.config.ts index 5e305866b6..c24b19ec98 100644 --- a/packages/router-generator/vite.config.ts +++ b/packages/router-generator/vite.config.ts @@ -14,7 +14,6 @@ const config = defineConfig({ export default mergeConfig( config, tanstackViteConfig({ - tsconfigPath: './tsconfig.build.json', entry: './src/index.ts', srcDir: './src', }), diff --git a/packages/router-plugin/AGENTS.md b/packages/router-plugin/AGENTS.md deleted file mode 100644 index e954110819..0000000000 --- a/packages/router-plugin/AGENTS.md +++ /dev/null @@ -1,7 +0,0 @@ -# Router bundler plugin - -- Preserve one initialization of shared module state across reference and split chunks. Shared extraction includes transitive dependencies and whole destructured declarations; never extract `Route` or bindings that depend on it. The invariant suite in `tests/code-splitter.test.ts` covers these contracts. -- `handleRouteUpdate` is stringified and injected into app modules. Keep runtime dependencies inside the function or explicitly emit them; extracting a helper to plugin module scope breaks the generated function. `tests/handle-route-update.test.ts` executes that emitted code. -- Route HMR rebuilds indexes, clears `resolvePathCache`, replaces lazy-chunk ownership, and refreshes active routes while preserving Fast Refresh component identities. Keep these steps coordinated when adding derived state. -- For code-splitting changes, add inputs under `tests/code-splitter/test-files/<framework>/`. Regenerate and review reference, virtual, and shared snapshots for every grouping in [`tests/code-splitter.test.ts`](tests/code-splitter.test.ts). -- Check [`tests/constants.ts`](tests/constants.ts) for framework coverage: the snapshot matrix currently covers React and Solid only. Validate affected Vue behavior in Vue router e2e apps. diff --git a/packages/router-plugin/CHANGELOG.md b/packages/router-plugin/CHANGELOG.md index 5b18ae7e6a..99e4fa614d 100644 --- a/packages/router-plugin/CHANGELOG.md +++ b/packages/router-plugin/CHANGELOG.md @@ -1,762 +1,5 @@ # @tanstack/router-plugin -## 1.169.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. - -- [#8851](https://github.com/TanStack/router/pull/8851) [`d250819`](https://github.com/TanStack/router/commit/d25081952dd04a5f5a44db7c8df5cbbf50fad054) - Require Vite 6 or later: the `vite` peer range is now `>=6.0.0`. Vite 5 is no longer supported. - -### Patch Changes - -- [`1ba19a0`](https://github.com/TanStack/router/commit/1ba19a04456983ee0f8adffd038b6b1194441e15) - fix: webpack and Rspack production builds no longer put the code splitter's "will not be code-split" warning, with the route file's absolute path, into the client bundle when the build process's `NODE_ENV` isn't `production`. The bundler's mode decides, and a config without `mode` counts as production, as it does for webpack and Rspack. The warning still prints in the build output. - -- [#8852](https://github.com/TanStack/router/pull/8852) [`94f36c4`](https://github.com/TanStack/router/commit/94f36c4a9ecf3062b326a8eb772e73b00c0644d9) - The esbuild plugin now throws when `autoCodeSplitting` is enabled, and `TanStackRouterCodeSplitterEsbuild` throws, instead of silently bundling every route without splitting. Route generation with esbuild is unchanged. - -- [#8856](https://github.com/TanStack/router/pull/8856) [`533ca27`](https://github.com/TanStack/router/commit/533ca2704452f36c5fef5c5fe084554d9b5db1ab) - Remove the undocumented `plugin.hmr.style` option and the `HmrOptions` type. Each bundler entry now picks its own HMR runtime: the webpack and Rspack entries already forced `'webpack'`, and on Vite, `'webpack'` broke route HMR. - -- [#8853](https://github.com/TanStack/router/pull/8853) [`13b6256`](https://github.com/TanStack/router/commit/13b625683030ea4ab359495ecda570e05e472587) - Remove internal code-splitter APIs: the `codeSplittingOptions.compilerPlugins` option, and the root-entry exports `unpluginRouterCodeSplitterFactory`, `getObjectPropertyKeyName`, `CodeSplitCompilerPlugin`, `ReferenceRouteCompilerPlugin`, `ReferenceRouteCompilerPluginContext` and `VirtualRouteSplitNodeCompilerPluginContext`. - -- [#8860](https://github.com/TanStack/router/pull/8860) [`b5e2ac9`](https://github.com/TanStack/router/commit/b5e2ac9c4cee4c5c6f464adc6cfddcddf6c84171) - Source maps of split routes now point at the route file. On webpack and Rspack (including Rsbuild), a split component or shared code mapped to the wrong line, because unplugin's loader dropped the router plugin's map; `unplugin` now requires `^3.5.0`, which keeps it. The maps of split and shared modules also name the route file itself instead of its `?tsr-split` / `?tsr-shared` module id, so debuggers bind breakpoints set in the route file. - -- [#8870](https://github.com/TanStack/router/pull/8870) [`f420d4a`](https://github.com/TanStack/router/commit/f420d4a6dacfaa81d306b7bbc9af8f1010d1a1bc) - Vite route HMR now writes `import.meta.hot.accept(` out instead of calling it through a `hot` alias. Vite only treats a module as a hot boundary when the call is spelled out, so an edit of a route file no framework plugin accepts (a `.ts` route file, or an app without `@vitejs/plugin-react`) reloaded the page instead of updating the route in place. With React HMR, a route file that declares its own top-level `hot` binding no longer fails to compile with `Duplicate declaration "hot"`. - -- Updated dependencies [[`446ce1b`](https://github.com/TanStack/router/commit/446ce1b30650d85f1fc78f2d1ee42712e40b75c6), [`ad5b3b7`](https://github.com/TanStack/router/commit/ad5b3b7a0990eed7351d672ea6695d341108e0d6), [`ff157f0`](https://github.com/TanStack/router/commit/ff157f0079982e90d62be7fdeecfb77e4fdcec69)]: - - @tanstack/router-generator@1.168.0 - - @tanstack/router-utils@1.163.0 - -## 1.168.48 - -### 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/<package>#<skill>`) instead of relative file links that break once packages are installed. - -- [#8737](https://github.com/TanStack/router/pull/8737) [`647cb73`](https://github.com/TanStack/router/commit/647cb737a5622813d276d6042766692ca5ae67ed) - Remove the `enableRouteGeneration` option. Route generation now always runs, so `autoCodeSplitting` always has the route metadata it needs. - -- 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/router-generator@1.167.46 - -## 1.168.47 - -### 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/router-generator@1.167.45 - -## 1.168.46 - -### Patch Changes - -- Updated dependencies [[`923d98b`](https://github.com/TanStack/router/commit/923d98b18b6cd90b6219591e20e86115dc61048e)]: - - @tanstack/router-utils@1.162.4 - - @tanstack/router-generator@1.167.44 - -## 1.168.45 - -### Patch Changes - -- Updated dependencies [[`d6ba115`](https://github.com/TanStack/router/commit/d6ba115d5751c75e20943f0062577cf17b446d82)]: - - @tanstack/router-core@1.171.37 - - @tanstack/react-router@1.170.44 - - @tanstack/router-generator@1.167.43 - -## 1.168.44 - -### Patch Changes - -- [#8655](https://github.com/TanStack/router/pull/8655) [`e66da18`](https://github.com/TanStack/router/commit/e66da18266859ab49e20a7b8c858232449ee5290) - Remove redundant string excludes from the reference code-splitter transform filter to avoid unnecessary glob compilation in unplugin bundler adapters. - -- Updated dependencies [[`57bd1a9`](https://github.com/TanStack/router/commit/57bd1a92f9839af5bf773c3b36d039569fb1a41e), [`94d6d8e`](https://github.com/TanStack/router/commit/94d6d8e49694e225cb07e2a6777633d08aeeb3c5)]: - - @tanstack/router-generator@1.167.42 - - @tanstack/router-core@1.171.36 - - @tanstack/react-router@1.170.43 - -## 1.168.43 - -### 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/router-generator@1.167.41 - -## 1.168.42 - -### 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/router-generator@1.167.40 - -## 1.168.41 - -### 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)]: - - @tanstack/react-router@1.170.40 - - @tanstack/router-core@1.171.33 - - @tanstack/router-generator@1.167.39 - -## 1.168.40 - -### 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/router-generator@1.167.38 - -## 1.168.39 - -### 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/router-generator@1.167.37 - -## 1.168.38 - -### 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-generator@1.167.36 - -## 1.168.37 - -### Patch Changes - -- [#8300](https://github.com/TanStack/router/pull/8300) [`49bcd4d`](https://github.com/TanStack/router/commit/49bcd4db743dba4a783d5533a42a0f97a5721292) - Refresh compatible build and runtime dependencies. - -- 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), [`0654c0a`](https://github.com/TanStack/router/commit/0654c0a1a427db24d9af13c1d6ad1217a588c0c9)]: - - @tanstack/router-core@1.171.29 - - @tanstack/react-router@1.170.34 - - @tanstack/router-generator@1.167.35 - - @tanstack/router-utils@1.162.3 - -## 1.168.36 - -### 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/router-generator@1.167.34 - -## 1.168.35 - -### 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/router-generator@1.167.33 - -## 1.168.34 - -### 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/router-generator@1.167.32 - -## 1.168.33 - -### 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/router-generator@1.167.31 - -## 1.168.32 - -### 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/router-generator@1.167.30 - -## 1.168.31 - -### 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/router-generator@1.167.29 - -## 1.168.30 - -### 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/router-generator@1.167.28 - -## 1.168.29 - -### 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/router-generator@1.167.27 - -## 1.168.28 - -### 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/router-generator@1.167.26 - -## 1.168.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/router-generator@1.167.25 - -## 1.168.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/router-generator@1.167.24 - -## 1.168.25 - -### Patch Changes - -- Updated dependencies [[`b2908c6`](https://github.com/TanStack/router/commit/b2908c642ac09aa08e6d965d2a820d7186e42fd5)]: - - @tanstack/router-core@1.171.17 - - @tanstack/react-router@1.170.20 - - @tanstack/router-generator@1.167.23 - -## 1.168.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/router-generator@1.167.22 - -## 1.168.23 - -### Patch Changes - -- [#7855](https://github.com/TanStack/router/pull/7855) [`49f6863`](https://github.com/TanStack/router/commit/49f686324574ea65851317cbba084eb386a911c6) - Preserve React component state during HMR when route components are declared with lowercase function names. The development-only React transforms cover split route component groups and unsplit root route component options, including shell, pending, and error components, without changing production output. - -## 1.168.22 - -### Patch Changes - -- Updated dependencies [[`78dd1a6`](https://github.com/TanStack/router/commit/78dd1a645dc1a9e9f4f649d9aff12005044d4fcc)]: - - @tanstack/router-generator@1.167.21 - -## 1.168.21 - -### Patch Changes - -- Updated dependencies [[`e56a677`](https://github.com/TanStack/router/commit/e56a67742da9021b009b8db0cdc8bfe99878c25b)]: - - @tanstack/router-generator@1.167.20 - -## 1.168.20 - -### 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/router-generator@1.167.19 - -## 1.168.19 - -### 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/router-generator@1.167.18 - -## 1.168.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/router-generator@1.167.17 - -## 1.168.17 - -### Patch Changes - -- [#7560](https://github.com/TanStack/router/pull/7560) [`837897f`](https://github.com/TanStack/router/commit/837897f0733b836dd63880546eec4c20cf06be59) - Fix route HMR so aliased route imports keep generated route properties after hot reloads. - -- Updated dependencies [[`df1076c`](https://github.com/TanStack/router/commit/df1076c03ae5a51ab384bebd4d6afda20fb6f107)]: - - @tanstack/router-core@1.171.12 - - @tanstack/react-router@1.170.14 - - @tanstack/router-generator@1.167.16 - -## 1.168.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/router-generator@1.167.15 - -## 1.168.15 - -### 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/router-utils@1.162.2 - - @tanstack/router-core@1.171.10 - - @tanstack/router-generator@1.167.14 - - @tanstack/react-router@1.170.12 - -## 1.168.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/router-generator@1.167.13 - -## 1.168.13 - -### 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/router-generator@1.167.12 - -## 1.168.12 - -### 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/router-generator@1.167.11 - -## 1.168.11 - -### 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/router-generator@1.167.10 - -## 1.168.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/router-generator@1.167.9 - -## 1.168.9 - -### Patch Changes - -- Updated dependencies [[`7df0d02`](https://github.com/TanStack/router/commit/7df0d02bfb1407b1f07731ef69af24e2f0e415d7)]: - - @tanstack/router-generator@1.167.8 - -## 1.168.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/router-generator@1.167.7 - -## 1.168.7 - -### Patch Changes - -- Update chokidar to v5. ([#7439](https://github.com/TanStack/router/pull/7439)) - -- 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. - -- Updated dependencies [[`5fa9e55`](https://github.com/TanStack/router/commit/5fa9e555f3a2edb5e45586623e6bcbfa7f7c7a6b)]: - - @tanstack/router-core@1.171.3 - - @tanstack/router-utils@1.162.1 - - @tanstack/react-router@1.170.5 - - @tanstack/router-generator@1.167.6 - -## 1.168.6 - -### 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)) - -- Updated dependencies [[`b60eb36`](https://github.com/TanStack/router/commit/b60eb36e59e8a468ee0742cbcf7f47aca1ff1c67)]: - - @tanstack/router-core@1.171.2 - - @tanstack/router-generator@1.167.5 - - @tanstack/react-router@1.170.4 - -## 1.168.5 - -### Patch Changes - -- Fix Vite Fast Refresh detection for root routes created with `createRootRouteWithContext` type arguments. ([#7420](https://github.com/TanStack/router/pull/7420)) - -## 1.168.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/router-generator@1.167.4 - -## 1.168.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/router-generator@1.167.3 - -## 1.168.2 - -### Patch Changes - -- Updated dependencies [[`742941e`](https://github.com/TanStack/router/commit/742941e2f1bf069c950d0a4985b2cd733639509e)]: - - @tanstack/router-generator@1.167.2 - -## 1.168.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/router-generator@1.167.1 - -## 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), [`038cd12`](https://github.com/TanStack/router/commit/038cd123b70bc6154d75abb6404a744c376f8f6a), [`201e150`](https://github.com/TanStack/router/commit/201e150bd1412bae2faa9ce53f0fefcb7574ac14)]: - - @tanstack/router-core@1.170.0 - - @tanstack/router-generator@1.167.0 - - @tanstack/react-router@1.170.0 - - @tanstack/router-utils@1.162.0 - - @tanstack/virtual-file-routes@1.162.0 - -## 1.167.35 - -### Patch Changes - -- Updated dependencies [[`c5811aa`](https://github.com/TanStack/router/commit/c5811aacb59b69a8179f14cd9529a51b2206d504)]: - - @tanstack/router-generator@1.166.42 - -## 1.167.34 - -### Patch Changes - -- Updated dependencies [[`35e88f0`](https://github.com/TanStack/router/commit/35e88f04996d71019a1868b7b06ecb4ddbc9df9e)]: - - @tanstack/router-core@1.169.2 - - @tanstack/react-router@1.169.2 - - @tanstack/router-generator@1.166.41 - -## 1.167.33 - -### 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-utils@1.161.8 - -## 1.167.32 - -### 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)) - -## 1.167.31 - -### 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/router-generator@1.166.39 - -## 1.167.30 - -### 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/router-generator@1.166.38 - -## 1.167.29 - -### 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/router-generator@1.166.37 - -## 1.167.28 - -### 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/router-generator@1.166.36 - -## 1.167.27 - -### Patch Changes - -- Updated dependencies [[`a2ad394`](https://github.com/TanStack/router/commit/a2ad394598e2079ab4050ebb16bb03b31d69c32a)]: - - @tanstack/router-generator@1.166.35 - -## 1.167.26 - -### Patch Changes - -- refactor(router-plugin): upgrade unplugin to `v3` ([#7258](https://github.com/TanStack/router/pull/7258)) - -## 1.167.25 - -### Patch Changes - -- Fix React route HMR for webpack and rspack so it no longer imports `react-refresh/runtime`, avoiding failures when that optional dependency is not installed. ([#7255](https://github.com/TanStack/router/pull/7255)) - -## 1.167.24 - -### 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/router-generator@1.166.34 - -## 1.167.23 - -### Patch Changes - -- rsbuild ([#7228](https://github.com/TanStack/router/pull/7228)) - -- Updated dependencies [[`91a7089`](https://github.com/TanStack/router/commit/91a708989d00537a21911e74ff60bbfec8266295)]: - - @tanstack/router-utils@1.161.7 - - @tanstack/router-generator@1.166.33 - -## 1.167.22 - -### 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/router-generator@1.166.32 - -## 1.167.21 - -### Patch Changes - -- Updated dependencies [[`328d7e5`](https://github.com/TanStack/router/commit/328d7e5ebc6b8074242a07d68ccafafb83e37a0e)]: - - @tanstack/router-generator@1.166.31 - -## 1.167.20 - -### Patch Changes - -- fix: update vite-plugin-solid peer dependency to support version 3.0.0-0 ([#7170](https://github.com/TanStack/router/pull/7170)) - -## 1.167.19 - -### Patch Changes - -- Updated dependencies [[`105d056`](https://github.com/TanStack/router/commit/105d05691a247779a63e7b688aa1207cce619339)]: - - @tanstack/router-generator@1.166.30 - - @tanstack/react-router@1.168.19 - -## 1.167.18 - -### Patch Changes - -- add vite 8 to peer deps ([#7160](https://github.com/TanStack/router/pull/7160)) - -## 1.167.17 - -### 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/router-generator@1.166.29 - -## 1.167.16 - -### 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/router-generator@1.166.28 - -## 1.167.15 - -### 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/router-generator@1.166.27 - -## 1.167.14 - -### 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/react-router@1.168.15 - - @tanstack/router-core@1.168.11 - - @tanstack/router-generator@1.166.26 - -## 1.167.13 - -### 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/react-router@1.168.14 - - @tanstack/router-core@1.168.10 - - @tanstack/router-generator@1.166.25 - -## 1.167.12 - -### 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/router-generator@1.166.24 - -## 1.167.11 - -### 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/router-generator@1.166.23 - -## 1.167.10 - -### Patch Changes - -- Initialize `import.meta.hot.data` before storing stable split components so Vitest does not crash when HMR data is missing. ([#7074](https://github.com/TanStack/router/pull/7074)) - -## 1.167.9 - -### 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/router-generator@1.166.22 - -## 1.167.8 - -### 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/router-generator@1.166.21 - -## 1.167.7 - -### Patch Changes - -- Updated dependencies [[`70b2225`](https://github.com/TanStack/router/commit/70b222513720d99c6d44bd3f28d1e9b19dc91a43)]: - - @tanstack/router-generator@1.166.20 - -## 1.167.6 - -### 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/router-generator@1.166.19 - -## 1.167.5 - -### 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/router-generator@1.166.18 - -## 1.167.4 - -### 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/router-generator@1.166.17 - -## 1.167.3 - -### Patch Changes - -- Updated dependencies [[`c9e1855`](https://github.com/TanStack/router/commit/c9e18555f3a5531e96de8f574cfca9edcdb18e5c)]: - - @tanstack/react-router@1.168.2 - - @tanstack/router-core@1.168.2 - - @tanstack/router-generator@1.166.16 - ## 1.167.2 ### Patch Changes diff --git a/packages/router-plugin/bin/intent.js b/packages/router-plugin/bin/intent.js new file mode 100755 index 0000000000..5b08532885 --- /dev/null +++ b/packages/router-plugin/bin/intent.js @@ -0,0 +1,25 @@ +#!/usr/bin/env node +// Auto-generated by @tanstack/intent setup +// Exposes the intent end-user CLI for consumers of this library. +// Commit this file, then add to your package.json: +// "bin": { "intent": "./bin/intent.js" } +try { + await import('@tanstack/intent/intent-library') +} catch (e) { + const isModuleNotFound = + e?.code === 'ERR_MODULE_NOT_FOUND' || e?.code === 'MODULE_NOT_FOUND' + const missingIntentLibrary = + typeof e?.message === 'string' && e.message.includes('@tanstack/intent') + + if (isModuleNotFound && missingIntentLibrary) { + console.error('@tanstack/intent is not installed.') + console.error('') + console.error('Install it as a dev dependency:') + console.error(' npm add -D @tanstack/intent') + console.error('') + console.error('Or run directly:') + console.error(' npx @tanstack/intent@latest list') + process.exit(1) + } + throw e +} diff --git a/packages/router-plugin/package.json b/packages/router-plugin/package.json index b681bb61a2..1b0372b0f6 100644 --- a/packages/router-plugin/package.json +++ b/packages/router-plugin/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/router-plugin", - "version": "1.169.0", + "version": "1.167.2", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", @@ -31,12 +31,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": "node ../../node_modules/typescript59/lib/tsc.js", - "test:types:ts60": "tsc6", - "test:types:ts70": "tsc", + "test:types:ts59": "tsc", "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", "build": "vite build" }, @@ -63,16 +63,6 @@ "default": "./dist/cjs/vite.cjs" } }, - "./context": { - "import": { - "types": "./dist/esm/context.d.ts", - "default": "./dist/esm/context.js" - }, - "require": { - "types": "./dist/cjs/context.d.cts", - "default": "./dist/cjs/context.cjs" - } - }, "./rspack": { "import": { "types": "./dist/esm/rspack.d.ts", @@ -114,42 +104,34 @@ "!skills/_artifacts" ], "engines": { - "node": "^20.19.0 || >=22.12.0" + "node": ">=20.19" }, "dependencies": { - "@babel/core": "catalog:", - "@babel/template": "^7.29.7", - "@babel/types": "catalog:", + "@babel/core": "^7.28.5", + "@babel/plugin-syntax-jsx": "^7.27.1", + "@babel/plugin-syntax-typescript": "^7.27.1", + "@babel/template": "^7.27.2", + "@babel/traverse": "^7.28.5", + "@babel/types": "^7.28.5", "@tanstack/router-core": "workspace:*", "@tanstack/router-generator": "workspace:*", "@tanstack/router-utils": "workspace:*", - "chokidar": "catalog:", - "unplugin": "^3.5.0", - "zod": "catalog:" + "@tanstack/virtual-file-routes": "workspace:*", + "chokidar": "^3.6.0", + "unplugin": "^2.1.2", + "zod": "^3.24.2" }, "devDependencies": { - "@rsbuild/core": "catalog:", + "@tanstack/intent": "^0.0.14", "@types/babel__core": "^7.20.5", "@types/babel__template": "^7.4.4", - "@types/node": ">=20", - "@tanstack/vite-config": "catalog:", - "vitest": "catalog:", - "jsdom": "catalog:", - "react": "catalog:", - "react-dom": "catalog:", - "@types/react": "catalog:", - "@types/react-dom": "catalog:", - "prettier": "^3.9.6", - "@arethetypeswrong/cli": "catalog:", - "publint": "catalog:", - "rimraf": "catalog:", - "webpack": "^5.104.1" + "@types/babel__traverse": "^7.28.0" }, "peerDependencies": { - "@rsbuild/core": ">=1.0.2 || ^2.0.0", + "@rsbuild/core": ">=1.0.2", "@tanstack/react-router": "workspace:^", - "vite": ">=6.0.0", - "vite-plugin-solid": "^2.11.10 || ^3.0.0-0", + "vite": ">=5.0.0 || >=6.0.0 || >=7.0.0", + "vite-plugin-solid": "^2.11.10 || 3.0.0-next.3", "webpack": ">=5.92.0" }, "peerDependenciesMeta": { @@ -168,5 +150,8 @@ "webpack": { "optional": true } + }, + "bin": { + "intent": "./bin/intent.js" } } diff --git a/packages/router-plugin/skills/_artifacts/domain_map.yaml b/packages/router-plugin/skills/_artifacts/domain_map.yaml index dd83f2c913..8ce9e31f4d 100644 --- a/packages/router-plugin/skills/_artifacts/domain_map.yaml +++ b/packages/router-plugin/skills/_artifacts/domain_map.yaml @@ -1,12 +1,12 @@ # domain_map.yaml # Library: @tanstack/router-plugin -# Version: 1.168.23 +# Version: 1.166.2 # Date: 2026-03-08 # Status: reviewed library: name: '@tanstack/router-plugin' - version: '1.168.23' + version: '1.166.2' repository: 'https://github.com/TanStack/router' description: >- Bundler plugin for route generation and automatic code splitting. @@ -59,12 +59,4 @@ skills: priority: MEDIUM status: active - - mistake: 'Editing routeTree.gen.ts instead of regenerating' - mechanism: >- - Manual changes are overwritten and can put source routes, generated - types, and runtime routing out of sync. Fix source or config and - regenerate the tree. - priority: HIGH - status: active - gaps: [] diff --git a/packages/router-plugin/skills/_artifacts/skill_spec.md b/packages/router-plugin/skills/_artifacts/skill_spec.md index 586ee34ade..4d4881232f 100644 --- a/packages/router-plugin/skills/_artifacts/skill_spec.md +++ b/packages/router-plugin/skills/_artifacts/skill_spec.md @@ -12,14 +12,13 @@ Bundler plugin for route generation and automatic code splitting. Supports Vite, | Skill | Type | Domain | What it covers | Failure modes | | ------------- | ---- | ------------------- | -------------------------------------------------------------- | ------------- | -| router-plugin | core | bundler-integration | Vite/Webpack/Rspack/esbuild plugins, route gen, code splitting | 3 | +| router-plugin | core | bundler-integration | Vite/Webpack/Rspack/esbuild plugins, route gen, code splitting | 2 | ## Failure Mode Inventory -### router-plugin (3 failure modes) +### router-plugin (2 failure modes) -| # | Mistake | Priority | Source | -| --- | ---------------------------------------------------- | -------- | ----------------- | -| 1 | Using wrong plugin export for bundler | HIGH | source/docs | -| 2 | Misconfiguring routesDirectory or generatedRouteTree | MEDIUM | source/docs | -| 3 | Editing routeTree.gen.ts instead of regenerating | HIGH | consistency audit | +| # | Mistake | Priority | Source | +| --- | ---------------------------------------------------- | -------- | ----------- | +| 1 | Using wrong plugin export for bundler | HIGH | source/docs | +| 2 | Misconfiguring routesDirectory or generatedRouteTree | MEDIUM | source/docs | diff --git a/packages/router-plugin/skills/_artifacts/skill_tree.yaml b/packages/router-plugin/skills/_artifacts/skill_tree.yaml index a313cc8a4e..eccd302d0f 100644 --- a/packages/router-plugin/skills/_artifacts/skill_tree.yaml +++ b/packages/router-plugin/skills/_artifacts/skill_tree.yaml @@ -1,6 +1,6 @@ library: name: '@tanstack/router-plugin' - version: '1.168.23' + version: '1.166.2' repository: 'https://github.com/TanStack/router' description: >- Bundler plugin for route generation and automatic code splitting. diff --git a/packages/router-plugin/skills/router-plugin/SKILL.md b/packages/router-plugin/skills/router-plugin/SKILL.md index 5353b7e8c0..3196bbc4a6 100644 --- a/packages/router-plugin/skills/router-plugin/SKILL.md +++ b/packages/router-plugin/skills/router-plugin/SKILL.md @@ -5,10 +5,9 @@ description: >- code splitting. Supports Vite, Webpack, Rspack, and esbuild. Configures autoCodeSplitting, routesDirectory, target framework, and code split groupings. -metadata: - type: core - library: tanstack-router - library_version: '1.168.23' +type: core +library: tanstack-router +library_version: '1.166.2' sources: - TanStack/router:packages/router-plugin/src - TanStack/router:docs/router/routing/file-based-routing.md @@ -91,23 +90,23 @@ esbuild.build({ plugins: [ tanstackRouter({ target: 'react', + autoCodeSplitting: true, }), ], }) ``` -> Automatic code splitting is not available with esbuild: the plugin throws when `autoCodeSplitting` is `true`. Use manual code splitting (`.lazy.tsx` files) or another bundler to split routes. - ## Configuration Options ### Core Options -| Option | Type | Default | Description | -| -------------------- | ----------------------------- | -------------------------- | -------------------------------- | -| `target` | `'react' \| 'solid' \| 'vue'` | `'react'` | Target framework | -| `routesDirectory` | `string` | `'./src/routes'` | Directory containing route files | -| `generatedRouteTree` | `string` | `'./src/routeTree.gen.ts'` | Path for generated route tree | -| `autoCodeSplitting` | `boolean` | `undefined` | Enable automatic code splitting | +| Option | Type | Default | Description | +| ----------------------- | ----------------------------- | -------------------------- | ------------------------------------------ | +| `target` | `'react' \| 'solid' \| 'vue'` | `'react'` | Target framework | +| `routesDirectory` | `string` | `'./src/routes'` | Directory containing route files | +| `generatedRouteTree` | `string` | `'./src/routeTree.gen.ts'` | Path for generated route tree | +| `autoCodeSplitting` | `boolean` | `undefined` | Enable automatic code splitting | +| `enableRouteGeneration` | `boolean` | `true` | Set to `false` to disable route generation | ### File Convention Options @@ -143,14 +142,15 @@ tanstackRouter({ ### Output Options -| Option | Type | Default | Description | -| --------------------------- | ---------------------- | ---------- | -------------------------------- | -| `quoteStyle` | `'single' \| 'double'` | `'single'` | Quote style in generated code | -| `semicolons` | `boolean` | `false` | Use semicolons in generated code | -| `disableTypes` | `boolean` | `false` | Disable TypeScript types | -| `disableLogging` | `boolean` | `false` | Suppress plugin logs | -| `addExtensions` | `boolean \| string` | `false` | Add file extensions to imports | -| `enableRouteTreeFormatting` | `boolean` | `true` | Format generated route tree | +| Option | Type | Default | Description | +| --------------------------- | ---------------------- | ----------- | -------------------------------------------- | +| `quoteStyle` | `'single' \| 'double'` | `'single'` | Quote style in generated code | +| `semicolons` | `boolean` | `false` | Use semicolons in generated code | +| `disableTypes` | `boolean` | `false` | Disable TypeScript types | +| `disableLogging` | `boolean` | `false` | Suppress plugin logs | +| `addExtensions` | `boolean \| string` | `false` | Add file extensions to imports | +| `enableRouteTreeFormatting` | `boolean` | `true` | Format generated route tree | +| `verboseFileRoutes` | `boolean` | `undefined` | When `false`, auto-imports `createFileRoute` | ### Virtual Route Config @@ -165,23 +165,12 @@ tanstackRouter({ ## How It Works -The composed plugin assembles up to 3 sub-plugins: +The composed plugin assembles up to 4 sub-plugins: 1. **Route Generator** (always) — Watches route files and generates `routeTree.gen.ts` 2. **Code Splitter** (when `autoCodeSplitting: true`) — Splits route files into lazy-loaded chunks using virtual modules -3. **HMR** (dev mode, when code splitter is off) — Hot-reloads route changes without full refresh - -## Route Refactor Workflow - -When moving, renaming, adding, or deleting file routes: - -1. Change the source files under `routesDirectory`. Keep the exported route identifier named `Route`. -2. Let the bundler plugin regenerate the tree, or run `pnpm exec tsr generate` when the project uses the CLI. -3. Inspect the generated diff for the expected route IDs, parents, paths, and imports. Never repair `routeTree.gen.ts` by hand. -4. Update links, redirects, `from` narrowing, params, preload calls, and tests that reference the old route. -5. Run route-generation tests, type tests, and a production build. A passing editor typecheck does not prove the plugin generated or split the new route correctly. - -Commit `routeTree.gen.ts`; it is generated source used by the application at runtime. +3. **Auto-Import** (when `verboseFileRoutes: false`) — Auto-injects `createFileRoute` imports +4. **HMR** (dev mode, when code splitter is off) — Hot-reloads route changes without full refresh ## Individual Plugin Exports @@ -192,6 +181,7 @@ import { tanstackRouter, // Composed (default) tanstackRouterGenerator, // Generator only tanStackRouterCodeSplitter, // Code splitter only + tanstackRouterAutoImport, // Auto-import only } from '@tanstack/router-plugin/vite' ``` @@ -240,11 +230,7 @@ function AboutPage() { } ``` -### 4. HIGH: Editing the generated route tree - -Changes to `routeTree.gen.ts` are overwritten and can leave source routes, generated types, and runtime routing out of sync. Fix route filenames or plugin configuration, regenerate, and verify the generated diff instead. - ## Cross-References -- `@tanstack/router-core#router-core/code-splitting` — manual code splitting concepts -- `@tanstack/virtual-file-routes#virtual-file-routes` — programmatic route trees +- [router-core/code-splitting](../../../router-core/skills/router-core/code-splitting/SKILL.md) — manual code splitting concepts +- [virtual-file-routes](../../../virtual-file-routes/skills/virtual-file-routes/SKILL.md) — programmatic route trees diff --git a/packages/router-plugin/src/context.ts b/packages/router-plugin/src/context.ts deleted file mode 100644 index fdf97fe94d..0000000000 --- a/packages/router-plugin/src/context.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { createRouterPluginContext } from './core/router-plugin-context' -export type { RouterPluginContext } from './core/router-plugin-context' diff --git a/packages/router-plugin/src/core/code-splitter/compilers.ts b/packages/router-plugin/src/core/code-splitter/compilers.ts index 0cd783a58a..5d5053b12f 100644 --- a/packages/router-plugin/src/core/code-splitter/compilers.ts +++ b/packages/router-plugin/src/core/code-splitter/compilers.ts @@ -2,55 +2,25 @@ import * as t from '@babel/types' import * as babel from '@babel/core' import * as template from '@babel/template' import { - buildDeclarationMap, - buildDependencyGraph, - collectIdentifiersFromPattern, - collectLocalBindingsFromStatement, - collectModuleLevelRefsFromNode, - createIdentifier, deadCodeElimination, - expandDestructuredDeclarations, - expandSharedDestructuredDeclarators, - expandTransitively, findReferencedIdentifiers, generateFromAst, parseAst, - removeBindingsTransitivelyDependingOn, - retainModuleLevelDeclarations, - stripUnreferencedTopLevelExpressionStatements, - unwrapExportedDeclarations, } from '@tanstack/router-utils' import { tsrShared, tsrSplit } from '../constants' -import { createRouteHmrStatement } from '../hmr' +import { createRouteHmrStatement } from '../route-hmr-statement' import { getObjectPropertyKeyName } from '../utils' +import { createIdentifier } from './path-ids' import { getFrameworkOptions } from './framework-options' import type { - CodeSplitCompilerPlugin, CompileCodeSplitReferenceRouteOptions, + ReferenceRouteCompilerPlugin, } from './plugins' import type { GeneratorResult, ParseAstOptions } from '@tanstack/router-utils' import type { CodeSplitGroupings, SplitRouteIdentNodes } from '../constants' +import type { Config, DeletableNodes } from '../config' import type { SplitNodeMeta } from './types' -export { - buildDeclarationMap, - buildDependencyGraph, - collectIdentifiersFromNode, - collectLocalBindingsFromStatement, - collectModuleLevelRefsFromNode, - expandDestructuredDeclarations, - expandSharedDestructuredDeclarators, - expandTransitively, - removeBindingsTransitivelyDependingOn, -} from '@tanstack/router-utils' - -export function removeBindingsDependingOnRoute( - bindings: Set<string>, - dependencyGraph: Map<string, Set<string>>, -) { - removeBindingsTransitivelyDependingOn(bindings, dependencyGraph, ['Route']) -} - const SPLIT_NODES_CONFIG = new Map<SplitRouteIdentNodes, SplitNodeMeta>([ [ 'loader', @@ -139,6 +109,124 @@ const allCreateRouteFns = [ ...unsplittableCreateRouteFns, ] +/** + * Recursively walk an AST node and collect referenced identifier-like names. + * Much cheaper than babel.traverse — no path/scope overhead. + * + * Notes: + * - Uses @babel/types `isReferenced` to avoid collecting non-references like + * object keys, member expression properties, or binding identifiers. + * - Also handles JSX identifiers for component references. + */ +export function collectIdentifiersFromNode(node: t.Node): Set<string> { + const ids = new Set<string>() + + ;(function walk( + n: t.Node | null | undefined, + parent?: t.Node, + grandparent?: t.Node, + parentKey?: string, + ) { + if (!n) return + + if (t.isIdentifier(n)) { + // When we don't have parent info (node passed in isolation), treat as referenced. + if (!parent || t.isReferenced(n, parent, grandparent)) { + ids.add(n.name) + } + return + } + + if (t.isJSXIdentifier(n)) { + // Skip attribute names: <div data-testid="x" /> + if (parent && t.isJSXAttribute(parent) && parentKey === 'name') { + return + } + + // Skip member properties: <Foo.Bar /> should count Foo, not Bar + if ( + parent && + t.isJSXMemberExpression(parent) && + parentKey === 'property' + ) { + return + } + + // Intrinsic elements (lowercase) are not identifiers + const first = n.name[0] + if (first && first === first.toLowerCase()) { + return + } + + ids.add(n.name) + return + } + + for (const key of t.VISITOR_KEYS[n.type] || []) { + const child = (n as any)[key] + if (Array.isArray(child)) { + for (const c of child) { + if (c && typeof c.type === 'string') { + walk(c, n, parent, key) + } + } + } else if (child && typeof child.type === 'string') { + walk(child, n, parent, key) + } + } + })(node) + + return ids +} + +/** + * Build a map from binding name → declaration AST node for all + * locally-declared module-level bindings. Built once, O(1) lookup. + */ +export function buildDeclarationMap(ast: t.File): Map<string, t.Node> { + const map = new Map<string, t.Node>() + for (const stmt of ast.program.body) { + const decl = + t.isExportNamedDeclaration(stmt) && stmt.declaration + ? stmt.declaration + : stmt + + if (t.isVariableDeclaration(decl)) { + for (const declarator of decl.declarations) { + for (const name of collectIdentifiersFromPattern(declarator.id)) { + map.set(name, declarator) + } + } + } else if (t.isFunctionDeclaration(decl) && decl.id) { + map.set(decl.id.name, decl) + } else if (t.isClassDeclaration(decl) && decl.id) { + map.set(decl.id.name, decl) + } + } + return map +} + +/** + * Build a dependency graph: for each local binding, the set of other local + * bindings its declaration references. Built once via simple node walking. + */ +export function buildDependencyGraph( + declMap: Map<string, t.Node>, + localBindings: Set<string>, +): Map<string, Set<string>> { + const graph = new Map<string, Set<string>>() + for (const [name, declNode] of declMap) { + if (!localBindings.has(name)) continue + const allIds = collectIdentifiersFromNode(declNode) + const deps = new Set<string>() + for (const id of allIds) { + if (id !== name && localBindings.has(id)) deps.add(id) + } + graph.set(name, deps) + } + return graph +} + /** * Computes module-level bindings that are shared between split and non-split * route properties. These bindings need to be extracted into a shared virtual @@ -150,7 +238,6 @@ const allCreateRouteFns = [ */ export function computeSharedBindings(opts: { code: string - filename?: string codeSplitGroupings: CodeSplitGroupings }): Set<string> { const ast = parseAst(opts) @@ -294,11 +381,199 @@ export function computeSharedBindings(opts: { // Remove shared bindings that transitively depend on `Route`. // The Route singleton must stay in the reference file; extracting a // binding that references it would duplicate Route in the shared module. - removeBindingsTransitivelyDependingOn(shared, fullDepGraph, ['Route']) + removeBindingsDependingOnRoute(shared, fullDepGraph) return shared } +/** + * If bindings from the same destructured declarator are referenced by + * different groups, mark all bindings from that declarator as shared. + */ +export function expandSharedDestructuredDeclarators( + ast: t.File, + refsByGroup: Map<string, Set<number>>, + shared: Set<string>, +) { + for (const stmt of ast.program.body) { + const decl = + t.isExportNamedDeclaration(stmt) && stmt.declaration + ? stmt.declaration + : stmt + + if (!t.isVariableDeclaration(decl)) continue + + for (const declarator of decl.declarations) { + if (!t.isObjectPattern(declarator.id) && !t.isArrayPattern(declarator.id)) + continue + + const names = collectIdentifiersFromPattern(declarator.id) + + const usedGroups = new Set<number>() + for (const name of names) { + const groups = refsByGroup.get(name) + if (!groups) continue + for (const g of groups) usedGroups.add(g) + } + + if (usedGroups.size >= 2) { + for (const name of names) { + shared.add(name) + } + } + } + } +} + +/** + * Collect locally-declared module-level binding names from a statement. + * Pure node inspection, no traversal. + */ +export function collectLocalBindingsFromStatement( + node: t.Statement | t.ModuleDeclaration, + bindings: Set<string>, +) { + const decl = + t.isExportNamedDeclaration(node) && node.declaration + ? node.declaration + : node + + if (t.isVariableDeclaration(decl)) { + for (const declarator of decl.declarations) { + for (const name of collectIdentifiersFromPattern(declarator.id)) { + bindings.add(name) + } + } + } else if (t.isFunctionDeclaration(decl) && decl.id) { + bindings.add(decl.id.name) + } else if (t.isClassDeclaration(decl) && decl.id) { + bindings.add(decl.id.name) + } +} + +/** + * Collect direct module-level binding names referenced from a given AST node. + * Uses a simple recursive walk instead of babel.traverse. + */ +export function collectModuleLevelRefsFromNode( + node: t.Node, + localModuleLevelBindings: Set<string>, +): Set<string> { + const allIds = collectIdentifiersFromNode(node) + const refs = new Set<string>() + for (const name of allIds) { + if (localModuleLevelBindings.has(name)) refs.add(name) + } + return refs +} + +/** + * Expand the shared set transitively using a prebuilt dependency graph. + * No AST traversals — pure graph BFS. + */ +export function expandTransitively( + shared: Set<string>, + depGraph: Map<string, Set<string>>, +) { + const queue = [...shared] + const visited = new Set<string>() + + while (queue.length > 0) { + const name = queue.pop()! + if (visited.has(name)) continue + visited.add(name) + + const deps = depGraph.get(name) + if (!deps) continue + + for (const dep of deps) { + if (!shared.has(dep)) { + shared.add(dep) + queue.push(dep) + } + } + } +} + +/** + * Remove any bindings from `shared` that transitively depend on `Route`. + * The Route singleton must remain in the reference file; if a shared binding + * references it (directly or transitively), extracting that binding would + * duplicate Route in the shared module. + * + * Uses `depGraph` which must include `Route` as a node so the dependency + * chain is visible. + */ +export function removeBindingsDependingOnRoute( + shared: Set<string>, + depGraph: Map<string, Set<string>>, +) { + const reverseGraph = new Map<string, Set<string>>() + for (const [name, deps] of depGraph) { + for (const dep of deps) { + let parents = reverseGraph.get(dep) + if (!parents) { + parents = new Set<string>() + reverseGraph.set(dep, parents) + } + parents.add(name) + } + } + + // Walk backwards from Route to find all bindings that can reach it. + const visited = new Set<string>() + const queue = ['Route'] + while (queue.length > 0) { + const cur = queue.pop()! + if (visited.has(cur)) continue + visited.add(cur) + + const parents = reverseGraph.get(cur) + if (!parents) continue + for (const parent of parents) { + if (!visited.has(parent)) queue.push(parent) + } + } + + for (const name of [...shared]) { + if (visited.has(name)) { + shared.delete(name) + } + } +} + +/** + * If any binding from a destructured declaration is shared, + * ensure all bindings from that same declaration are also shared. + * Pure node inspection of program.body, no traversal. + */ +export function expandDestructuredDeclarations( + ast: t.File, + shared: Set<string>, +) { + for (const stmt of ast.program.body) { + const decl = + t.isExportNamedDeclaration(stmt) && stmt.declaration + ? stmt.declaration + : stmt + + if (!t.isVariableDeclaration(decl)) continue + + for (const declarator of decl.declarations) { + if (!t.isObjectPattern(declarator.id) && !t.isArrayPattern(declarator.id)) + continue + + const names = collectIdentifiersFromPattern(declarator.id) + const hasShared = names.some((n) => shared.has(n)) + if (hasShared) { + for (const n of names) { + shared.add(n) + } + } + } + } +} + /** * Find which shared bindings are user-exported in the original source. * These need to be re-exported from the shared module. @@ -362,11 +637,16 @@ function removeSharedDeclarations(ast: t.File, sharedBindings: Set<string>) { } export function compileCodeSplitReferenceRoute( - opts: ParseAstOptions & - CompileCodeSplitReferenceRouteOptions & { - isProduction?: boolean - compilerPlugins?: Array<CodeSplitCompilerPlugin> - }, + opts: ParseAstOptions & { + codeSplitGroupings: CodeSplitGroupings + deleteNodes?: Set<DeletableNodes> + targetFramework: Config['target'] + filename: string + id: string + addHmr?: boolean + sharedBindings?: Set<string> + compilerPlugins?: Array<ReferenceRouteCompilerPlugin> + }, ): GeneratorResult | null { const ast = parseAst(opts) @@ -453,11 +733,7 @@ export function compileCodeSplitReferenceRoute( programPath.pushContainer( 'body', - createRouteHmrStatement(stableRouteOptionKeys, { - hmrStyle: opts.hmrStyle ?? 'vite', - targetFramework: opts.targetFramework, - routeId: opts.hmrRouteId, - }), + createRouteHmrStatement(stableRouteOptionKeys), ) modified = true hmrAdded = true @@ -466,21 +742,6 @@ export function compileCodeSplitReferenceRoute( if (t.isObjectExpression(routeOptions)) { const insertionPath = path.getStatementParent() ?? path - opts.compilerPlugins?.forEach((plugin) => { - const pluginResult = plugin.onRouteOptions?.({ - programPath, - callExpressionPath: path, - insertionPath, - routeOptions, - createRouteFn, - opts: opts as CompileCodeSplitReferenceRouteOptions, - }) - - if (pluginResult?.modified) { - modified = true - } - }) - if (opts.deleteNodes && opts.deleteNodes.size > 0) { routeOptions.properties = routeOptions.properties.filter( (prop) => { @@ -643,7 +904,6 @@ export function compileCodeSplitReferenceRoute( splitNodeMeta, lazyRouteComponentIdent: LAZY_ROUTE_COMPONENT_IDENT, - opts, }, ) @@ -848,9 +1108,8 @@ export function compileCodeSplitReferenceRoute( ) console.warn(warningMessage) - // Development builds log it in the page too. The bundler's mode decides, - // not the build process's NODE_ENV, which webpack never sets. - if (!opts.isProduction) { + // append this warning to the file using a template + if (process.env.NODE_ENV !== 'production') { const warningTemplate = template.statement( `console.warn(${JSON.stringify(warningMessage)})`, )() @@ -881,7 +1140,6 @@ export function compileCodeSplitVirtualRoute( splitTargets: Array<SplitRouteIdentNodes> filename: string sharedBindings?: Set<string> - compilerPlugins?: Array<CodeSplitCompilerPlugin> }, ): GeneratorResult { const ast = parseAst(opts) @@ -1018,14 +1276,6 @@ export function compileCodeSplitVirtualRoute( // Add the node to the program if (splitNode) { - for (const plugin of opts.compilerPlugins ?? []) { - plugin.onVirtualRouteSplitNode?.({ - programPath, - splitNode, - splitNodeMeta: splitMeta, - }) - } - if (t.isFunctionDeclaration(splitNode)) { // an anonymous function declaration should only happen for `export default function() {...}` // so we should never get here @@ -1034,7 +1284,6 @@ export function compileCodeSplitVirtualRoute( `Function declaration for "${SPLIT_TYPE}" must have an identifier.`, ) } - splitMeta.shouldRemoveNode = false splitMeta.localExporterIdent = splitNode.id.name } else if ( @@ -1046,7 +1295,7 @@ export function compileCodeSplitVirtualRoute( t.variableDeclaration('const', [ t.variableDeclarator( t.identifier(splitMeta.localExporterIdent), - splitNode, + splitNode as any, ), ]), ) @@ -1277,7 +1526,22 @@ export function compileCodeSplitVirtualRoute( }) deadCodeElimination(ast, refIdents) - stripUnreferencedTopLevelExpressionStatements(ast) + + // Strip top-level expression statements that reference no locally-bound names. + // DCE only removes unused declarations; bare side-effect statements like + // `console.log(...)` survive even when the virtual file has no exports. + { + const locallyBound = new Set<string>() + for (const stmt of ast.program.body) { + collectLocalBindingsFromStatement(stmt, locallyBound) + } + ast.program.body = ast.program.body.filter((stmt) => { + if (!t.isExpressionStatement(stmt)) return true + const refs = collectIdentifiersFromNode(stmt) + // Keep if it references at least one locally-bound identifier + return [...refs].some((name) => locallyBound.has(name)) + }) + } // If the body is empty after DCE, strip directive prologues too. // A file containing only `'use client'` with no real code is useless. @@ -1287,8 +1551,7 @@ export function compileCodeSplitVirtualRoute( const result = generateFromAst(ast, { sourceMaps: true, - // Name the route file, not this module's `?tsr-*` id. - sourceFileName: removeSplitSearchParamFromFilename(opts.filename), + sourceFileName: opts.filename, filename: opts.filename, }) @@ -1333,8 +1596,49 @@ export function compileCodeSplitSharedRoute( keepBindings.delete('Route') expandTransitively(keepBindings, depGraph) - retainModuleLevelDeclarations(ast, keepBindings) - unwrapExportedDeclarations(ast) + // Remove all statements except: + // - Import declarations (needed for deps; DCE will clean unused ones) + // - Declarations of bindings in keepBindings + ast.program.body = ast.program.body.filter((stmt) => { + // Always keep imports — DCE will remove unused ones + if (t.isImportDeclaration(stmt)) return true + + const decl = + t.isExportNamedDeclaration(stmt) && stmt.declaration + ? stmt.declaration + : stmt + + if (t.isVariableDeclaration(decl)) { + // Keep declarators where at least one binding is in keepBindings + decl.declarations = decl.declarations.filter((declarator) => { + const names = collectIdentifiersFromPattern(declarator.id) + return names.some((n) => keepBindings.has(n)) + }) + if (decl.declarations.length === 0) return false + + // Strip the `export` wrapper — shared module controls its own exports + if (t.isExportNamedDeclaration(stmt) && stmt.declaration) { + return true // keep for now, we'll convert below + } + return true + } else if (t.isFunctionDeclaration(decl) && decl.id) { + return keepBindings.has(decl.id.name) + } else if (t.isClassDeclaration(decl) && decl.id) { + return keepBindings.has(decl.id.name) + } + + // Remove everything else (expression statements, other exports, etc.) + return false + }) + + // Convert `export const/function/class` to plain declarations + // (we'll add our own export statement at the end) + ast.program.body = ast.program.body.map((stmt) => { + if (t.isExportNamedDeclaration(stmt) && stmt.declaration) { + return stmt.declaration + } + return stmt + }) // Export all shared bindings (sorted for deterministic output) const exportNames = [...opts.sharedBindings].sort((a, b) => @@ -1379,8 +1683,7 @@ export function compileCodeSplitSharedRoute( const result = generateFromAst(ast, { sourceMaps: true, - // Name the route file, not this module's `?tsr-*` id. - sourceFileName: removeSplitSearchParamFromFilename(opts.filename), + sourceFileName: opts.filename, filename: opts.filename, }) @@ -1535,6 +1838,50 @@ function getImportSpecifierAndPathFromLocalName( return { specifier, path } } +/** + * Recursively collects all identifier names from a destructuring pattern + * (ObjectPattern, ArrayPattern, AssignmentPattern, RestElement). + */ +function collectIdentifiersFromPattern( + node: t.LVal | t.Node | null | undefined, +): Array<string> { + if (!node) { + return [] + } + + if (t.isIdentifier(node)) { + return [node.name] + } + + if (t.isAssignmentPattern(node)) { + return collectIdentifiersFromPattern(node.left) + } + + if (t.isRestElement(node)) { + return collectIdentifiersFromPattern(node.argument) + } + + if (t.isObjectPattern(node)) { + return node.properties.flatMap((prop) => { + if (t.isObjectProperty(prop)) { + return collectIdentifiersFromPattern(prop.value as t.LVal) + } + if (t.isRestElement(prop)) { + return collectIdentifiersFromPattern(prop.argument) + } + return [] + }) + } + + if (t.isArrayPattern(node)) { + return node.elements.flatMap((element) => + collectIdentifiersFromPattern(element), + ) + } + + return [] +} + // Reusable function to get literal value or resolve variable to literal function resolveIdentifier(path: any, node: any): t.Node | undefined { if (t.isIdentifier(node)) { diff --git a/packages/router-utils/src/path-ids.ts b/packages/router-plugin/src/core/code-splitter/path-ids.ts similarity index 100% rename from packages/router-utils/src/path-ids.ts rename to packages/router-plugin/src/core/code-splitter/path-ids.ts diff --git a/packages/router-plugin/src/core/code-splitter/plugins.ts b/packages/router-plugin/src/core/code-splitter/plugins.ts index 94444c1aec..841b20aea8 100644 --- a/packages/router-plugin/src/core/code-splitter/plugins.ts +++ b/packages/router-plugin/src/core/code-splitter/plugins.ts @@ -1,7 +1,6 @@ import type babel from '@babel/core' import type * as t from '@babel/types' import type { Config, DeletableNodes } from '../config' -import type { HmrStyle } from '../hmr' import type { CodeSplitGroupings } from '../constants' import type { SplitNodeMeta } from './types' @@ -12,8 +11,6 @@ export type CompileCodeSplitReferenceRouteOptions = { filename: string id: string addHmr?: boolean - hmrStyle?: HmrStyle - hmrRouteId?: string sharedBindings?: Set<string> } @@ -34,25 +31,15 @@ export type ReferenceRouteSplitPropertyCompilerPluginContext = { prop: t.ObjectProperty splitNodeMeta: SplitNodeMeta lazyRouteComponentIdent: string - opts: CompileCodeSplitReferenceRouteOptions } export type ReferenceRouteCompilerPluginResult = { modified?: boolean } -export type VirtualRouteSplitNodeCompilerPluginContext = { - programPath: babel.NodePath<t.Program> - splitNode: t.Node - splitNodeMeta: SplitNodeMeta -} - -export type CodeSplitCompilerPlugin = { +export type ReferenceRouteCompilerPlugin = { name: string getStableRouteOptionKeys?: () => Array<string> - onRouteOptions?: ( - ctx: ReferenceRouteCompilerPluginContext, - ) => void | ReferenceRouteCompilerPluginResult onAddHmr?: ( ctx: ReferenceRouteCompilerPluginContext, ) => void | ReferenceRouteCompilerPluginResult @@ -62,9 +49,4 @@ export type CodeSplitCompilerPlugin = { onSplitRouteProperty?: ( ctx: ReferenceRouteSplitPropertyCompilerPluginContext, ) => void | t.Expression - onVirtualRouteSplitNode?: ( - ctx: VirtualRouteSplitNodeCompilerPluginContext, - ) => void } - -export type ReferenceRouteCompilerPlugin = CodeSplitCompilerPlugin diff --git a/packages/router-plugin/src/core/code-splitter/plugins/framework-plugins.ts b/packages/router-plugin/src/core/code-splitter/plugins/framework-plugins.ts index cf4b150807..1ea299302f 100644 --- a/packages/router-plugin/src/core/code-splitter/plugins/framework-plugins.ts +++ b/packages/router-plugin/src/core/code-splitter/plugins/framework-plugins.ts @@ -1,24 +1,23 @@ import { createReactRefreshIgnoredRouteExportsPlugin } from './react-refresh-ignored-route-exports' import { createReactRefreshRouteComponentsPlugin } from './react-refresh-route-components' import { createReactStableHmrSplitRouteComponentsPlugin } from './react-stable-hmr-split-route-components' -import type { CodeSplitCompilerPlugin } from '../plugins' +import type { ReferenceRouteCompilerPlugin } from '../plugins' import type { Config } from '../../config' -import type { HmrStyle } from '../../hmr' -export function getFrameworkHmrCompilerPlugins(opts: { +export function getReferenceRouteCompilerPlugins(opts: { targetFramework: Config['target'] - hmrStyle?: HmrStyle -}): Array<CodeSplitCompilerPlugin> | undefined { + addHmr?: boolean +}): Array<ReferenceRouteCompilerPlugin> | undefined { switch (opts.targetFramework) { case 'react': { - const hmrStyle = opts.hmrStyle ?? 'vite' - return [ - ...(hmrStyle === 'vite' - ? [createReactRefreshIgnoredRouteExportsPlugin()] - : []), - createReactRefreshRouteComponentsPlugin(), - createReactStableHmrSplitRouteComponentsPlugin({ hmrStyle }), - ] + if (opts.addHmr) { + return [ + createReactRefreshIgnoredRouteExportsPlugin(), + createReactRefreshRouteComponentsPlugin(), + createReactStableHmrSplitRouteComponentsPlugin(), + ] + } + return undefined } default: return undefined diff --git a/packages/router-plugin/src/core/code-splitter/plugins/react-refresh-ignored-route-exports.ts b/packages/router-plugin/src/core/code-splitter/plugins/react-refresh-ignored-route-exports.ts index f951d863b3..1bcfc00bbc 100644 --- a/packages/router-plugin/src/core/code-splitter/plugins/react-refresh-ignored-route-exports.ts +++ b/packages/router-plugin/src/core/code-splitter/plugins/react-refresh-ignored-route-exports.ts @@ -3,10 +3,9 @@ import * as t from '@babel/types' import { getUniqueProgramIdentifier } from '../../utils' import type { ReferenceRouteCompilerPlugin } from '../plugins' -const buildReactRefreshIgnoredRouteExportsStatements = template.statements( +const buildReactRefreshIgnoredRouteExportsStatement = template.statement( ` if (import.meta.hot && typeof window !== 'undefined') { - import.meta.hot.data ??= {} const tsrReactRefresh = window.__TSR_REACT_REFRESH__ ??= (() => { const ignoredExportsById = new Map() const previousGetIgnoredExports = window.__getReactRefreshIgnoredExports @@ -50,7 +49,7 @@ export function createReactRefreshIgnoredRouteExportsPlugin(): ReferenceRouteCom ctx.programPath.pushContainer( 'body', - buildReactRefreshIgnoredRouteExportsStatements({ + buildReactRefreshIgnoredRouteExportsStatement({ moduleId: t.stringLiteral(ctx.opts.id), }), ) diff --git a/packages/router-plugin/src/core/code-splitter/plugins/react-refresh-route-components.ts b/packages/router-plugin/src/core/code-splitter/plugins/react-refresh-route-components.ts index 44041671e0..f7c4bca338 100644 --- a/packages/router-plugin/src/core/code-splitter/plugins/react-refresh-route-components.ts +++ b/packages/router-plugin/src/core/code-splitter/plugins/react-refresh-route-components.ts @@ -13,74 +13,29 @@ const REACT_REFRESH_ROUTE_COMPONENT_IDENTS = new Set([ 'notFoundComponent', ]) -type RouteComponentContext = { +function hoistInlineRouteComponents(ctx: { programPath: Parameters<typeof getUniqueProgramIdentifier>[0] insertionPath: { insertBefore: (nodes: Array<t.VariableDeclaration>) => void } routeOptions: t.ObjectExpression -} - -function isReactComponentName(name: string) { - const firstCharacter = name[0] - - return ( - firstCharacter !== undefined && - firstCharacter >= 'A' && - firstCharacter <= 'Z' - ) -} - -function getRouteComponentKey(prop: t.ObjectProperty) { - const key = getObjectPropertyKeyName(prop) - - return key && REACT_REFRESH_ROUTE_COMPONENT_IDENTS.has(key) ? key : undefined -} - -function prepareRouteComponentsForReactRefresh(ctx: RouteComponentContext) { +}) { const hoistedDeclarations: Array<t.VariableDeclaration> = [] - let modified = false - for (const prop of ctx.routeOptions.properties) { + ctx.routeOptions.properties.forEach((prop) => { if (!t.isObjectProperty(prop)) { - continue + return } - const key = getRouteComponentKey(prop) + const key = getObjectPropertyKeyName(prop) - if (!key) { - continue - } - - if (t.isIdentifier(prop.value)) { - if (isReactComponentName(prop.value.name)) { - continue - } - - const bindingNode = ctx.programPath.scope.getBinding(prop.value.name) - ?.path.node - const isLocalComponentBinding = - t.isFunctionDeclaration(bindingNode) || - t.isClassDeclaration(bindingNode) || - t.isVariableDeclarator(bindingNode) - - if (!isLocalComponentBinding) { - continue - } - - const componentIdentifier = getUniqueProgramIdentifier( - ctx.programPath, - `TSR${key[0]!.toUpperCase()}${key.slice(1)}`, - ) - - ctx.programPath.scope.rename(prop.value.name, componentIdentifier.name) - modified = true - continue + if (!key || !REACT_REFRESH_ROUTE_COMPONENT_IDENTS.has(key)) { + return } if ( !t.isArrowFunctionExpression(prop.value) && !t.isFunctionExpression(prop.value) ) { - continue + return } const hoistedIdentifier = getUniqueProgramIdentifier( @@ -95,14 +50,14 @@ function prepareRouteComponentsForReactRefresh(ctx: RouteComponentContext) { ) prop.value = t.cloneNode(hoistedIdentifier) - modified = true + }) + + if (hoistedDeclarations.length === 0) { + return false } - if (hoistedDeclarations.length > 0) { - ctx.insertionPath.insertBefore(hoistedDeclarations) - } - - return modified + ctx.insertionPath.insertBefore(hoistedDeclarations) + return true } export function createReactRefreshRouteComponentsPlugin(): ReferenceRouteCompilerPlugin { @@ -111,32 +66,27 @@ export function createReactRefreshRouteComponentsPlugin(): ReferenceRouteCompile getStableRouteOptionKeys() { return [...REACT_REFRESH_ROUTE_COMPONENT_IDENTS] }, - onAddHmr(ctx) { - if (prepareRouteComponentsForReactRefresh(ctx)) { + onUnsplittableRoute(ctx) { + if (!ctx.opts.addHmr) { + return + } + + if (hoistInlineRouteComponents(ctx)) { return { modified: true } } return }, - onVirtualRouteSplitNode(ctx) { - if ( - ctx.splitNodeMeta.splitStrategy !== 'lazyRouteComponent' || - !t.isFunctionDeclaration(ctx.splitNode) || - !ctx.splitNode.id || - isReactComponentName(ctx.splitNode.id.name) - ) { + onAddHmr(ctx) { + if (!ctx.opts.addHmr) { return } - const componentIdentifier = getUniqueProgramIdentifier( - ctx.programPath, - ctx.splitNodeMeta.localExporterIdent, - ) + if (hoistInlineRouteComponents(ctx)) { + return { modified: true } + } - ctx.programPath.scope.rename( - ctx.splitNode.id.name, - componentIdentifier.name, - ) + return }, } } diff --git a/packages/router-plugin/src/core/code-splitter/plugins/react-stable-hmr-split-route-components.ts b/packages/router-plugin/src/core/code-splitter/plugins/react-stable-hmr-split-route-components.ts index f67a189f40..5146202ad3 100644 --- a/packages/router-plugin/src/core/code-splitter/plugins/react-stable-hmr-split-route-components.ts +++ b/packages/router-plugin/src/core/code-splitter/plugins/react-stable-hmr-split-route-components.ts @@ -1,7 +1,6 @@ import * as template from '@babel/template' import * as t from '@babel/types' import { getUniqueProgramIdentifier } from '../../utils' -import type { HmrStyle } from '../../hmr' import type { ReferenceRouteCompilerPlugin } from '../plugins' function capitalizeIdentifier(str: string) { @@ -14,13 +13,9 @@ function createHotDataKey(exportName: string) { const buildStableSplitComponentStatements = template.statements( ` - const %%stableComponentIdent%% = (() => { - const hot = %%hotExpression%% - const hotData = hot ? (hot.data ??= {}) : undefined - return hotData?.[%%hotDataKey%%] ?? %%lazyRouteComponentIdent%%(%%localImporterIdent%%, %%exporterIdent%%) - })() - if (%%hotExpression%%) { - ((%%hotExpression%%).data ??= {})[%%hotDataKey%%] = %%stableComponentIdent%% + const %%stableComponentIdent%% = import.meta.hot?.data?.[%%hotDataKey%%] ?? %%lazyRouteComponentIdent%%(%%localImporterIdent%%, %%exporterIdent%%) + if (import.meta.hot) { + import.meta.hot.data[%%hotDataKey%%] = %%stableComponentIdent%% } `, { @@ -28,15 +23,7 @@ const buildStableSplitComponentStatements = template.statements( }, ) -function hotExpressionAstFor(hmrStyle: HmrStyle): t.Expression { - return template.expression.ast( - hmrStyle === 'webpack' ? 'import.meta.webpackHot' : 'import.meta.hot', - ) -} - -export function createReactStableHmrSplitRouteComponentsPlugin(opts: { - hmrStyle: HmrStyle -}): ReferenceRouteCompilerPlugin { +export function createReactStableHmrSplitRouteComponentsPlugin(): ReferenceRouteCompilerPlugin { return { name: 'react-stable-hmr-split-route-components', onSplitRouteProperty(ctx) { @@ -55,7 +42,6 @@ export function createReactStableHmrSplitRouteComponentsPlugin(opts: { buildStableSplitComponentStatements({ stableComponentIdent, hotDataKey: t.stringLiteral(hotDataKey), - hotExpression: hotExpressionAstFor(opts.hmrStyle), lazyRouteComponentIdent: t.identifier(ctx.lazyRouteComponentIdent), localImporterIdent: t.identifier( ctx.splitNodeMeta.localImporterIdent, diff --git a/packages/router-plugin/src/core/config.ts b/packages/router-plugin/src/core/config.ts index 6c11241a01..f93166d392 100644 --- a/packages/router-plugin/src/core/config.ts +++ b/packages/router-plugin/src/core/config.ts @@ -73,11 +73,7 @@ export type CodeSplittingOptions = { } const codeSplittingOptionsSchema = z.object({ - splitBehavior: z - .custom< - CodeSplittingOptions['splitBehavior'] - >((value) => typeof value === 'function') - .optional(), + splitBehavior: z.function().optional(), defaultBehavior: splitGroupingsSchema.optional(), deleteNodes: z.array(z.string()).optional(), addHmr: z.boolean().optional().default(true), @@ -89,6 +85,7 @@ type FileRouteKeys = keyof (Parameters< export type DeletableNodes = FileRouteKeys | (string & {}) export const configSchema = generatorConfigSchema.extend({ + enableRouteGeneration: z.boolean().optional(), codeSplittingOptions: z .custom<CodeSplittingOptions>((v) => { return codeSplittingOptionsSchema.parse(v) diff --git a/packages/router-plugin/src/core/hmr/handle-route-update.ts b/packages/router-plugin/src/core/hmr/handle-route-update.ts deleted file mode 100644 index 23b51d2432..0000000000 --- a/packages/router-plugin/src/core/hmr/handle-route-update.ts +++ /dev/null @@ -1,104 +0,0 @@ -import type { AnyRoute, AnyRouter } from '@tanstack/router-core' - -type AnyRouteWithPrivateProps = AnyRoute & { - options: Record<string, unknown> - parentRoute: AnyRoute - _lazy?: Promise<void> | true - update: (options: Record<string, unknown>) => unknown - _path: string - _id: string - _fullPath: string - _to: string -} - -type AnyRouterWithPrivateState = AnyRouter & { - routesById: Record<string, AnyRoute> - buildRouteTree: () => Parameters<AnyRouter['setRoutes']>[0] - setRoutes: AnyRouter['setRoutes'] - _refreshRoute?: () => Promise<void> - _replaceRouteChunk: (route: AnyRoute, lazyFn: AnyRoute['lazyFn']) => void -} - -function handleRouteUpdate( - routeId: string, - newRoute: AnyRouteWithPrivateProps, -) { - const router = window.__TSR_ROUTER__ as AnyRouterWithPrivateState - const oldRoute = router.routesById[routeId] as - | AnyRouteWithPrivateProps - | undefined - - if (!oldRoute) { - return - } - - // Generated route-tree options are not present on the freshly imported route - // module, but they must stay on the live route before rebuilding indexes. - const generatedRouteOptionKeys = new Set(['id', 'path', 'getParentRoute']) - const generatedRouteOptions: Record<string, unknown> = {} - generatedRouteOptionKeys.forEach((key) => { - if (key in oldRoute.options) { - generatedRouteOptions[key] = oldRoute.options[key] - } - }) - - const oldHasShellComponent = 'shellComponent' in oldRoute.options - const newHasShellComponent = 'shellComponent' in newRoute.options - const preserveComponentIdentity = - oldHasShellComponent === newHasShellComponent - - // Keys whose identity must remain stable to prevent React from - // unmounting/remounting the component tree. React Fast Refresh already - // handles hot-updating the function bodies of these components — our job - // is only to update non-component route options (loader, head, etc.). - // For code-split (splittable) routes, the lazyRouteComponent wrapper is - // already cached in the bundler hot data so its identity is stable. - // For unsplittable routes (e.g. root routes), the component is a plain - // function reference that gets recreated on every module re-execution, - // so we must explicitly preserve the old reference. - // Preserve component identity so React doesn't remount. - // React Fast Refresh patches the function bodies in-place. - const componentKeys = '__TSR_COMPONENT_TYPES__' as unknown as Array<string> - if (preserveComponentIdentity) { - componentKeys.forEach((key) => { - if (key in oldRoute.options && key in newRoute.options) { - newRoute.options[key] = oldRoute.options[key] - } - }) - } - - const nextOptions = { - ...newRoute.options, - ...generatedRouteOptions, - } - - oldRoute.options = nextOptions - oldRoute.update(nextOptions) - router._replaceRouteChunk(oldRoute, newRoute.lazyFn) - - router.setRoutes(router.buildRouteTree()) - syncHotRouteExport(oldRoute) - router.resolvePathCache.clear() - void router._refreshRoute?.() - - function syncHotRouteExport(liveRoute: AnyRouteWithPrivateProps) { - // routeTree.gen.ts mutates the original module export with generated - // routing state. Mirror that state onto the fresh HMR export too, so - // aliased route imports keep working after the module is hot-reloaded. - newRoute.options = liveRoute.options - newRoute.parentRoute = liveRoute.parentRoute - newRoute._path = liveRoute._path - newRoute._id = liveRoute._id - newRoute._fullPath = liveRoute._fullPath - newRoute._to = liveRoute._to - } -} - -const handleRouteUpdateStr = handleRouteUpdate.toString() - -export function getHandleRouteUpdateCode(stableRouteOptionKeys: Array<string>) { - return handleRouteUpdateStr.replace( - /['"]__TSR_COMPONENT_TYPES__['"]/, - JSON.stringify(stableRouteOptionKeys), - ) -} diff --git a/packages/router-plugin/src/core/hmr/index.ts b/packages/router-plugin/src/core/hmr/index.ts deleted file mode 100644 index b3c8545851..0000000000 --- a/packages/router-plugin/src/core/hmr/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -export { createRouteHmrStatement } from './select-adapter' -export type { CreateRouteHmrStatementOpts, HmrStyle } from './select-adapter' -export { createViteHmrStatement } from './vite-adapter' -export { createWebpackHmrStatement } from './webpack-adapter' -export { getHandleRouteUpdateCode } from './handle-route-update' diff --git a/packages/router-plugin/src/core/hmr/select-adapter.ts b/packages/router-plugin/src/core/hmr/select-adapter.ts deleted file mode 100644 index 5ad2646970..0000000000 --- a/packages/router-plugin/src/core/hmr/select-adapter.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { createViteHmrStatement } from './vite-adapter' -import { createWebpackHmrStatement } from './webpack-adapter' -import type { Config } from '../config' -import type * as t from '@babel/types' - -/** - * The HMR runtime to emit code for: - * - `'vite'`: ESM `import.meta.hot` with Vite accept-callback semantics. - * - `'webpack'`: `import.meta.webpackHot` with webpack / Rspack `module.hot` - * re-execution semantics. - */ -export type HmrStyle = 'vite' | 'webpack' - -export type CreateRouteHmrStatementOpts = { - hmrStyle: HmrStyle - targetFramework: Config['target'] - routeId?: string -} - -/** - * Dispatches to the HMR adapter of the bundler the plugin runs in. `hmrStyle` - * comes from the bundler-specific plugin entry (e.g. `rspack.ts` → - * `'webpack'`), not from user config. - */ -export function createRouteHmrStatement( - stableRouteOptionKeys: Array<string>, - opts: CreateRouteHmrStatementOpts, -): Array<t.Statement> { - const routeId = opts.routeId === '/__root' ? '__root__' : opts.routeId - - if (opts.hmrStyle === 'webpack') { - return createWebpackHmrStatement(stableRouteOptionKeys, { - targetFramework: opts.targetFramework, - routeId, - }) - } - return createViteHmrStatement(stableRouteOptionKeys, { - routeId, - }) -} diff --git a/packages/router-plugin/src/core/hmr/vite-adapter.ts b/packages/router-plugin/src/core/hmr/vite-adapter.ts deleted file mode 100644 index 5357c45acf..0000000000 --- a/packages/router-plugin/src/core/hmr/vite-adapter.ts +++ /dev/null @@ -1,65 +0,0 @@ -import * as template from '@babel/template' -import { getHandleRouteUpdateCode } from './handle-route-update' -import type * as t from '@babel/types' - -/** - * Emits HMR accept code for Vite / native ESM HMR: `import.meta.hot.accept` - * with a callback that receives the freshly re-imported module. Vite makes the - * module a hot boundary only when the code spells `import.meta.hot.accept(` - * out, so the call must not go through an alias. - * - * `targetFramework` is currently unused — Vite's framework-specific fast-refresh - * plugins handle component body patching via their own accept boundaries — but - * we take it for API symmetry with `createWebpackHmrStatement`. - */ -export function createViteHmrStatement( - stableRouteOptionKeys: Array<string>, - opts: { - routeId?: string - } = {}, -): Array<t.Statement> { - const handleRouteUpdateCode = getHandleRouteUpdateCode(stableRouteOptionKeys) - // The replacement Route object can be uninitialized; keep a generated id as - // fallback for the existing router route we need to patch. - const routeIdFallback = - typeof opts.routeId === 'string' ? JSON.stringify(opts.routeId) : 'Route.id' - - return [ - template.statement( - ` -if (import.meta.hot) { - const hotData = import.meta.hot.data ??= {} - const handleRouteUpdate = ${handleRouteUpdateCode} - const initialRouteId = ${routeIdFallback} ?? hotData['tsr-route-id'] - if (initialRouteId) { - hotData['tsr-route-id'] = initialRouteId - } - const existingRoute = - typeof window !== 'undefined' && initialRouteId - ? window.__TSR_ROUTER__?.routesById?.[initialRouteId] - : undefined - if (initialRouteId && existingRoute && existingRoute !== Route) { - handleRouteUpdate(initialRouteId, Route) - hotData['tsr-route-update-handled'] = Route - } - import.meta.hot.accept((newModule) => { - if (Route && newModule && newModule.Route) { - const routeId = hotData['tsr-route-id'] ?? ${routeIdFallback} - if (routeId) { - hotData['tsr-route-id'] = routeId - } - if (hotData['tsr-route-update-handled'] === newModule.Route) { - delete hotData['tsr-route-update-handled'] - return - } - handleRouteUpdate(routeId, newModule.Route) - } - }) -} -`, - { - syntacticPlaceholders: true, - }, - )(), - ] -} diff --git a/packages/router-plugin/src/core/hmr/webpack-adapter.ts b/packages/router-plugin/src/core/hmr/webpack-adapter.ts deleted file mode 100644 index eaf34ccfb1..0000000000 --- a/packages/router-plugin/src/core/hmr/webpack-adapter.ts +++ /dev/null @@ -1,96 +0,0 @@ -import * as template from '@babel/template' -import { getHandleRouteUpdateCode } from './handle-route-update' -import type { Config } from '../config' -import type * as t from '@babel/types' - -/** - * Emits HMR accept code for bundlers with webpack-compatible `module.hot` - * semantics (classic webpack via `import.meta.webpackHot`, and Rspack). - * - * Unlike Vite's `hot.accept((newModule) => {...})` — where the callback receives - * the freshly re-imported module — webpack re-executes the module factory on - * accept, so our HMR logic must live at module top level and read the previous - * `routeId` out of `hot.data`. `hot.dispose` stashes it for the next run, and - * `hot.accept()` (no callback) enrolls us as a self-accepting boundary. - * - * Returns an array of statements that patches route definitions during HMR. - */ -export function createWebpackHmrStatement( - stableRouteOptionKeys: Array<string>, - opts: { - targetFramework: Config['target'] - routeId?: string - }, -): Array<t.Statement> { - const handleRouteUpdateCode = getHandleRouteUpdateCode(stableRouteOptionKeys) - const staticRouteIdLiteral = - typeof opts.routeId === 'string' - ? JSON.stringify(opts.routeId) - : 'undefined' - - // React-only: route modules aren't React Refresh "boundaries" (they export - // a non-component `Route`), so the bundler's react-refresh runtime won't - // call `performReactRefresh` for us. We kick it manually after swapping - // route options so newly-registered component bodies get patched into live - // fibers. - // - // Webpack and Rspack refresh plugins inject `__react_refresh_utils__` via - // ProvidePlugin. Use it when present instead of importing - // `react-refresh/runtime`, because Rsbuild apps may use React without the - // React plugin and therefore may not have that optional dependency installed. - // - // Use the same delayed refresh style as Rspack's React Refresh runtime. - // Route modules and their split component chunks can arrive in separate HMR - // steps under CI load; a microtask can run before the split chunk registers - // its new component family, causing the refresh to no-op or remount. - // - // For non-React frameworks we skip this entirely. - const reactRefreshCall = - opts.targetFramework === 'react' - ? ` - try { - const tsrReactRefreshUtils = - typeof __react_refresh_utils__ !== 'undefined' - ? __react_refresh_utils__ - : undefined - const tsrEnqueueUpdate = - tsrReactRefreshUtils && typeof tsrReactRefreshUtils.enqueueUpdate === 'function' - ? tsrReactRefreshUtils.enqueueUpdate - : undefined - if (tsrEnqueueUpdate) { - tsrEnqueueUpdate(() => {}) - } - } catch (_err) { /* noop */ }` - : '' - - return [ - template.statement( - ` -if (import.meta.webpackHot) { - const hot = import.meta.webpackHot - const hotData = hot.data ??= {} - const routeId = hotData['tsr-route-id'] ?? Route.id ?? (Route.isRoot ? '__root__' : ${staticRouteIdLiteral}) - if (routeId) { - hotData['tsr-route-id'] = routeId - } - const existingRoute = - typeof window !== 'undefined' && routeId - ? window.__TSR_ROUTER__?.routesById?.[routeId] - : undefined - if (routeId && existingRoute && existingRoute !== Route) { - (${handleRouteUpdateCode})(routeId, Route)${reactRefreshCall} - } - hot.dispose((data) => { - if (routeId) { - data['tsr-route-id'] = routeId - } - }) - hot.accept() -} -`, - { - syntacticPlaceholders: true, - }, - )(), - ] -} diff --git a/packages/router-plugin/src/core/route-autoimport-plugin.ts b/packages/router-plugin/src/core/route-autoimport-plugin.ts new file mode 100644 index 0000000000..742f80b343 --- /dev/null +++ b/packages/router-plugin/src/core/route-autoimport-plugin.ts @@ -0,0 +1,120 @@ +import { generateFromAst, logDiff, parseAst } from '@tanstack/router-utils' +import * as babel from '@babel/core' +import * as template from '@babel/template' +import { getConfig } from './config' +import { debug, normalizePath } from './utils' +import type { Config } from './config' +import type { UnpluginFactory } from 'unplugin' + +/** + * This plugin adds imports for createFileRoute and createLazyFileRoute to the file route. + */ +export const unpluginRouteAutoImportFactory: UnpluginFactory< + Partial<Config | (() => Config)> | undefined +> = (options = {}) => { + let ROOT: string = process.cwd() + let userConfig: Config + + function initUserConfig() { + if (typeof options === 'function') { + userConfig = options() + } else { + userConfig = getConfig(options, ROOT) + } + } + return { + name: 'tanstack-router:autoimport', + enforce: 'pre', + + transform: { + filter: { + // this is necessary for webpack / rspack to avoid matching .html files + id: /\.(m|c)?(j|t)sx?$/, + code: /createFileRoute\(|createLazyFileRoute\(/, + }, + handler(code, id) { + const normalizedId = normalizePath(id) + if (!globalThis.TSR_ROUTES_BY_ID_MAP?.has(normalizedId)) { + return null + } + let routeType: 'createFileRoute' | 'createLazyFileRoute' + if (code.includes('createFileRoute(')) { + routeType = 'createFileRoute' + } else if (code.includes('createLazyFileRoute(')) { + routeType = 'createLazyFileRoute' + } else { + return null + } + + const routerImportPath = `@tanstack/${userConfig.target}-router` + + const ast = parseAst({ code }) + + let isCreateRouteFunctionImported = false as boolean + + babel.traverse(ast, { + Program: { + enter(programPath) { + programPath.traverse({ + ImportDeclaration(path) { + const importedSpecifiers = path.node.specifiers.map( + (specifier) => specifier.local.name, + ) + if ( + importedSpecifiers.includes(routeType) && + path.node.source.value === routerImportPath + ) { + isCreateRouteFunctionImported = true + } + }, + }) + }, + }, + }) + + if (!isCreateRouteFunctionImported) { + if (debug) console.info('Adding autoimports to route ', normalizedId) + + const autoImportStatement = template.statement( + `import { ${routeType} } from '${routerImportPath}'`, + )() + ast.program.body.unshift(autoImportStatement) + + const result = generateFromAst(ast, { + sourceMaps: true, + filename: normalizedId, + sourceFileName: normalizedId, + }) + if (debug) { + logDiff(code, result.code) + console.log('Output:\n', result.code + '\n\n') + } + return result + } + + return null + }, + }, + + vite: { + configResolved(config) { + ROOT = config.root + initUserConfig() + }, + // this check may only happen after config is resolved, so we use applyToEnvironment (apply is too early) + applyToEnvironment() { + return userConfig.verboseFileRoutes === false + }, + }, + + rspack() { + ROOT = process.cwd() + initUserConfig() + }, + + webpack() { + ROOT = process.cwd() + initUserConfig() + }, + } +} diff --git a/packages/router-plugin/src/core/route-hmr-statement.ts b/packages/router-plugin/src/core/route-hmr-statement.ts new file mode 100644 index 0000000000..c0b4c2def0 --- /dev/null +++ b/packages/router-plugin/src/core/route-hmr-statement.ts @@ -0,0 +1,182 @@ +import * as template from '@babel/template' +import type { AnyRoute, AnyRouteMatch, AnyRouter } from '@tanstack/router-core' + +type AnyRouteWithPrivateProps = AnyRoute & { + options: Record<string, unknown> + _componentsPromise?: Promise<void> + _lazyPromise?: Promise<void> + update: (options: Record<string, unknown>) => unknown + _path: string + _id: string + _fullPath: string + _to: string +} + +type AnyRouterWithPrivateMaps = AnyRouter & { + routesById: Record<string, AnyRoute> + routesByPath: Record<string, AnyRoute> + stores: AnyRouter['stores'] & { + cachedMatchStoresById: Map< + string, + { + setState: (updater: (prev: AnyRouteMatch) => AnyRouteMatch) => void + } + > + pendingMatchStoresById: Map< + string, + { + setState: (updater: (prev: AnyRouteMatch) => AnyRouteMatch) => void + } + > + activeMatchStoresById: Map< + string, + { + setState: (updater: (prev: AnyRouteMatch) => AnyRouteMatch) => void + } + > + } +} + +type AnyRouteMatchWithPrivateProps = AnyRouteMatch & { + __beforeLoadContext?: unknown +} + +function handleRouteUpdate( + routeId: string, + newRoute: AnyRouteWithPrivateProps, +) { + const router = window.__TSR_ROUTER__ as AnyRouterWithPrivateMaps + const oldRoute = router.routesById[routeId] as + | AnyRouteWithPrivateProps + | undefined + + if (!oldRoute) { + return + } + + // Keys whose identity must remain stable to prevent React from + // unmounting/remounting the component tree. React Fast Refresh already + // handles hot-updating the function bodies of these components — our job + // is only to update non-component route options (loader, head, etc.). + // For code-split (splittable) routes, the lazyRouteComponent wrapper is + // already cached in import.meta.hot.data so its identity is stable. + // For unsplittable routes (e.g. root routes), the component is a plain + // function reference that gets recreated on every module re-execution, + // so we must explicitly preserve the old reference. + const removedKeys = new Set<string>() + Object.keys(oldRoute.options).forEach((key) => { + if (!(key in newRoute.options)) { + removedKeys.add(key) + delete oldRoute.options[key] + } + }) + + // Preserve component identity so React doesn't remount. + // React Fast Refresh patches the function bodies in-place. + const componentKeys = '__TSR_COMPONENT_TYPES__' as unknown as Array<string> + componentKeys.forEach((key) => { + if (key in oldRoute.options && key in newRoute.options) { + newRoute.options[key] = oldRoute.options[key] + } + }) + + oldRoute.options = newRoute.options + oldRoute.update(newRoute.options) + oldRoute._componentsPromise = undefined + oldRoute._lazyPromise = undefined + + router.routesById[oldRoute.id] = oldRoute + router.routesByPath[oldRoute.fullPath] = oldRoute + + router.processedTree.matchCache.clear() + router.processedTree.flatCache?.clear() + router.processedTree.singleCache.clear() + router.resolvePathCache.clear() + walkReplaceSegmentTree(oldRoute, router.processedTree.segmentTree) + + const filter = (m: AnyRouteMatch) => m.routeId === oldRoute.id + const activeMatch = router.stores.activeMatchesSnapshot.state.find(filter) + const pendingMatch = router.stores.pendingMatchesSnapshot.state.find(filter) + const cachedMatches = router.stores.cachedMatchesSnapshot.state.filter(filter) + + if (activeMatch || pendingMatch || cachedMatches.length > 0) { + // Clear stale match data for removed route options BEFORE invalidating. + // Without this, router.invalidate() -> matchRoutes() reuses the existing + // match from the store (via ...existingMatch spread) and the stale + // loaderData / __beforeLoadContext survives the reload cycle. + // + // We must update the store directly (not via router.updateMatch) because + // updateMatch wraps in startTransition which may defer the state update, + // and we need the clear to be visible before invalidate reads the store. + if (removedKeys.has('loader') || removedKeys.has('beforeLoad')) { + const matchIds = [ + activeMatch?.id, + pendingMatch?.id, + ...cachedMatches.map((match) => match.id), + ].filter(Boolean) as Array<string> + router.batch(() => { + for (const matchId of matchIds) { + const store = + router.stores.pendingMatchStoresById.get(matchId) || + router.stores.activeMatchStoresById.get(matchId) || + router.stores.cachedMatchStoresById.get(matchId) + if (store) { + store.setState((prev) => { + const next: AnyRouteMatchWithPrivateProps = { ...prev } + + if (removedKeys.has('loader')) { + next.loaderData = undefined + } + if (removedKeys.has('beforeLoad')) { + next.__beforeLoadContext = undefined + } + + return next + }) + } + } + }) + } + + router.invalidate({ filter, sync: true }) + } + + function walkReplaceSegmentTree( + route: AnyRouteWithPrivateProps, + node: AnyRouter['processedTree']['segmentTree'], + ) { + if (node.route?.id === route.id) node.route = route + if (node.index) walkReplaceSegmentTree(route, node.index) + node.static?.forEach((child) => walkReplaceSegmentTree(route, child)) + node.staticInsensitive?.forEach((child) => + walkReplaceSegmentTree(route, child), + ) + node.dynamic?.forEach((child) => walkReplaceSegmentTree(route, child)) + node.optional?.forEach((child) => walkReplaceSegmentTree(route, child)) + node.wildcard?.forEach((child) => walkReplaceSegmentTree(route, child)) + } +} + +const handleRouteUpdateStr = handleRouteUpdate.toString() + +export function createRouteHmrStatement(stableRouteOptionKeys: Array<string>) { + return template.statement( + ` +if (import.meta.hot) { + import.meta.hot.accept((newModule) => { + if (Route && newModule && newModule.Route) { + const routeId = import.meta.hot.data['tsr-route-id'] ?? Route.id + if (routeId) { + import.meta.hot.data['tsr-route-id'] = routeId + } + (${handleRouteUpdateStr.replace( + /['"]__TSR_COMPONENT_TYPES__['"]/, + JSON.stringify(stableRouteOptionKeys), + )})(routeId, newModule.Route) + } + }) +} +`, + { placeholderPattern: false }, + )() +} diff --git a/packages/router-plugin/src/core/router-code-splitter-plugin.ts b/packages/router-plugin/src/core/router-code-splitter-plugin.ts index ecc7607d59..22a22e2af4 100644 --- a/packages/router-plugin/src/core/router-code-splitter-plugin.ts +++ b/packages/router-plugin/src/core/router-code-splitter-plugin.ts @@ -4,7 +4,7 @@ */ import { fileURLToPath, pathToFileURL } from 'node:url' -import { decodeIdentifier, logDiff } from '@tanstack/router-utils' +import { logDiff } from '@tanstack/router-utils' import { getConfig, splitGroupingsSchema } from './config' import { compileCodeSplitReferenceRoute, @@ -13,25 +13,24 @@ import { computeSharedBindings, detectCodeSplitGroupingsFromRoute, } from './code-splitter/compilers' -import { getFrameworkHmrCompilerPlugins } from './code-splitter/plugins/framework-plugins' +import { getReferenceRouteCompilerPlugins } from './code-splitter/plugins/framework-plugins' import { defaultCodeSplitGroupings, splitRouteIdentNodes, + tsrShared, tsrSplit, } from './constants' -import { debug, normalizePath, routeFactoryCallCodeFilter } from './utils' -import { createRouterPluginContext } from './router-plugin-context' +import { decodeIdentifier } from './code-splitter/path-ids' +import { debug, normalizePath } from './utils' import type { CodeSplitGroupings, SplitRouteIdentNodes } from './constants' import type { GetRoutesByFileMapResultValue } from '@tanstack/router-generator' -import type { CodeSplitCompilerPlugin } from './code-splitter/plugins' import type { Config } from './config' -import type { HmrStyle } from './hmr' -import type { RouterPluginContext } from './router-plugin-context' import type { UnpluginFactory, TransformResult as UnpluginTransformResult, } from 'unplugin' +const PLUGIN_NAME = 'unplugin:router-code-splitter' const CODE_SPLITTER_PLUGIN_NAME = 'tanstack-router:code-splitter:compile-reference-file' @@ -78,18 +77,11 @@ const TRANSFORMATION_PLUGINS_BY_FRAMEWORK: Record< ], } -export function createRouterCodeSplitterPlugin( - options: Partial<Config | (() => Config)> | undefined = {}, - routerPluginContext: RouterPluginContext, - hmrStyle: HmrStyle = 'vite', -): ReturnType<UnpluginFactory<Partial<Config | (() => Config)> | undefined>> { +export const unpluginRouterCodeSplitterFactory: UnpluginFactory< + Partial<Config | (() => Config)> | undefined +> = (options = {}, { framework: _framework }) => { let ROOT: string = process.cwd() let userConfig: Config - let addHmr: boolean - let compilerPlugins: Array<CodeSplitCompilerPlugin> - let virtualRouteCompilerPlugins: Array<CodeSplitCompilerPlugin> - - let isProduction = process.env.NODE_ENV === 'production' function initUserConfig() { if (typeof options === 'function') { @@ -97,18 +89,8 @@ export function createRouterCodeSplitterPlugin( } else { userConfig = getConfig(options, ROOT) } - - addHmr = (userConfig.codeSplittingOptions?.addHmr ?? true) && !isProduction - compilerPlugins = addHmr - ? (getFrameworkHmrCompilerPlugins({ - targetFramework: userConfig.target, - hmrStyle, - }) ?? []) - : [] - virtualRouteCompilerPlugins = compilerPlugins.filter( - (plugin) => plugin.onVirtualRouteSplitNode, - ) } + const isProduction = process.env.NODE_ENV === 'production' // Map from normalized route file path → set of shared binding names. // Populated by the reference compiler, consumed by virtual and shared compilers. const sharedBindingsMap = new Map<string, Set<string>>() @@ -132,13 +114,12 @@ export function createRouterCodeSplitterPlugin( const fromCode = detectCodeSplitGroupingsFromRoute({ code, - filename: id, }) if (fromCode.groupings !== undefined) { const res = splitGroupingsSchema.safeParse(fromCode.groupings) if (!res.success) { - const message = res.error.issues.map((e) => e.message).join('. ') + const message = res.error.errors.map((e) => e.message).join('. ') throw new Error( `The groupings for the route "${id}" are invalid.\n${message}`, ) @@ -148,13 +129,13 @@ export function createRouterCodeSplitterPlugin( const userShouldSplitFn = getShouldSplitFn() const pluginSplitBehavior = userShouldSplitFn?.({ - routeId: generatorNodeInfo.routeId, + routeId: generatorNodeInfo.routePath, }) as CodeSplitGroupings | undefined if (pluginSplitBehavior) { const res = splitGroupingsSchema.safeParse(pluginSplitBehavior) if (!res.success) { - const message = res.error.issues.map((e) => e.message).join('. ') + const message = res.error.errors.map((e) => e.message).join('. ') throw new Error( `The groupings returned when using \`splitBehavior\` for the route "${id}" are invalid.\n${message}`, ) @@ -167,7 +148,6 @@ export function createRouterCodeSplitterPlugin( // Compute shared bindings before compiling the reference route const sharedBindings = computeSharedBindings({ code, - filename: id, codeSplitGroupings: splitGroupings, }) if (sharedBindings.size > 0) { @@ -176,21 +156,24 @@ export function createRouterCodeSplitterPlugin( sharedBindingsMap.delete(id) } + const addHmr = + (userConfig.codeSplittingOptions?.addHmr ?? true) && !isProduction + const compiledReferenceRoute = compileCodeSplitReferenceRoute({ code, codeSplitGroupings: splitGroupings, targetFramework: userConfig.target, filename: id, id, - isProduction, deleteNodes: userConfig.codeSplittingOptions?.deleteNodes ? new Set(userConfig.codeSplittingOptions.deleteNodes) : undefined, addHmr, - hmrStyle, - hmrRouteId: generatorNodeInfo.routeId, sharedBindings: sharedBindings.size > 0 ? sharedBindings : undefined, - compilerPlugins, + compilerPlugins: getReferenceRouteCompilerPlugins({ + targetFramework: userConfig.target, + addHmr, + }), }) if (compiledReferenceRoute === null) { @@ -239,7 +222,6 @@ export function createRouterCodeSplitterPlugin( filename: id, splitTargets: grouping, sharedBindings: resolvedSharedBindings, - compilerPlugins: virtualRouteCompilerPlugins, }) if (debug) { @@ -250,6 +232,11 @@ export function createRouterCodeSplitterPlugin( return result } + const includedCode = [ + 'createFileRoute(', + 'createRootRoute(', + 'createRootRouteWithContext(', + ] return [ { name: 'tanstack-router:code-splitter:compile-reference-file', @@ -258,18 +245,22 @@ export function createRouterCodeSplitterPlugin( transform: { filter: { id: { + exclude: [tsrSplit, tsrShared], // this is necessary for webpack / rspack to avoid matching .html files include: /\.(m|c)?(j|t)sx?$/, }, code: { - include: routeFactoryCallCodeFilter, + include: includedCode, }, }, handler(code, id) { const normalizedId = normalizePath(id) const generatorFileInfo = - routerPluginContext.routesByFile.get(normalizedId) - if (generatorFileInfo) { + globalThis.TSR_ROUTES_BY_ID_MAP?.get(normalizedId) + if ( + generatorFileInfo && + includedCode.some((included) => code.includes(included)) + ) { return handleCompilingReferenceFile( code, normalizedId, @@ -283,7 +274,6 @@ export function createRouterCodeSplitterPlugin( vite: { configResolved(config) { - isProduction = config.command === 'build' ROOT = config.root initUserConfig() @@ -328,15 +318,25 @@ export function createRouterCodeSplitterPlugin( }, rspack(compiler) { - isProduction = (compiler.options.mode ?? 'production') === 'production' ROOT = process.cwd() initUserConfig() + + if (compiler.options.mode === 'production') { + compiler.hooks.done.tap(PLUGIN_NAME, () => { + console.info('✅ ' + PLUGIN_NAME + ': code-splitting done!') + }) + } }, webpack(compiler) { - isProduction = (compiler.options.mode ?? 'production') === 'production' ROOT = process.cwd() initUserConfig() + + if (compiler.options.mode === 'production') { + compiler.hooks.done.tap(PLUGIN_NAME, () => { + console.info('✅ ' + PLUGIN_NAME + ': code-splitting done!') + }) + } }, }, { @@ -411,9 +411,3 @@ export function createRouterCodeSplitterPlugin( }, ] } - -export const unpluginRouterCodeSplitterFactory: UnpluginFactory< - Partial<Config | (() => Config)> | undefined -> = (options = {}) => { - return createRouterCodeSplitterPlugin(options, createRouterPluginContext()) -} diff --git a/packages/router-plugin/src/core/router-composed-plugin.ts b/packages/router-plugin/src/core/router-composed-plugin.ts index 5bcaaf8da9..e7b6f10821 100644 --- a/packages/router-plugin/src/core/router-composed-plugin.ts +++ b/packages/router-plugin/src/core/router-composed-plugin.ts @@ -1,102 +1,41 @@ import { getConfig } from '@tanstack/router-generator' -import { createRouterGeneratorPlugin } from './router-generator-plugin' -import { createRouterCodeSplitterPlugin } from './router-code-splitter-plugin' -import { createRouterHmrPlugin } from './router-hmr-plugin' -import { createRouterPluginContext } from './router-plugin-context' +import { unpluginRouterGeneratorFactory } from './router-generator-plugin' +import { unpluginRouterCodeSplitterFactory } from './router-code-splitter-plugin' +import { unpluginRouterHmrFactory } from './router-hmr-plugin' +import { unpluginRouteAutoImportFactory } from './route-autoimport-plugin' import type { Config } from './config' -import type { HmrStyle } from './hmr' -import type { - RspackCompiler, - UnpluginFactory, - UnpluginOptions, - WebpackCompiler, -} from 'unplugin' - -const INLINE_CSS_DEFAULT_DEFINES = { - 'process.env.TSS_INLINE_CSS_ENABLED': JSON.stringify('false'), - 'import.meta.env.TSS_INLINE_CSS_ENABLED': JSON.stringify('false'), -} - -type EsbuildOptionsWithDefine = Parameters< - NonNullable<NonNullable<UnpluginOptions['esbuild']>['config']> ->[0] - -function applyWebpackInlineCssDefaultDefinePlugin(compiler: WebpackCompiler) { - new compiler.webpack.DefinePlugin(INLINE_CSS_DEFAULT_DEFINES).apply(compiler) -} - -function applyRspackInlineCssDefaultDefinePlugin(compiler: RspackCompiler) { - new compiler.webpack.DefinePlugin(INLINE_CSS_DEFAULT_DEFINES).apply(compiler) -} +import type { UnpluginFactory } from 'unplugin' export const unpluginRouterComposedFactory: UnpluginFactory< - Partial<Config | (() => Config)> | undefined + Partial<Config> | undefined > = (options = {}, meta) => { const ROOT: string = process.cwd() - const userConfig = getConfig( - (typeof options === 'function' ? options() : options) as Partial<Config>, - ROOT, - ) - const routerPluginContext = createRouterPluginContext() - // webpack and Rspack share webpack's `import.meta.webpackHot` HMR API. - const hmrStyle: HmrStyle = - meta.framework === 'webpack' || meta.framework === 'rspack' - ? 'webpack' - : 'vite' + const userConfig = getConfig(options, ROOT) - const getPlugin = (plugin: ReturnType<UnpluginFactory<any>>) => { + const getPlugin = (pluginFactory: UnpluginFactory<Partial<Config>>) => { + const plugin = pluginFactory(options, meta) if (!Array.isArray(plugin)) { return [plugin] } return plugin } - const routerGenerator = getPlugin( - createRouterGeneratorPlugin(options, routerPluginContext), - ) - const routerCodeSplitter = getPlugin( - createRouterCodeSplitterPlugin(options, routerPluginContext, hmrStyle), - ) + const routerGenerator = getPlugin(unpluginRouterGeneratorFactory) + const routerCodeSplitter = getPlugin(unpluginRouterCodeSplitterFactory) + const routeAutoImport = getPlugin(unpluginRouteAutoImportFactory) - const result = [ - { - name: 'tanstack:router-inline-css-defaults', - vite: { - config() { - return { - define: { - ...INLINE_CSS_DEFAULT_DEFINES, - }, - } - }, - }, - webpack(compiler: WebpackCompiler) { - applyWebpackInlineCssDefaultDefinePlugin(compiler) - }, - rspack(compiler: RspackCompiler) { - applyRspackInlineCssDefaultDefinePlugin(compiler) - }, - esbuild: { - config(options: EsbuildOptionsWithDefine) { - options.define = { - ...INLINE_CSS_DEFAULT_DEFINES, - ...options.define, - } - }, - }, - }, - ...routerGenerator, - ] + const result = [...routerGenerator] if (userConfig.autoCodeSplitting) { result.push(...routerCodeSplitter) } + if (userConfig.verboseFileRoutes === false) { + result.push(...routeAutoImport) + } const isProduction = process.env.NODE_ENV === 'production' if (!isProduction && !userConfig.autoCodeSplitting) { - const routerHmr = getPlugin( - createRouterHmrPlugin(options, routerPluginContext, hmrStyle), - ) + const routerHmr = getPlugin(unpluginRouterHmrFactory) result.push(...routerHmr) } return result diff --git a/packages/router-plugin/src/core/router-generator-plugin.ts b/packages/router-plugin/src/core/router-generator-plugin.ts index 50dde9f55c..055a1bc3c5 100644 --- a/packages/router-plugin/src/core/router-generator-plugin.ts +++ b/packages/router-plugin/src/core/router-generator-plugin.ts @@ -1,24 +1,23 @@ import { isAbsolute, join, normalize } from 'node:path' import { Generator, resolveConfigPath } from '@tanstack/router-generator' import { getConfig } from './config' -import { createRouterPluginContext } from './router-plugin-context' import type { GeneratorEvent } from '@tanstack/router-generator' import type { FSWatcher } from 'chokidar' import type { UnpluginFactory } from 'unplugin' import type { Config } from './config' -import type { RouterPluginContext } from './router-plugin-context' const PLUGIN_NAME = 'unplugin:router-generator' -export function createRouterGeneratorPlugin( - options: Partial<Config | (() => Config)> | undefined = {}, - routerPluginContext: RouterPluginContext, -): ReturnType<UnpluginFactory<Partial<Config | (() => Config)> | undefined>> { +export const unpluginRouterGeneratorFactory: UnpluginFactory< + Partial<Config | (() => Config)> | undefined +> = (options = {}) => { let ROOT: string = process.cwd() let userConfig: Config let generator: Generator + const routeGenerationDisabled = () => + userConfig.enableRouteGeneration === false const getRoutesDirectoryPath = () => { return isAbsolute(userConfig.routesDirectory) ? userConfig.routesDirectory @@ -44,6 +43,9 @@ export function createRouterGeneratorPlugin( file: string event: 'create' | 'update' | 'delete' }) => { + if (routeGenerationDisabled()) { + return + } let generatorEvent: GeneratorEvent | undefined = undefined if (opts) { const filePath = normalize(opts.file) @@ -56,7 +58,7 @@ export function createRouterGeneratorPlugin( try { await generator.run(generatorEvent) - routerPluginContext.routesByFile = generator.getRoutesByFileMap() + globalThis.TSR_ROUTES_BY_ID_MAP = generator.getRoutesByFileMap() } catch (e) { console.error(e) } @@ -144,9 +146,3 @@ export function createRouterGeneratorPlugin( }, } } - -export const unpluginRouterGeneratorFactory: UnpluginFactory< - Partial<Config | (() => Config)> | undefined -> = (options = {}) => { - return createRouterGeneratorPlugin(options, createRouterPluginContext()) -} diff --git a/packages/router-plugin/src/core/router-hmr-plugin.ts b/packages/router-plugin/src/core/router-hmr-plugin.ts index 3f14a38be5..9ebb745772 100644 --- a/packages/router-plugin/src/core/router-hmr-plugin.ts +++ b/packages/router-plugin/src/core/router-hmr-plugin.ts @@ -1,14 +1,11 @@ import { generateFromAst, logDiff, parseAst } from '@tanstack/router-utils' import { compileCodeSplitReferenceRoute } from './code-splitter/compilers' -import { getFrameworkHmrCompilerPlugins } from './code-splitter/plugins/framework-plugins' -import { createRouteHmrStatement } from './hmr' -import { debug, normalizePath, routeFactoryCallCodeFilter } from './utils' +import { getReferenceRouteCompilerPlugins } from './code-splitter/plugins/framework-plugins' +import { createRouteHmrStatement } from './route-hmr-statement' +import { debug, normalizePath } from './utils' import { getConfig } from './config' -import { createRouterPluginContext } from './router-plugin-context' import type { UnpluginFactory } from 'unplugin' import type { Config } from './config' -import type { HmrStyle } from './hmr' -import type { RouterPluginContext } from './router-plugin-context' /** * This plugin adds HMR support for file routes. @@ -16,18 +13,16 @@ import type { RouterPluginContext } from './router-plugin-context' * handles HMR for code-split routes itself. */ -export function createRouterHmrPlugin( - options: Partial<Config | (() => Config)> | undefined = {}, - routerPluginContext: RouterPluginContext, - hmrStyle: HmrStyle = 'vite', -): ReturnType<UnpluginFactory<Partial<Config> | undefined>> { +const includeCode = [ + 'createFileRoute(', + 'createRootRoute(', + 'createRootRouteWithContext(', +] +export const unpluginRouterHmrFactory: UnpluginFactory< + Partial<Config> | undefined +> = (options = {}) => { let ROOT: string = process.cwd() - - const resolveUserConfig = () => { - return getConfig(typeof options === 'function' ? options() : options, ROOT) - } - - let userConfig = resolveUserConfig() + let userConfig = options as Config return { name: 'tanstack-router:hmr', @@ -37,30 +32,27 @@ export function createRouterHmrPlugin( // this is necessary for webpack / rspack to avoid matching .html files id: /\.(m|c)?(j|t)sx?$/, code: { - include: routeFactoryCallCodeFilter, + include: includeCode, }, }, handler(code, id) { const normalizedId = normalizePath(id) - const routeEntry = routerPluginContext.routesByFile.get(normalizedId) - if (!routeEntry) { + if (!globalThis.TSR_ROUTES_BY_ID_MAP?.has(normalizedId)) { return null } if (debug) console.info('Adding HMR handling to route ', normalizedId) if (userConfig.target === 'react') { - const compilerPlugins = getFrameworkHmrCompilerPlugins({ + const compilerPlugins = getReferenceRouteCompilerPlugins({ targetFramework: 'react', - hmrStyle, + addHmr: true, }) const compiled = compileCodeSplitReferenceRoute({ code, filename: normalizedId, id: normalizedId, addHmr: true, - hmrStyle, - hmrRouteId: routeEntry.routeId, codeSplitGroupings: [], targetFramework: 'react', compilerPlugins, @@ -76,14 +68,8 @@ export function createRouterHmrPlugin( } } - const ast = parseAst({ code, filename: normalizedId }) - ast.program.body.push( - ...createRouteHmrStatement([], { - hmrStyle, - targetFramework: userConfig.target, - routeId: routeEntry.routeId, - }), - ) + const ast = parseAst({ code }) + ast.program.body.push(createRouteHmrStatement([])) const result = generateFromAst(ast, { sourceMaps: true, filename: normalizedId, @@ -99,7 +85,7 @@ export function createRouterHmrPlugin( vite: { configResolved(config) { ROOT = config.root - userConfig = resolveUserConfig() + userConfig = getConfig(options, ROOT) }, applyToEnvironment(environment) { if (userConfig.plugin?.vite?.environmentName) { @@ -110,9 +96,3 @@ export function createRouterHmrPlugin( }, } } - -export const unpluginRouterHmrFactory: UnpluginFactory< - Partial<Config> | undefined -> = (options = {}) => { - return createRouterHmrPlugin(options, createRouterPluginContext()) -} diff --git a/packages/router-plugin/src/core/router-plugin-context.ts b/packages/router-plugin/src/core/router-plugin-context.ts deleted file mode 100644 index fad9fbe038..0000000000 --- a/packages/router-plugin/src/core/router-plugin-context.ts +++ /dev/null @@ -1,11 +0,0 @@ -import type { GetRoutesByFileMapResult } from '@tanstack/router-generator' - -export type RouterPluginContext = { - routesByFile: GetRoutesByFileMapResult -} - -export function createRouterPluginContext(): RouterPluginContext { - return { - routesByFile: new Map(), - } -} diff --git a/packages/router-plugin/src/core/utils.ts b/packages/router-plugin/src/core/utils.ts index 61ab1ca278..267582d6ec 100644 --- a/packages/router-plugin/src/core/utils.ts +++ b/packages/router-plugin/src/core/utils.ts @@ -16,12 +16,6 @@ export function normalizePath(path: string): string { return path.replace(/\\/g, '/') } -export const routeFactoryCallCodeFilter = [ - /\bcreateFileRoute\s*\(/, - /\bcreateRootRoute\s*\(/, - /\bcreateRootRouteWithContext\s*(?:<|\()/, -] - export function getObjectPropertyKeyName( prop: t.ObjectProperty, ): string | undefined { diff --git a/packages/router-plugin/src/esbuild.ts b/packages/router-plugin/src/esbuild.ts index e2c184bb3d..c2caaf2cef 100644 --- a/packages/router-plugin/src/esbuild.ts +++ b/packages/router-plugin/src/esbuild.ts @@ -1,30 +1,11 @@ import { createEsbuildPlugin } from 'unplugin' -import { configSchema, getConfig } from './core/config' -import { createRouterGeneratorPlugin } from './core/router-generator-plugin' +import { configSchema } from './core/config' +import { unpluginRouterCodeSplitterFactory } from './core/router-code-splitter-plugin' +import { unpluginRouterGeneratorFactory } from './core/router-generator-plugin' import { unpluginRouterComposedFactory } from './core/router-composed-plugin' -import { createRouterPluginContext } from './core/router-plugin-context' import type { CodeSplittingOptions, Config } from './core/config' -import type { RouterPluginContext } from './core/router-plugin-context' - -type RouterPluginOptions = Partial<Config | (() => Config)> | undefined - -const defaultRouterPluginContext = createRouterPluginContext() - -const ESBUILD_SPLITTING_ERROR = - '@tanstack/router-plugin: route code splitting (`autoCodeSplitting`) is not supported with esbuild. ' + - 'Use the generator alone (`TanStackRouterGeneratorEsbuild`), or set `autoCodeSplitting: false`.' - -function refuseSplitting(options: RouterPluginOptions) { - const config = - typeof options === 'function' - ? options() - : getConfig(options ?? {}, process.cwd()) - if (config.autoCodeSplitting) { - throw new Error(ESBUILD_SPLITTING_ERROR) - } -} /** * @example @@ -35,26 +16,22 @@ function refuseSplitting(options: RouterPluginOptions) { * } * ``` */ -const TanStackRouterGeneratorEsbuild = ( - options?: RouterPluginOptions, - routerPluginContext?: RouterPluginContext, -) => { - const pluginContext = routerPluginContext ?? defaultRouterPluginContext - return createEsbuildPlugin((pluginOptions: RouterPluginOptions) => - createRouterGeneratorPlugin(pluginOptions, pluginContext), - )(options) -} +const TanStackRouterGeneratorEsbuild = createEsbuildPlugin( + unpluginRouterGeneratorFactory, +) /** - * Route code splitting is not available with esbuild: this entry refuses - * clearly. + * @example + * ```ts + * export default { + * plugins: [TanStackRouterCodeSplitterEsbuild()], + * // ... + * } + * ``` */ -const TanStackRouterCodeSplitterEsbuild = ( - _options?: RouterPluginOptions, - _routerPluginContext?: RouterPluginContext, -): never => { - throw new Error(ESBUILD_SPLITTING_ERROR) -} +const TanStackRouterCodeSplitterEsbuild = createEsbuildPlugin( + unpluginRouterCodeSplitterFactory, +) /** * @example @@ -65,10 +42,7 @@ const TanStackRouterCodeSplitterEsbuild = ( * } * ``` */ -const TanStackRouterEsbuild = (options: RouterPluginOptions = {}) => { - refuseSplitting(options) - return createEsbuildPlugin(unpluginRouterComposedFactory)(options) -} +const TanStackRouterEsbuild = createEsbuildPlugin(unpluginRouterComposedFactory) const tanstackRouter = TanStackRouterEsbuild export default TanStackRouterEsbuild @@ -80,4 +54,4 @@ export { tanstackRouter, } -export type { Config, CodeSplittingOptions, RouterPluginContext } +export type { Config, CodeSplittingOptions } diff --git a/packages/router-plugin/src/global.d.ts b/packages/router-plugin/src/global.d.ts new file mode 100644 index 0000000000..c08dc57529 --- /dev/null +++ b/packages/router-plugin/src/global.d.ts @@ -0,0 +1,7 @@ +/* eslint-disable no-var */ +import type { GetRoutesByFileMapResult } from '@tanstack/router-generator' + +declare global { + var TSR_ROUTES_BY_ID_MAP: GetRoutesByFileMapResult | undefined +} +export {} diff --git a/packages/router-plugin/src/index.ts b/packages/router-plugin/src/index.ts index c892c32671..a89dbf5656 100644 --- a/packages/router-plugin/src/index.ts +++ b/packages/router-plugin/src/index.ts @@ -1,6 +1,6 @@ export { configSchema, getConfig } from './core/config' +export { unpluginRouterCodeSplitterFactory } from './core/router-code-splitter-plugin' export { unpluginRouterGeneratorFactory } from './core/router-generator-plugin' -export { createRouterPluginContext } from './core/router-plugin-context' export type { Config, ConfigInput, @@ -8,7 +8,6 @@ export type { CodeSplittingOptions, DeletableNodes, } from './core/config' -export type { RouterPluginContext } from './core/router-plugin-context' export { tsrSplit, splitRouteIdentNodes, diff --git a/packages/router-plugin/src/rspack.ts b/packages/router-plugin/src/rspack.ts index 6020179cce..9eef9f2221 100644 --- a/packages/router-plugin/src/rspack.ts +++ b/packages/router-plugin/src/rspack.ts @@ -1,16 +1,10 @@ import { createRspackPlugin } from 'unplugin' import { configSchema } from './core/config' -import { createRouterCodeSplitterPlugin } from './core/router-code-splitter-plugin' -import { createRouterGeneratorPlugin } from './core/router-generator-plugin' +import { unpluginRouterCodeSplitterFactory } from './core/router-code-splitter-plugin' +import { unpluginRouterGeneratorFactory } from './core/router-generator-plugin' import { unpluginRouterComposedFactory } from './core/router-composed-plugin' -import { createRouterPluginContext } from './core/router-plugin-context' import type { CodeSplittingOptions, Config } from './core/config' -import type { RouterPluginContext } from './core/router-plugin-context' - -type RspackRouterPluginOptions = Partial<Config> | (() => Partial<Config>) - -const defaultRouterPluginContext = createRouterPluginContext() /** * @example @@ -25,23 +19,11 @@ const defaultRouterPluginContext = createRouterPluginContext() * }) * ``` */ -const TanStackRouterGeneratorRspack = ( - options?: RspackRouterPluginOptions, - routerPluginContext?: RouterPluginContext, -) => { - const pluginContext = routerPluginContext ?? defaultRouterPluginContext - return createRspackPlugin((pluginOptions) => - createRouterGeneratorPlugin( - pluginOptions as Partial<Config | (() => Config)> | undefined, - pluginContext, - ), - )(options) -} +const TanStackRouterGeneratorRspack = /* #__PURE__ */ createRspackPlugin( + unpluginRouterGeneratorFactory, +) /** - * Rspack uses webpack-compatible `import.meta.webpackHot` HMR, which the - * code splitter emits for it. - * * @example * ```ts * export default defineConfig({ @@ -54,19 +36,9 @@ const TanStackRouterGeneratorRspack = ( * }) * ``` */ -const TanStackRouterCodeSplitterRspack = ( - options?: RspackRouterPluginOptions, - routerPluginContext?: RouterPluginContext, -) => { - const pluginContext = routerPluginContext ?? defaultRouterPluginContext - return createRspackPlugin((pluginOptions) => - createRouterCodeSplitterPlugin( - pluginOptions as Partial<Config | (() => Config)> | undefined, - pluginContext, - 'webpack', - ), - )(options) -} +const TanStackRouterCodeSplitterRspack = /* #__PURE__ */ createRspackPlugin( + unpluginRouterCodeSplitterFactory, +) /** * @example @@ -93,4 +65,4 @@ export { TanStackRouterCodeSplitterRspack, tanstackRouter, } -export type { Config, CodeSplittingOptions, RouterPluginContext } +export type { Config, CodeSplittingOptions } diff --git a/packages/router-plugin/src/vite.ts b/packages/router-plugin/src/vite.ts index 3608887f33..75b66f31aa 100644 --- a/packages/router-plugin/src/vite.ts +++ b/packages/router-plugin/src/vite.ts @@ -1,16 +1,15 @@ import { createVitePlugin } from 'unplugin' -import { configSchema, getConfig } from './core/config' -import { createRouterCodeSplitterPlugin } from './core/router-code-splitter-plugin' -import { createRouterGeneratorPlugin } from './core/router-generator-plugin' +import { configSchema } from './core/config' +import { unpluginRouterCodeSplitterFactory } from './core/router-code-splitter-plugin' +import { unpluginRouterGeneratorFactory } from './core/router-generator-plugin' import { unpluginRouterComposedFactory } from './core/router-composed-plugin' -import { createRouterPluginContext } from './core/router-plugin-context' -import type { CodeSplittingOptions, Config } from './core/config' -import type { RouterPluginContext } from './core/router-plugin-context' +import { unpluginRouteAutoImportFactory } from './core/route-autoimport-plugin' +import type { CodeSplittingOptions, Config, getConfig } from './core/config' -type RouterPluginOptions = Partial<Config | (() => Config)> | undefined - -const defaultRouterPluginContext = createRouterPluginContext() +const tanstackRouterAutoImport = createVitePlugin( + unpluginRouteAutoImportFactory, +) /** * @example @@ -21,15 +20,7 @@ const defaultRouterPluginContext = createRouterPluginContext() * }) * ``` */ -const tanstackRouterGenerator = ( - options?: RouterPluginOptions, - routerPluginContext?: RouterPluginContext, -) => { - const pluginContext = routerPluginContext ?? defaultRouterPluginContext - return createVitePlugin((pluginOptions: RouterPluginOptions) => - createRouterGeneratorPlugin(pluginOptions, pluginContext), - )(options) -} +const tanstackRouterGenerator = createVitePlugin(unpluginRouterGeneratorFactory) /** * @example @@ -40,15 +31,9 @@ const tanstackRouterGenerator = ( * }) * ``` */ -const tanStackRouterCodeSplitter = ( - options?: RouterPluginOptions, - routerPluginContext?: RouterPluginContext, -) => { - const pluginContext = routerPluginContext ?? defaultRouterPluginContext - return createVitePlugin((pluginOptions: RouterPluginOptions) => - createRouterCodeSplitterPlugin(pluginOptions, pluginContext), - )(options) -} +const tanStackRouterCodeSplitter = createVitePlugin( + unpluginRouterCodeSplitterFactory, +) /** * @example @@ -70,10 +55,11 @@ export default tanstackRouter export { configSchema, getConfig, + tanstackRouterAutoImport, tanStackRouterCodeSplitter, tanstackRouterGenerator, TanStackRouterVite, tanstackRouter, } -export type { Config, CodeSplittingOptions, RouterPluginContext } +export type { Config, CodeSplittingOptions } diff --git a/packages/router-plugin/src/webpack.ts b/packages/router-plugin/src/webpack.ts index 9a0063fd6f..a718e6056a 100644 --- a/packages/router-plugin/src/webpack.ts +++ b/packages/router-plugin/src/webpack.ts @@ -1,14 +1,10 @@ import { createWebpackPlugin } from 'unplugin' import { configSchema } from './core/config' -import { createRouterCodeSplitterPlugin } from './core/router-code-splitter-plugin' -import { createRouterGeneratorPlugin } from './core/router-generator-plugin' +import { unpluginRouterCodeSplitterFactory } from './core/router-code-splitter-plugin' +import { unpluginRouterGeneratorFactory } from './core/router-generator-plugin' import { unpluginRouterComposedFactory } from './core/router-composed-plugin' -import { createRouterPluginContext } from './core/router-plugin-context' import type { CodeSplittingOptions, Config } from './core/config' -import type { RouterPluginContext } from './core/router-plugin-context' - -const defaultRouterPluginContext = createRouterPluginContext() /** * @example @@ -19,19 +15,11 @@ const defaultRouterPluginContext = createRouterPluginContext() * } * ``` */ -const TanStackRouterGeneratorWebpack = ( - options?: Partial<Config>, - routerPluginContext?: RouterPluginContext, -) => { - const pluginContext = routerPluginContext ?? defaultRouterPluginContext - return createWebpackPlugin((pluginOptions: Partial<Config> | undefined) => - createRouterGeneratorPlugin(pluginOptions, pluginContext), - )(options) -} +const TanStackRouterGeneratorWebpack = /* #__PURE__ */ createWebpackPlugin( + unpluginRouterGeneratorFactory, +) /** - * Route HMR in development goes through `import.meta.webpackHot`. - * * @example * ```ts * export default { @@ -40,15 +28,9 @@ const TanStackRouterGeneratorWebpack = ( * } * ``` */ -const TanStackRouterCodeSplitterWebpack = ( - options?: Partial<Config>, - routerPluginContext?: RouterPluginContext, -) => { - const pluginContext = routerPluginContext ?? defaultRouterPluginContext - return createWebpackPlugin((pluginOptions: Partial<Config> | undefined) => - createRouterCodeSplitterPlugin(pluginOptions, pluginContext, 'webpack'), - )(options) -} +const TanStackRouterCodeSplitterWebpack = /* #__PURE__ */ createWebpackPlugin( + unpluginRouterCodeSplitterFactory, +) /** * @example @@ -72,4 +54,4 @@ export { TanStackRouterCodeSplitterWebpack, tanstackRouter, } -export type { Config, CodeSplittingOptions, RouterPluginContext } +export type { Config, CodeSplittingOptions } diff --git a/packages/router-plugin/tests/add-hmr.test.ts b/packages/router-plugin/tests/add-hmr.test.ts index 0d89832f3b..3369ea6dd9 100644 --- a/packages/router-plugin/tests/add-hmr.test.ts +++ b/packages/router-plugin/tests/add-hmr.test.ts @@ -1,21 +1,11 @@ -import { - mkdir, - mkdtemp, - readFile, - readdir, - rm, - writeFile, -} from 'node:fs/promises' +import { readFile, readdir } from 'node:fs/promises' import path from 'node:path' -import { createServer } from 'vite' import { describe, expect, it } from 'vitest' import { compileCodeSplitReferenceRoute } from '../src/core/code-splitter/compilers' import { defaultCodeSplitGroupings } from '../src/core/constants' -import { getFrameworkHmrCompilerPlugins } from '../src/core/code-splitter/plugins/framework-plugins' -import { createRouteHmrStatement } from '../src/core/hmr' +import { getReferenceRouteCompilerPlugins } from '../src/core/code-splitter/plugins/framework-plugins' import { frameworks } from './constants' -import { formatSnapshot } from './format-snapshot' function getFrameworkDir(framework: string) { const files = path.resolve(__dirname, `./add-hmr/test-files/${framework}`) @@ -41,14 +31,13 @@ describe('add-hmr works', () => { addHmr: true, codeSplitGroupings: defaultCodeSplitGroupings, targetFramework: framework, - compilerPlugins: getFrameworkHmrCompilerPlugins({ + compilerPlugins: getReferenceRouteCompilerPlugins({ targetFramework: framework, + addHmr: true, }), }) - await expect( - await formatSnapshot(compileResult?.code || code, filename), - ).toMatchFileSnapshot( + await expect(compileResult?.code || code).toMatchFileSnapshot( path.join(dirs.snapshots, filename.replace('.tsx', '@true.tsx')), ) }, @@ -67,311 +56,16 @@ describe('add-hmr works', () => { addHmr: false, codeSplitGroupings: defaultCodeSplitGroupings, targetFramework: framework, + compilerPlugins: getReferenceRouteCompilerPlugins({ + targetFramework: framework, + addHmr: false, + }), }) - await expect( - await formatSnapshot(compileResult?.code || code, filename), - ).toMatchFileSnapshot( + await expect(compileResult?.code || code).toMatchFileSnapshot( path.join(dirs.snapshots, filename.replace('.tsx', '@false.tsx')), ) }, ) }) - - it('supports configurable webpackHot HMR code generation', async () => { - const filename = 'arrow-function.tsx' - const framework = 'react' - const file = await readFile( - path.join(getFrameworkDir(framework).files, filename), - ) - const code = file.toString() - - const compileResult = compileCodeSplitReferenceRoute({ - code, - filename, - id: filename, - addHmr: true, - hmrStyle: 'webpack', - codeSplitGroupings: defaultCodeSplitGroupings, - targetFramework: framework, - compilerPlugins: getFrameworkHmrCompilerPlugins({ - targetFramework: framework, - hmrStyle: 'webpack', - }), - }) - - await expect( - await formatSnapshot(compileResult?.code || code, filename), - ).toMatchFileSnapshot( - path.join( - getFrameworkDir(framework).snapshots, - filename.replace('.tsx', '@webpack-hot.tsx'), - ), - ) - }) - - it('supports configurable webpackHot unsplittable HMR generation', async () => { - const statement = createRouteHmrStatement([], { - hmrStyle: 'webpack', - targetFramework: 'react', - }) - const output = JSON.stringify(statement) - - expect(output).toContain('webpackHot') - expect(output).not.toContain('import.meta.hot') - expect(output).toContain('oldHasShellComponent') - }) - - it('supports configurable Vite unsplittable HMR generation', async () => { - const statement = createRouteHmrStatement([], { - hmrStyle: 'vite', - targetFramework: 'react', - }) - const output = JSON.stringify(statement) - - expect(output).toContain('MetaProperty') - expect(output).toContain('hot') - expect(output).not.toContain('webpackHot') - expect(output).toContain('newModule') - }) - - it('generates lazy reset and scoped route refresh without route context mutation', async () => { - const filename = 'arrow-function.tsx' - const framework = 'react' - const file = await readFile( - path.join(getFrameworkDir(framework).files, filename), - ) - const code = file.toString() - const compileResult = compileCodeSplitReferenceRoute({ - code, - filename, - id: filename, - addHmr: true, - codeSplitGroupings: defaultCodeSplitGroupings, - targetFramework: framework, - compilerPlugins: getFrameworkHmrCompilerPlugins({ - targetFramework: framework, - }), - }) - if (!compileResult) { - throw new Error('Expected the reference route to be transformed') - } - const output = compileResult.code - - expect(output).toContain( - 'router._replaceRouteChunk(oldRoute, newRoute.lazyFn);', - ) - expect(output).toContain('void router._refreshRoute?.();') - expect(output).not.toContain('__routeContext') - }) - - it('uses a generated route id fallback for Vite HMR', async () => { - const statement = createRouteHmrStatement([], { - hmrStyle: 'vite', - targetFramework: 'react', - routeId: '/posts', - }) - const output = JSON.stringify(statement) - - expect(output).toContain('tsr-route-id') - expect(output).toContain('/posts') - }) - - it('prefers the current generated route id over stale Vite hot data', async () => { - const statement = createRouteHmrStatement([], { - hmrStyle: 'vite', - targetFramework: 'react', - routeId: '/current-route', - }) - const output = JSON.stringify(statement) - - expect(output).toContain('"name":"initialRouteId"') - expect(output).toContain( - '"operator":"??","left":{"type":"StringLiteral","value":"/current-route"', - ) - expect(output).toContain('"object":{"type":"Identifier","name":"hotData"}') - }) - - it('normalizes the generated root route id for Vite HMR', async () => { - const statement = createRouteHmrStatement([], { - hmrStyle: 'vite', - targetFramework: 'react', - routeId: '/__root', - }) - const output = JSON.stringify(statement) - - expect(output).toContain('__root__') - expect(output).not.toContain('/__root') - }) -}) - -/** - * Starts a Vite dev server with the router plugin (and no framework plugin) - * for an app made of `files`, connects an HMR client to it the way the - * browser's `/@vite/client` does, and requests the app's modules from - * `main.ts` on, as a page would. - */ -async function startDevApp( - files: Record<string, string>, - options: { autoCodeSplitting: boolean }, -) { - // Keep the app inside the package so runtime imports resolve. - const root = await mkdtemp(path.join(__dirname, '.add-hmr-')) - await mkdir(path.join(root, 'routes')) - const allFiles: Record<string, string> = { - 'index.html': '<script type="module" src="/main.ts"></script>', - 'main.ts': `import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' -export const router = createRouter({ routeTree }) -`, - 'routes/__root.tsx': `import { createRootRoute } from '@tanstack/react-router' -export const Route = createRootRoute({}) -`, - ...files, - } - for (const [file, code] of Object.entries(allFiles)) { - await writeFile(path.join(root, file), code) - } - const { tanstackRouter } = await import('../src/vite') - const server = await createServer({ - root, - configFile: false, - logLevel: 'silent', - server: { port: 0, strictPort: false }, - // A dependency optimisation would reload the page on its own. - optimizeDeps: { noDiscovery: true, include: [] }, - plugins: [ - tanstackRouter({ - target: 'react', - routesDirectory: './routes', - generatedRouteTree: './routeTree.gen.ts', - autoCodeSplitting: options.autoCodeSplitting, - }), - ], - }) - const close = async () => { - await server.close() - await rm(root, { recursive: true, force: true }) - } - try { - await server.listen() - const origin = server.resolvedUrls!.local[0]!.replace(/\/$/, '') - const messages: Array<{ type: string }> = [] - const socket = new WebSocket( - `${origin.replace('http', 'ws')}/?token=${server.config.webSocketToken}`, - 'vite-hmr', - ) - socket.addEventListener('message', (event) => { - messages.push(JSON.parse(String(event.data))) - }) - await new Promise((resolve, reject) => { - socket.addEventListener('open', resolve) - socket.addEventListener('error', reject) - }) - const statuses: Record<string, number> = {} - const served: Record<string, string> = {} - const queue = ['/main.ts'] - while (queue.length > 0) { - const url = queue.shift()! - if (url in statuses) { - continue - } - const response = await fetch(origin + url) - statuses[url] = response.status - const code = await response.text() - served[url] = code - // Static imports of the app's own modules - for (const [, imported] of code.matchAll( - /^import\s[^'"]*?["'](\/(?!@|node_modules)[^"'?]+)["']/gm, - )) { - queue.push(imported!) - } - } - return { - statuses, - served, - /** Writes `code` to `file`; resolves with Vite's first reaction. */ - async edit(file: string, code: string) { - const seen = messages.length - await writeFile(path.join(root, file), code) - const deadline = Date.now() + 10_000 - while (Date.now() < deadline) { - const reaction = messages - .slice(seen) - .find( - (message) => - message.type === 'update' || message.type === 'full-reload', - ) - if (reaction) { - return reaction.type - } - await new Promise((resolve) => setTimeout(resolve, 50)) - } - return 'nothing' - }, - async close() { - socket.close() - await close() - }, - } - } catch (error) { - await close() - throw error - } -} - -describe('route HMR in a Vite dev server', () => { - // Vite makes a module a hot boundary only when its code spells - // `import.meta.hot.accept(` out. Route modules no framework plugin accepts - // (a `.ts` route file, or an app without `@vitejs/plugin-react`) reloaded - // the page on every edit. - it.each([ - { - name: 'a .ts route file', - file: 'routes/index.ts', - code: `import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/')({ loader: () => 'data v1' }) -`, - autoCodeSplitting: true, - }, - { - name: 'a route component, without a framework plugin', - file: 'routes/index.tsx', - code: `import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/')({ component: () => <p>page v1</p> }) -`, - autoCodeSplitting: false, - }, - ])( - 'an edit of $name is a hot update, not a page reload', - async ({ file, code, autoCodeSplitting }) => { - const app = await startDevApp({ [file]: code }, { autoCodeSplitting }) - try { - expect(app.statuses[`/${file}`]).toBe(200) - expect(await app.edit(file, code.replace('v1', 'v2'))).toBe('update') - } finally { - await app.close() - } - }, - 30_000, - ) - - it('serves a route file with a binding named hot', async () => { - const app = await startDevApp( - { - 'routes/index.tsx': `import { createFileRoute } from '@tanstack/react-router' -const hot = 'hot' -export const Route = createFileRoute('/')({ component: () => <p>{hot}</p> }) -`, - }, - // Unsplit, so the binding stays in the module the HMR code goes into - { autoCodeSplitting: false }, - ) - try { - expect(app.statuses['/routes/index.tsx']).toBe(200) - expect(app.served['/routes/index.tsx']).toMatch(/const hot = ["']hot["']/) - } finally { - await app.close() - } - }, 30_000) }) diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/arrow-function@false.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/arrow-function@false.tsx index 994c89e7b2..48e3768224 100644 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/arrow-function@false.tsx +++ b/packages/router-plugin/tests/add-hmr/snapshots/react/arrow-function@false.tsx @@ -1,10 +1,9 @@ -const $$splitComponentImporter = () => - import('arrow-function.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import * as React from 'react' -import { createFileRoute } from '@tanstack/react-router' -import { fetchPosts } from '../posts' +const $$splitComponentImporter = () => import('arrow-function.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import * as React from 'react'; +import { createFileRoute } from '@tanstack/react-router'; +import { fetchPosts } from '../posts'; export const Route = createFileRoute('/posts')({ loader: fetchPosts, - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/arrow-function@true.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/arrow-function@true.tsx index e45f8b634a..17262ea127 100644 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/arrow-function@true.tsx +++ b/packages/router-plugin/tests/add-hmr/snapshots/react/arrow-function@true.tsx @@ -1,115 +1,118 @@ -const $$splitComponentImporter = () => - import('arrow-function.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import * as React from 'react' -import { createFileRoute } from '@tanstack/react-router' -import { fetchPosts } from '../posts' -const TSRSplitComponent = (() => { - const hot = import.meta.hot - const hotData = hot ? (hot.data ??= {}) : undefined - return ( - hotData?.['tsr-split-component:component'] ?? - lazyRouteComponent($$splitComponentImporter, 'component') - ) -})() +const $$splitComponentImporter = () => import('arrow-function.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import * as React from 'react'; +import { createFileRoute } from '@tanstack/react-router'; +import { fetchPosts } from '../posts'; +const TSRSplitComponent = import.meta.hot?.data?.["tsr-split-component:component"] ?? lazyRouteComponent($$splitComponentImporter, "component"); if (import.meta.hot) { - ;(import.meta.hot.data ??= {})['tsr-split-component:component'] = - TSRSplitComponent + import.meta.hot.data["tsr-split-component:component"] = TSRSplitComponent; } export const Route = createFileRoute('/posts')({ loader: fetchPosts, - component: TSRSplitComponent, -}) + component: TSRSplitComponent +}); if (import.meta.hot && typeof window !== 'undefined') { - import.meta.hot.data ??= {} - const tsrReactRefresh = (window.__TSR_REACT_REFRESH__ ??= (() => { - const ignoredExportsById = new Map() - const previousGetIgnoredExports = window.__getReactRefreshIgnoredExports - window.__getReactRefreshIgnoredExports = (ctx) => { - const ignoredExports = previousGetIgnoredExports?.(ctx) ?? [] - const moduleIgnored = ignoredExportsById.get(ctx.id) ?? [] - return [...ignoredExports, ...moduleIgnored] - } - return { ignoredExportsById } - })()) - tsrReactRefresh.ignoredExportsById.set('arrow-function.tsx', ['Route']) + const tsrReactRefresh = window.__TSR_REACT_REFRESH__ ??= (() => { + const ignoredExportsById = new Map(); + const previousGetIgnoredExports = window.__getReactRefreshIgnoredExports; + window.__getReactRefreshIgnoredExports = ctx => { + const ignoredExports = previousGetIgnoredExports?.(ctx) ?? []; + const moduleIgnored = ignoredExportsById.get(ctx.id) ?? []; + return [...ignoredExports, ...moduleIgnored]; + }; + return { + ignoredExportsById + }; + })(); + tsrReactRefresh.ignoredExportsById.set("arrow-function.tsx", ['Route']); } export function TSRFastRefreshAnchor() { - return null + return null; } if (import.meta.hot) { - const hotData = (import.meta.hot.data ??= {}) - const handleRouteUpdate = function handleRouteUpdate(routeId, newRoute) { - const router = window.__TSR_ROUTER__ - const oldRoute = router.routesById[routeId] - if (!oldRoute) { - return - } - const generatedRouteOptionKeys = new Set(['id', 'path', 'getParentRoute']) - const generatedRouteOptions = {} - generatedRouteOptionKeys.forEach((key) => { - if (key in oldRoute.options) { - generatedRouteOptions[key] = oldRoute.options[key] - } - }) - const oldHasShellComponent = 'shellComponent' in oldRoute.options - const newHasShellComponent = 'shellComponent' in newRoute.options - const preserveComponentIdentity = - oldHasShellComponent === newHasShellComponent - const componentKeys = [ - 'component', - 'shellComponent', - 'pendingComponent', - 'errorComponent', - 'notFoundComponent', - ] - if (preserveComponentIdentity) { - componentKeys.forEach((key) => { - if (key in oldRoute.options && key in newRoute.options) { - newRoute.options[key] = oldRoute.options[key] - } - }) - } - const nextOptions = { ...newRoute.options, ...generatedRouteOptions } - oldRoute.options = nextOptions - oldRoute.update(nextOptions) - router._replaceRouteChunk(oldRoute, newRoute.lazyFn) - router.setRoutes(router.buildRouteTree()) - syncHotRouteExport(oldRoute) - router.resolvePathCache.clear() - void router._refreshRoute?.() - function syncHotRouteExport(liveRoute) { - newRoute.options = liveRoute.options - newRoute.parentRoute = liveRoute.parentRoute - newRoute._path = liveRoute._path - newRoute._id = liveRoute._id - newRoute._fullPath = liveRoute._fullPath - newRoute._to = liveRoute._to - } - } - const initialRouteId = Route.id ?? hotData['tsr-route-id'] - if (initialRouteId) { - hotData['tsr-route-id'] = initialRouteId - } - const existingRoute = - typeof window !== 'undefined' && initialRouteId - ? window.__TSR_ROUTER__?.routesById?.[initialRouteId] - : undefined - if (initialRouteId && existingRoute && existingRoute !== Route) { - handleRouteUpdate(initialRouteId, Route) - hotData['tsr-route-update-handled'] = Route - } - import.meta.hot.accept((newModule) => { + import.meta.hot.accept(newModule => { if (Route && newModule && newModule.Route) { - const routeId = hotData['tsr-route-id'] ?? Route.id + const routeId = import.meta.hot.data['tsr-route-id'] ?? Route.id; if (routeId) { - hotData['tsr-route-id'] = routeId + import.meta.hot.data['tsr-route-id'] = routeId; } - if (hotData['tsr-route-update-handled'] === newModule.Route) { - delete hotData['tsr-route-update-handled'] - return - } - handleRouteUpdate(routeId, newModule.Route) + (function handleRouteUpdate(routeId, newRoute) { + const router = window.__TSR_ROUTER__; + const oldRoute = router.routesById[routeId]; + if (!oldRoute) { + return; + } + ; + const removedKeys = new Set(); + Object.keys(oldRoute.options).forEach(key => { + if (!(key in newRoute.options)) { + removedKeys.add(key); + delete oldRoute.options[key]; + } + }); + const componentKeys = ["component", "shellComponent", "pendingComponent", "errorComponent", "notFoundComponent"]; + componentKeys.forEach(key => { + if (key in oldRoute.options && key in newRoute.options) { + newRoute.options[key] = oldRoute.options[key]; + } + }); + oldRoute.options = newRoute.options; + oldRoute.update(newRoute.options); + oldRoute._componentsPromise = undefined; + oldRoute._lazyPromise = undefined; + router.routesById[oldRoute.id] = oldRoute; + router.routesByPath[oldRoute.fullPath] = oldRoute; + router.processedTree.matchCache.clear(); + router.processedTree.flatCache?.clear(); + router.processedTree.singleCache.clear(); + router.resolvePathCache.clear(); + walkReplaceSegmentTree(oldRoute, router.processedTree.segmentTree); + const filter = m => m.routeId === oldRoute.id; + const activeMatch = router.stores.activeMatchesSnapshot.state.find(filter); + const pendingMatch = router.stores.pendingMatchesSnapshot.state.find(filter); + const cachedMatches = router.stores.cachedMatchesSnapshot.state.filter(filter); + if (activeMatch || pendingMatch || cachedMatches.length > 0) { + if (removedKeys.has("loader") || removedKeys.has("beforeLoad")) { + const matchIds = [activeMatch?.id, pendingMatch?.id, ...cachedMatches.map(match => match.id)].filter(Boolean); + router.batch(() => { + for (const matchId of matchIds) { + const store = router.stores.pendingMatchStoresById.get(matchId) || router.stores.activeMatchStoresById.get(matchId) || router.stores.cachedMatchStoresById.get(matchId); + if (store) { + store.setState(prev => { + const next = { + ...prev + }; + if (removedKeys.has("loader")) { + next.loaderData = undefined; + } + ; + if (removedKeys.has("beforeLoad")) { + next.__beforeLoadContext = undefined; + } + ; + return next; + }); + } + } + }); + } + ; + router.invalidate({ + filter, + sync: true + }); + } + ; + function walkReplaceSegmentTree(route, node) { + if (node.route?.id === route.id) node.route = route; + if (node.index) walkReplaceSegmentTree(route, node.index); + node.static?.forEach(child => walkReplaceSegmentTree(route, child)); + node.staticInsensitive?.forEach(child => walkReplaceSegmentTree(route, child)); + node.dynamic?.forEach(child => walkReplaceSegmentTree(route, child)); + node.optional?.forEach(child => walkReplaceSegmentTree(route, child)); + node.wildcard?.forEach(child => walkReplaceSegmentTree(route, child)); + } + })(routeId, newModule.Route); } - }) -} + }); +} \ No newline at end of file diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/arrow-function@webpack-hot.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/arrow-function@webpack-hot.tsx deleted file mode 100644 index eb655d0287..0000000000 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/arrow-function@webpack-hot.tsx +++ /dev/null @@ -1,107 +0,0 @@ -const $$splitComponentImporter = () => - import('arrow-function.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import * as React from 'react' -import { createFileRoute } from '@tanstack/react-router' -import { fetchPosts } from '../posts' -const TSRSplitComponent = (() => { - const hot = import.meta.webpackHot - const hotData = hot ? (hot.data ??= {}) : undefined - return ( - hotData?.['tsr-split-component:component'] ?? - lazyRouteComponent($$splitComponentImporter, 'component') - ) -})() -if (import.meta.webpackHot) { - ;(import.meta.webpackHot.data ??= {})['tsr-split-component:component'] = - TSRSplitComponent -} -export const Route = createFileRoute('/posts')({ - loader: fetchPosts, - component: TSRSplitComponent, -}) -if (import.meta.webpackHot) { - const hot = import.meta.webpackHot - const hotData = (hot.data ??= {}) - const routeId = - hotData['tsr-route-id'] ?? - Route.id ?? - (Route.isRoot ? '__root__' : undefined) - if (routeId) { - hotData['tsr-route-id'] = routeId - } - const existingRoute = - typeof window !== 'undefined' && routeId - ? window.__TSR_ROUTER__?.routesById?.[routeId] - : undefined - if (routeId && existingRoute && existingRoute !== Route) { - ;(function handleRouteUpdate(routeId, newRoute) { - const router = window.__TSR_ROUTER__ - const oldRoute = router.routesById[routeId] - if (!oldRoute) { - return - } - const generatedRouteOptionKeys = new Set(['id', 'path', 'getParentRoute']) - const generatedRouteOptions = {} - generatedRouteOptionKeys.forEach((key) => { - if (key in oldRoute.options) { - generatedRouteOptions[key] = oldRoute.options[key] - } - }) - const oldHasShellComponent = 'shellComponent' in oldRoute.options - const newHasShellComponent = 'shellComponent' in newRoute.options - const preserveComponentIdentity = - oldHasShellComponent === newHasShellComponent - const componentKeys = [ - 'component', - 'shellComponent', - 'pendingComponent', - 'errorComponent', - 'notFoundComponent', - ] - if (preserveComponentIdentity) { - componentKeys.forEach((key) => { - if (key in oldRoute.options && key in newRoute.options) { - newRoute.options[key] = oldRoute.options[key] - } - }) - } - const nextOptions = { ...newRoute.options, ...generatedRouteOptions } - oldRoute.options = nextOptions - oldRoute.update(nextOptions) - router._replaceRouteChunk(oldRoute, newRoute.lazyFn) - router.setRoutes(router.buildRouteTree()) - syncHotRouteExport(oldRoute) - router.resolvePathCache.clear() - void router._refreshRoute?.() - function syncHotRouteExport(liveRoute) { - newRoute.options = liveRoute.options - newRoute.parentRoute = liveRoute.parentRoute - newRoute._path = liveRoute._path - newRoute._id = liveRoute._id - newRoute._fullPath = liveRoute._fullPath - newRoute._to = liveRoute._to - } - })(routeId, Route) - try { - const tsrReactRefreshUtils = - typeof __react_refresh_utils__ !== 'undefined' - ? __react_refresh_utils__ - : undefined - const tsrEnqueueUpdate = - tsrReactRefreshUtils && - typeof tsrReactRefreshUtils.enqueueUpdate === 'function' - ? tsrReactRefreshUtils.enqueueUpdate - : undefined - if (tsrEnqueueUpdate) { - tsrEnqueueUpdate(() => {}) - } - } catch (_err) {} - } - hot.dispose((data) => { - if (routeId) { - data['tsr-route-id'] = routeId - } - }) - hot.accept() -} diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/createFileRoute-lowercase-components@false.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/createFileRoute-lowercase-components@false.tsx deleted file mode 100644 index e0b52f6ad6..0000000000 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/createFileRoute-lowercase-components@false.tsx +++ /dev/null @@ -1,17 +0,0 @@ -const $$splitComponentImporter = () => - import('createFileRoute-lowercase-components.tsx?tsr-split=component') -const $$splitErrorComponentImporter = () => - import('createFileRoute-lowercase-components.tsx?tsr-split=errorComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/lowercase-components')({ - pendingComponent: pendingComponent, - errorComponent: lazyRouteComponent( - $$splitErrorComponentImporter, - 'errorComponent', - ), - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) -function pendingComponent() { - return <div>Pending</div> -} diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/createFileRoute-lowercase-components@true.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/createFileRoute-lowercase-components@true.tsx deleted file mode 100644 index 441852d762..0000000000 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/createFileRoute-lowercase-components@true.tsx +++ /dev/null @@ -1,134 +0,0 @@ -const $$splitComponentImporter = () => - import('createFileRoute-lowercase-components.tsx?tsr-split=component') -const $$splitErrorComponentImporter = () => - import('createFileRoute-lowercase-components.tsx?tsr-split=errorComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' -const TSRSplitErrorComponent = (() => { - const hot = import.meta.hot - const hotData = hot ? (hot.data ??= {}) : undefined - return ( - hotData?.['tsr-split-component:errorComponent'] ?? - lazyRouteComponent($$splitErrorComponentImporter, 'errorComponent') - ) -})() -if (import.meta.hot) { - ;(import.meta.hot.data ??= {})['tsr-split-component:errorComponent'] = - TSRSplitErrorComponent -} -const TSRSplitComponent = (() => { - const hot = import.meta.hot - const hotData = hot ? (hot.data ??= {}) : undefined - return ( - hotData?.['tsr-split-component:component'] ?? - lazyRouteComponent($$splitComponentImporter, 'component') - ) -})() -if (import.meta.hot) { - ;(import.meta.hot.data ??= {})['tsr-split-component:component'] = - TSRSplitComponent -} -export const Route = createFileRoute('/lowercase-components')({ - pendingComponent: TSRPendingComponent, - errorComponent: TSRSplitErrorComponent, - component: TSRSplitComponent, -}) -function TSRPendingComponent() { - return <div>Pending</div> -} -if (import.meta.hot && typeof window !== 'undefined') { - import.meta.hot.data ??= {} - const tsrReactRefresh = (window.__TSR_REACT_REFRESH__ ??= (() => { - const ignoredExportsById = new Map() - const previousGetIgnoredExports = window.__getReactRefreshIgnoredExports - window.__getReactRefreshIgnoredExports = (ctx) => { - const ignoredExports = previousGetIgnoredExports?.(ctx) ?? [] - const moduleIgnored = ignoredExportsById.get(ctx.id) ?? [] - return [...ignoredExports, ...moduleIgnored] - } - return { ignoredExportsById } - })()) - tsrReactRefresh.ignoredExportsById.set( - 'createFileRoute-lowercase-components.tsx', - ['Route'], - ) -} -export function TSRFastRefreshAnchor() { - return null -} -if (import.meta.hot) { - const hotData = (import.meta.hot.data ??= {}) - const handleRouteUpdate = function handleRouteUpdate(routeId, newRoute) { - const router = window.__TSR_ROUTER__ - const oldRoute = router.routesById[routeId] - if (!oldRoute) { - return - } - const generatedRouteOptionKeys = new Set(['id', 'path', 'getParentRoute']) - const generatedRouteOptions = {} - generatedRouteOptionKeys.forEach((key) => { - if (key in oldRoute.options) { - generatedRouteOptions[key] = oldRoute.options[key] - } - }) - const oldHasShellComponent = 'shellComponent' in oldRoute.options - const newHasShellComponent = 'shellComponent' in newRoute.options - const preserveComponentIdentity = - oldHasShellComponent === newHasShellComponent - const componentKeys = [ - 'component', - 'shellComponent', - 'pendingComponent', - 'errorComponent', - 'notFoundComponent', - ] - if (preserveComponentIdentity) { - componentKeys.forEach((key) => { - if (key in oldRoute.options && key in newRoute.options) { - newRoute.options[key] = oldRoute.options[key] - } - }) - } - const nextOptions = { ...newRoute.options, ...generatedRouteOptions } - oldRoute.options = nextOptions - oldRoute.update(nextOptions) - router._replaceRouteChunk(oldRoute, newRoute.lazyFn) - router.setRoutes(router.buildRouteTree()) - syncHotRouteExport(oldRoute) - router.resolvePathCache.clear() - void router._refreshRoute?.() - function syncHotRouteExport(liveRoute) { - newRoute.options = liveRoute.options - newRoute.parentRoute = liveRoute.parentRoute - newRoute._path = liveRoute._path - newRoute._id = liveRoute._id - newRoute._fullPath = liveRoute._fullPath - newRoute._to = liveRoute._to - } - } - const initialRouteId = Route.id ?? hotData['tsr-route-id'] - if (initialRouteId) { - hotData['tsr-route-id'] = initialRouteId - } - const existingRoute = - typeof window !== 'undefined' && initialRouteId - ? window.__TSR_ROUTER__?.routesById?.[initialRouteId] - : undefined - if (initialRouteId && existingRoute && existingRoute !== Route) { - handleRouteUpdate(initialRouteId, Route) - hotData['tsr-route-update-handled'] = Route - } - import.meta.hot.accept((newModule) => { - if (Route && newModule && newModule.Route) { - const routeId = hotData['tsr-route-id'] ?? Route.id - if (routeId) { - hotData['tsr-route-id'] = routeId - } - if (hotData['tsr-route-update-handled'] === newModule.Route) { - delete hotData['tsr-route-update-handled'] - return - } - handleRouteUpdate(routeId, newModule.Route) - } - }) -} diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRoute-inline-component@false.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRoute-inline-component@false.tsx index 7e3ad124ae..5daf018617 100644 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRoute-inline-component@false.tsx +++ b/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRoute-inline-component@false.tsx @@ -1,3 +1,6 @@ import * as React from 'react' import { createRootRoute } from '@tanstack/react-router' -export const Route = createRootRoute({ component: () => <div>root hmr</div> }) + +export const Route = createRootRoute({ + component: () => <div>root hmr</div>, +}) diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRoute-inline-component@true.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRoute-inline-component@true.tsx index f45186bdd9..7ccb71595c 100644 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRoute-inline-component@true.tsx +++ b/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRoute-inline-component@true.tsx @@ -1,100 +1,111 @@ -import * as React from 'react' -import { createRootRoute } from '@tanstack/react-router' -const TSRComponent = () => <div>root hmr</div> -export const Route = createRootRoute({ component: TSRComponent }) +import * as React from 'react'; +import { createRootRoute } from '@tanstack/react-router'; +const TSRComponent = () => <div>root hmr</div>; +export const Route = createRootRoute({ + component: TSRComponent +}); if (import.meta.hot && typeof window !== 'undefined') { - import.meta.hot.data ??= {} - const tsrReactRefresh = (window.__TSR_REACT_REFRESH__ ??= (() => { - const ignoredExportsById = new Map() - const previousGetIgnoredExports = window.__getReactRefreshIgnoredExports - window.__getReactRefreshIgnoredExports = (ctx) => { - const ignoredExports = previousGetIgnoredExports?.(ctx) ?? [] - const moduleIgnored = ignoredExportsById.get(ctx.id) ?? [] - return [...ignoredExports, ...moduleIgnored] - } - return { ignoredExportsById } - })()) - tsrReactRefresh.ignoredExportsById.set( - 'createRootRoute-inline-component.tsx', - ['Route'], - ) + const tsrReactRefresh = window.__TSR_REACT_REFRESH__ ??= (() => { + const ignoredExportsById = new Map(); + const previousGetIgnoredExports = window.__getReactRefreshIgnoredExports; + window.__getReactRefreshIgnoredExports = ctx => { + const ignoredExports = previousGetIgnoredExports?.(ctx) ?? []; + const moduleIgnored = ignoredExportsById.get(ctx.id) ?? []; + return [...ignoredExports, ...moduleIgnored]; + }; + return { + ignoredExportsById + }; + })(); + tsrReactRefresh.ignoredExportsById.set("createRootRoute-inline-component.tsx", ['Route']); } export function TSRFastRefreshAnchor() { - return null + return null; } if (import.meta.hot) { - const hotData = (import.meta.hot.data ??= {}) - const handleRouteUpdate = function handleRouteUpdate(routeId, newRoute) { - const router = window.__TSR_ROUTER__ - const oldRoute = router.routesById[routeId] - if (!oldRoute) { - return - } - const generatedRouteOptionKeys = new Set(['id', 'path', 'getParentRoute']) - const generatedRouteOptions = {} - generatedRouteOptionKeys.forEach((key) => { - if (key in oldRoute.options) { - generatedRouteOptions[key] = oldRoute.options[key] - } - }) - const oldHasShellComponent = 'shellComponent' in oldRoute.options - const newHasShellComponent = 'shellComponent' in newRoute.options - const preserveComponentIdentity = - oldHasShellComponent === newHasShellComponent - const componentKeys = [ - 'component', - 'shellComponent', - 'pendingComponent', - 'errorComponent', - 'notFoundComponent', - ] - if (preserveComponentIdentity) { - componentKeys.forEach((key) => { - if (key in oldRoute.options && key in newRoute.options) { - newRoute.options[key] = oldRoute.options[key] - } - }) - } - const nextOptions = { ...newRoute.options, ...generatedRouteOptions } - oldRoute.options = nextOptions - oldRoute.update(nextOptions) - router._replaceRouteChunk(oldRoute, newRoute.lazyFn) - router.setRoutes(router.buildRouteTree()) - syncHotRouteExport(oldRoute) - router.resolvePathCache.clear() - void router._refreshRoute?.() - function syncHotRouteExport(liveRoute) { - newRoute.options = liveRoute.options - newRoute.parentRoute = liveRoute.parentRoute - newRoute._path = liveRoute._path - newRoute._id = liveRoute._id - newRoute._fullPath = liveRoute._fullPath - newRoute._to = liveRoute._to - } - } - const initialRouteId = Route.id ?? hotData['tsr-route-id'] - if (initialRouteId) { - hotData['tsr-route-id'] = initialRouteId - } - const existingRoute = - typeof window !== 'undefined' && initialRouteId - ? window.__TSR_ROUTER__?.routesById?.[initialRouteId] - : undefined - if (initialRouteId && existingRoute && existingRoute !== Route) { - handleRouteUpdate(initialRouteId, Route) - hotData['tsr-route-update-handled'] = Route - } - import.meta.hot.accept((newModule) => { + import.meta.hot.accept(newModule => { if (Route && newModule && newModule.Route) { - const routeId = hotData['tsr-route-id'] ?? Route.id + const routeId = import.meta.hot.data['tsr-route-id'] ?? Route.id; if (routeId) { - hotData['tsr-route-id'] = routeId + import.meta.hot.data['tsr-route-id'] = routeId; } - if (hotData['tsr-route-update-handled'] === newModule.Route) { - delete hotData['tsr-route-update-handled'] - return - } - handleRouteUpdate(routeId, newModule.Route) + (function handleRouteUpdate(routeId, newRoute) { + const router = window.__TSR_ROUTER__; + const oldRoute = router.routesById[routeId]; + if (!oldRoute) { + return; + } + ; + const removedKeys = new Set(); + Object.keys(oldRoute.options).forEach(key => { + if (!(key in newRoute.options)) { + removedKeys.add(key); + delete oldRoute.options[key]; + } + }); + const componentKeys = ["component", "shellComponent", "pendingComponent", "errorComponent", "notFoundComponent"]; + componentKeys.forEach(key => { + if (key in oldRoute.options && key in newRoute.options) { + newRoute.options[key] = oldRoute.options[key]; + } + }); + oldRoute.options = newRoute.options; + oldRoute.update(newRoute.options); + oldRoute._componentsPromise = undefined; + oldRoute._lazyPromise = undefined; + router.routesById[oldRoute.id] = oldRoute; + router.routesByPath[oldRoute.fullPath] = oldRoute; + router.processedTree.matchCache.clear(); + router.processedTree.flatCache?.clear(); + router.processedTree.singleCache.clear(); + router.resolvePathCache.clear(); + walkReplaceSegmentTree(oldRoute, router.processedTree.segmentTree); + const filter = m => m.routeId === oldRoute.id; + const activeMatch = router.stores.activeMatchesSnapshot.state.find(filter); + const pendingMatch = router.stores.pendingMatchesSnapshot.state.find(filter); + const cachedMatches = router.stores.cachedMatchesSnapshot.state.filter(filter); + if (activeMatch || pendingMatch || cachedMatches.length > 0) { + if (removedKeys.has("loader") || removedKeys.has("beforeLoad")) { + const matchIds = [activeMatch?.id, pendingMatch?.id, ...cachedMatches.map(match => match.id)].filter(Boolean); + router.batch(() => { + for (const matchId of matchIds) { + const store = router.stores.pendingMatchStoresById.get(matchId) || router.stores.activeMatchStoresById.get(matchId) || router.stores.cachedMatchStoresById.get(matchId); + if (store) { + store.setState(prev => { + const next = { + ...prev + }; + if (removedKeys.has("loader")) { + next.loaderData = undefined; + } + ; + if (removedKeys.has("beforeLoad")) { + next.__beforeLoadContext = undefined; + } + ; + return next; + }); + } + } + }); + } + ; + router.invalidate({ + filter, + sync: true + }); + } + ; + function walkReplaceSegmentTree(route, node) { + if (node.route?.id === route.id) node.route = route; + if (node.index) walkReplaceSegmentTree(route, node.index); + node.static?.forEach(child => walkReplaceSegmentTree(route, child)); + node.staticInsensitive?.forEach(child => walkReplaceSegmentTree(route, child)); + node.dynamic?.forEach(child => walkReplaceSegmentTree(route, child)); + node.optional?.forEach(child => walkReplaceSegmentTree(route, child)); + node.wildcard?.forEach(child => walkReplaceSegmentTree(route, child)); + } + })(routeId, newModule.Route); } - }) -} + }); +} \ No newline at end of file diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRoute-lowercase-components@false.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRoute-lowercase-components@false.tsx deleted file mode 100644 index 6fac4df1f1..0000000000 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRoute-lowercase-components@false.tsx +++ /dev/null @@ -1,20 +0,0 @@ -import * as React from 'react' -import { createRootRoute } from '@tanstack/react-router' -export const Route = createRootRoute({ - shellComponent: shellComponent, - pendingComponent: pendingComponent, - errorComponent: errorComponent, - component: component, -}) -function shellComponent({ children }: { children: React.ReactNode }) { - return <html>{children}</html> -} -function pendingComponent() { - return <div>Pending</div> -} -function errorComponent() { - return <div>Error</div> -} -function component() { - return <div>Hello</div> -} diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRoute-lowercase-components@true.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRoute-lowercase-components@true.tsx deleted file mode 100644 index f9a6875fe7..0000000000 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRoute-lowercase-components@true.tsx +++ /dev/null @@ -1,116 +0,0 @@ -import * as React from 'react' -import { createRootRoute } from '@tanstack/react-router' -export const Route = createRootRoute({ - shellComponent: TSRShellComponent, - pendingComponent: TSRPendingComponent, - errorComponent: TSRErrorComponent, - component: TSRComponent, -}) -function TSRShellComponent({ children }: { children: React.ReactNode }) { - return <html>{children}</html> -} -function TSRPendingComponent() { - return <div>Pending</div> -} -function TSRErrorComponent() { - return <div>Error</div> -} -function TSRComponent() { - return <div>Hello</div> -} -if (import.meta.hot && typeof window !== 'undefined') { - import.meta.hot.data ??= {} - const tsrReactRefresh = (window.__TSR_REACT_REFRESH__ ??= (() => { - const ignoredExportsById = new Map() - const previousGetIgnoredExports = window.__getReactRefreshIgnoredExports - window.__getReactRefreshIgnoredExports = (ctx) => { - const ignoredExports = previousGetIgnoredExports?.(ctx) ?? [] - const moduleIgnored = ignoredExportsById.get(ctx.id) ?? [] - return [...ignoredExports, ...moduleIgnored] - } - return { ignoredExportsById } - })()) - tsrReactRefresh.ignoredExportsById.set( - 'createRootRoute-lowercase-components.tsx', - ['Route'], - ) -} -export function TSRFastRefreshAnchor() { - return null -} -if (import.meta.hot) { - const hotData = (import.meta.hot.data ??= {}) - const handleRouteUpdate = function handleRouteUpdate(routeId, newRoute) { - const router = window.__TSR_ROUTER__ - const oldRoute = router.routesById[routeId] - if (!oldRoute) { - return - } - const generatedRouteOptionKeys = new Set(['id', 'path', 'getParentRoute']) - const generatedRouteOptions = {} - generatedRouteOptionKeys.forEach((key) => { - if (key in oldRoute.options) { - generatedRouteOptions[key] = oldRoute.options[key] - } - }) - const oldHasShellComponent = 'shellComponent' in oldRoute.options - const newHasShellComponent = 'shellComponent' in newRoute.options - const preserveComponentIdentity = - oldHasShellComponent === newHasShellComponent - const componentKeys = [ - 'component', - 'shellComponent', - 'pendingComponent', - 'errorComponent', - 'notFoundComponent', - ] - if (preserveComponentIdentity) { - componentKeys.forEach((key) => { - if (key in oldRoute.options && key in newRoute.options) { - newRoute.options[key] = oldRoute.options[key] - } - }) - } - const nextOptions = { ...newRoute.options, ...generatedRouteOptions } - oldRoute.options = nextOptions - oldRoute.update(nextOptions) - router._replaceRouteChunk(oldRoute, newRoute.lazyFn) - router.setRoutes(router.buildRouteTree()) - syncHotRouteExport(oldRoute) - router.resolvePathCache.clear() - void router._refreshRoute?.() - function syncHotRouteExport(liveRoute) { - newRoute.options = liveRoute.options - newRoute.parentRoute = liveRoute.parentRoute - newRoute._path = liveRoute._path - newRoute._id = liveRoute._id - newRoute._fullPath = liveRoute._fullPath - newRoute._to = liveRoute._to - } - } - const initialRouteId = Route.id ?? hotData['tsr-route-id'] - if (initialRouteId) { - hotData['tsr-route-id'] = initialRouteId - } - const existingRoute = - typeof window !== 'undefined' && initialRouteId - ? window.__TSR_ROUTER__?.routesById?.[initialRouteId] - : undefined - if (initialRouteId && existingRoute && existingRoute !== Route) { - handleRouteUpdate(initialRouteId, Route) - hotData['tsr-route-update-handled'] = Route - } - import.meta.hot.accept((newModule) => { - if (Route && newModule && newModule.Route) { - const routeId = hotData['tsr-route-id'] ?? Route.id - if (routeId) { - hotData['tsr-route-id'] = routeId - } - if (hotData['tsr-route-update-handled'] === newModule.Route) { - delete hotData['tsr-route-update-handled'] - return - } - handleRouteUpdate(routeId, newModule.Route) - } - }) -} diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRoute@false.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRoute@false.tsx deleted file mode 100644 index 5c779d9876..0000000000 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRoute@false.tsx +++ /dev/null @@ -1,6 +0,0 @@ -import * as React from 'react' -import { createRootRoute } from '@tanstack/react-router' -export const Route = createRootRoute({ component: RootComponent }) -function RootComponent() { - return <div>Hello</div> -} diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRoute@true.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRoute@true.tsx deleted file mode 100644 index 3bde5adf5c..0000000000 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRoute@true.tsx +++ /dev/null @@ -1,99 +0,0 @@ -import * as React from 'react' -import { createRootRoute } from '@tanstack/react-router' -export const Route = createRootRoute({ component: RootComponent }) -function RootComponent() { - return <div>Hello</div> -} -if (import.meta.hot && typeof window !== 'undefined') { - import.meta.hot.data ??= {} - const tsrReactRefresh = (window.__TSR_REACT_REFRESH__ ??= (() => { - const ignoredExportsById = new Map() - const previousGetIgnoredExports = window.__getReactRefreshIgnoredExports - window.__getReactRefreshIgnoredExports = (ctx) => { - const ignoredExports = previousGetIgnoredExports?.(ctx) ?? [] - const moduleIgnored = ignoredExportsById.get(ctx.id) ?? [] - return [...ignoredExports, ...moduleIgnored] - } - return { ignoredExportsById } - })()) - tsrReactRefresh.ignoredExportsById.set('createRootRoute.tsx', ['Route']) -} -export function TSRFastRefreshAnchor() { - return null -} -if (import.meta.hot) { - const hotData = (import.meta.hot.data ??= {}) - const handleRouteUpdate = function handleRouteUpdate(routeId, newRoute) { - const router = window.__TSR_ROUTER__ - const oldRoute = router.routesById[routeId] - if (!oldRoute) { - return - } - const generatedRouteOptionKeys = new Set(['id', 'path', 'getParentRoute']) - const generatedRouteOptions = {} - generatedRouteOptionKeys.forEach((key) => { - if (key in oldRoute.options) { - generatedRouteOptions[key] = oldRoute.options[key] - } - }) - const oldHasShellComponent = 'shellComponent' in oldRoute.options - const newHasShellComponent = 'shellComponent' in newRoute.options - const preserveComponentIdentity = - oldHasShellComponent === newHasShellComponent - const componentKeys = [ - 'component', - 'shellComponent', - 'pendingComponent', - 'errorComponent', - 'notFoundComponent', - ] - if (preserveComponentIdentity) { - componentKeys.forEach((key) => { - if (key in oldRoute.options && key in newRoute.options) { - newRoute.options[key] = oldRoute.options[key] - } - }) - } - const nextOptions = { ...newRoute.options, ...generatedRouteOptions } - oldRoute.options = nextOptions - oldRoute.update(nextOptions) - router._replaceRouteChunk(oldRoute, newRoute.lazyFn) - router.setRoutes(router.buildRouteTree()) - syncHotRouteExport(oldRoute) - router.resolvePathCache.clear() - void router._refreshRoute?.() - function syncHotRouteExport(liveRoute) { - newRoute.options = liveRoute.options - newRoute.parentRoute = liveRoute.parentRoute - newRoute._path = liveRoute._path - newRoute._id = liveRoute._id - newRoute._fullPath = liveRoute._fullPath - newRoute._to = liveRoute._to - } - } - const initialRouteId = Route.id ?? hotData['tsr-route-id'] - if (initialRouteId) { - hotData['tsr-route-id'] = initialRouteId - } - const existingRoute = - typeof window !== 'undefined' && initialRouteId - ? window.__TSR_ROUTER__?.routesById?.[initialRouteId] - : undefined - if (initialRouteId && existingRoute && existingRoute !== Route) { - handleRouteUpdate(initialRouteId, Route) - hotData['tsr-route-update-handled'] = Route - } - import.meta.hot.accept((newModule) => { - if (Route && newModule && newModule.Route) { - const routeId = hotData['tsr-route-id'] ?? Route.id - if (routeId) { - hotData['tsr-route-id'] = routeId - } - if (hotData['tsr-route-update-handled'] === newModule.Route) { - delete hotData['tsr-route-update-handled'] - return - } - handleRouteUpdate(routeId, newModule.Route) - } - }) -} diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRouteWithContext-type-args@false.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRouteWithContext-type-args@false.tsx deleted file mode 100644 index 43f27087a6..0000000000 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRouteWithContext-type-args@false.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import * as React from 'react' -import { createRootRouteWithContext } from '@tanstack/react-router' -interface MyRouterContext { - auth: boolean -} -export const Route = createRootRouteWithContext<MyRouterContext>()({ - component: RootComponent, -}) -function RootComponent() { - return <div>Hello</div> -} diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRouteWithContext-type-args@true.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRouteWithContext-type-args@true.tsx deleted file mode 100644 index c96d6f01a5..0000000000 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRouteWithContext-type-args@true.tsx +++ /dev/null @@ -1,107 +0,0 @@ -import * as React from 'react' -import { createRootRouteWithContext } from '@tanstack/react-router' -interface MyRouterContext { - auth: boolean -} -export const Route = createRootRouteWithContext<MyRouterContext>()({ - component: RootComponent, -}) -function RootComponent() { - return <div>Hello</div> -} -if (import.meta.hot && typeof window !== 'undefined') { - import.meta.hot.data ??= {} - const tsrReactRefresh = (window.__TSR_REACT_REFRESH__ ??= (() => { - const ignoredExportsById = new Map() - const previousGetIgnoredExports = window.__getReactRefreshIgnoredExports - window.__getReactRefreshIgnoredExports = (ctx) => { - const ignoredExports = previousGetIgnoredExports?.(ctx) ?? [] - const moduleIgnored = ignoredExportsById.get(ctx.id) ?? [] - return [...ignoredExports, ...moduleIgnored] - } - return { ignoredExportsById } - })()) - tsrReactRefresh.ignoredExportsById.set( - 'createRootRouteWithContext-type-args.tsx', - ['Route'], - ) -} -export function TSRFastRefreshAnchor() { - return null -} -if (import.meta.hot) { - const hotData = (import.meta.hot.data ??= {}) - const handleRouteUpdate = function handleRouteUpdate(routeId, newRoute) { - const router = window.__TSR_ROUTER__ - const oldRoute = router.routesById[routeId] - if (!oldRoute) { - return - } - const generatedRouteOptionKeys = new Set(['id', 'path', 'getParentRoute']) - const generatedRouteOptions = {} - generatedRouteOptionKeys.forEach((key) => { - if (key in oldRoute.options) { - generatedRouteOptions[key] = oldRoute.options[key] - } - }) - const oldHasShellComponent = 'shellComponent' in oldRoute.options - const newHasShellComponent = 'shellComponent' in newRoute.options - const preserveComponentIdentity = - oldHasShellComponent === newHasShellComponent - const componentKeys = [ - 'component', - 'shellComponent', - 'pendingComponent', - 'errorComponent', - 'notFoundComponent', - ] - if (preserveComponentIdentity) { - componentKeys.forEach((key) => { - if (key in oldRoute.options && key in newRoute.options) { - newRoute.options[key] = oldRoute.options[key] - } - }) - } - const nextOptions = { ...newRoute.options, ...generatedRouteOptions } - oldRoute.options = nextOptions - oldRoute.update(nextOptions) - router._replaceRouteChunk(oldRoute, newRoute.lazyFn) - router.setRoutes(router.buildRouteTree()) - syncHotRouteExport(oldRoute) - router.resolvePathCache.clear() - void router._refreshRoute?.() - function syncHotRouteExport(liveRoute) { - newRoute.options = liveRoute.options - newRoute.parentRoute = liveRoute.parentRoute - newRoute._path = liveRoute._path - newRoute._id = liveRoute._id - newRoute._fullPath = liveRoute._fullPath - newRoute._to = liveRoute._to - } - } - const initialRouteId = Route.id ?? hotData['tsr-route-id'] - if (initialRouteId) { - hotData['tsr-route-id'] = initialRouteId - } - const existingRoute = - typeof window !== 'undefined' && initialRouteId - ? window.__TSR_ROUTER__?.routesById?.[initialRouteId] - : undefined - if (initialRouteId && existingRoute && existingRoute !== Route) { - handleRouteUpdate(initialRouteId, Route) - hotData['tsr-route-update-handled'] = Route - } - import.meta.hot.accept((newModule) => { - if (Route && newModule && newModule.Route) { - const routeId = hotData['tsr-route-id'] ?? Route.id - if (routeId) { - hotData['tsr-route-id'] = routeId - } - if (hotData['tsr-route-update-handled'] === newModule.Route) { - delete hotData['tsr-route-update-handled'] - return - } - handleRouteUpdate(routeId, newModule.Route) - } - }) -} diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/destructuring@false.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/destructuring@false.tsx index 112fded569..d80f17484f 100644 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/destructuring@false.tsx +++ b/packages/router-plugin/tests/add-hmr/snapshots/react/destructuring@false.tsx @@ -1,9 +1,11 @@ import thing from 'thing' + export function test() { const { foo: { bar: { destructured }, }, } = thing + return destructured } diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/destructuring@true.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/destructuring@true.tsx index 112fded569..d80f17484f 100644 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/destructuring@true.tsx +++ b/packages/router-plugin/tests/add-hmr/snapshots/react/destructuring@true.tsx @@ -1,9 +1,11 @@ import thing from 'thing' + export function test() { const { foo: { bar: { destructured }, }, } = thing + return destructured } diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/explicit-undefined-component@false.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/explicit-undefined-component@false.tsx index 8109a89624..4fdd9d1c68 100644 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/explicit-undefined-component@false.tsx +++ b/packages/router-plugin/tests/add-hmr/snapshots/react/explicit-undefined-component@false.tsx @@ -1,3 +1,6 @@ import React from 'react' import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/')({ component: undefined }) + +export const Route = createFileRoute('/')({ + component: undefined, +}) diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/explicit-undefined-component@true.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/explicit-undefined-component@true.tsx index 99674604fa..4c24fe967c 100644 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/explicit-undefined-component@true.tsx +++ b/packages/router-plugin/tests/add-hmr/snapshots/react/explicit-undefined-component@true.tsx @@ -1,98 +1,110 @@ -import React from 'react' -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/')({ component: undefined }) +import React from 'react'; +import { createFileRoute } from '@tanstack/react-router'; +export const Route = createFileRoute('/')({ + component: undefined +}); if (import.meta.hot && typeof window !== 'undefined') { - import.meta.hot.data ??= {} - const tsrReactRefresh = (window.__TSR_REACT_REFRESH__ ??= (() => { - const ignoredExportsById = new Map() - const previousGetIgnoredExports = window.__getReactRefreshIgnoredExports - window.__getReactRefreshIgnoredExports = (ctx) => { - const ignoredExports = previousGetIgnoredExports?.(ctx) ?? [] - const moduleIgnored = ignoredExportsById.get(ctx.id) ?? [] - return [...ignoredExports, ...moduleIgnored] - } - return { ignoredExportsById } - })()) - tsrReactRefresh.ignoredExportsById.set('explicit-undefined-component.tsx', [ - 'Route', - ]) + const tsrReactRefresh = window.__TSR_REACT_REFRESH__ ??= (() => { + const ignoredExportsById = new Map(); + const previousGetIgnoredExports = window.__getReactRefreshIgnoredExports; + window.__getReactRefreshIgnoredExports = ctx => { + const ignoredExports = previousGetIgnoredExports?.(ctx) ?? []; + const moduleIgnored = ignoredExportsById.get(ctx.id) ?? []; + return [...ignoredExports, ...moduleIgnored]; + }; + return { + ignoredExportsById + }; + })(); + tsrReactRefresh.ignoredExportsById.set("explicit-undefined-component.tsx", ['Route']); } export function TSRFastRefreshAnchor() { - return null + return null; } if (import.meta.hot) { - const hotData = (import.meta.hot.data ??= {}) - const handleRouteUpdate = function handleRouteUpdate(routeId, newRoute) { - const router = window.__TSR_ROUTER__ - const oldRoute = router.routesById[routeId] - if (!oldRoute) { - return - } - const generatedRouteOptionKeys = new Set(['id', 'path', 'getParentRoute']) - const generatedRouteOptions = {} - generatedRouteOptionKeys.forEach((key) => { - if (key in oldRoute.options) { - generatedRouteOptions[key] = oldRoute.options[key] - } - }) - const oldHasShellComponent = 'shellComponent' in oldRoute.options - const newHasShellComponent = 'shellComponent' in newRoute.options - const preserveComponentIdentity = - oldHasShellComponent === newHasShellComponent - const componentKeys = [ - 'component', - 'shellComponent', - 'pendingComponent', - 'errorComponent', - 'notFoundComponent', - ] - if (preserveComponentIdentity) { - componentKeys.forEach((key) => { - if (key in oldRoute.options && key in newRoute.options) { - newRoute.options[key] = oldRoute.options[key] - } - }) - } - const nextOptions = { ...newRoute.options, ...generatedRouteOptions } - oldRoute.options = nextOptions - oldRoute.update(nextOptions) - router._replaceRouteChunk(oldRoute, newRoute.lazyFn) - router.setRoutes(router.buildRouteTree()) - syncHotRouteExport(oldRoute) - router.resolvePathCache.clear() - void router._refreshRoute?.() - function syncHotRouteExport(liveRoute) { - newRoute.options = liveRoute.options - newRoute.parentRoute = liveRoute.parentRoute - newRoute._path = liveRoute._path - newRoute._id = liveRoute._id - newRoute._fullPath = liveRoute._fullPath - newRoute._to = liveRoute._to - } - } - const initialRouteId = Route.id ?? hotData['tsr-route-id'] - if (initialRouteId) { - hotData['tsr-route-id'] = initialRouteId - } - const existingRoute = - typeof window !== 'undefined' && initialRouteId - ? window.__TSR_ROUTER__?.routesById?.[initialRouteId] - : undefined - if (initialRouteId && existingRoute && existingRoute !== Route) { - handleRouteUpdate(initialRouteId, Route) - hotData['tsr-route-update-handled'] = Route - } - import.meta.hot.accept((newModule) => { + import.meta.hot.accept(newModule => { if (Route && newModule && newModule.Route) { - const routeId = hotData['tsr-route-id'] ?? Route.id + const routeId = import.meta.hot.data['tsr-route-id'] ?? Route.id; if (routeId) { - hotData['tsr-route-id'] = routeId + import.meta.hot.data['tsr-route-id'] = routeId; } - if (hotData['tsr-route-update-handled'] === newModule.Route) { - delete hotData['tsr-route-update-handled'] - return - } - handleRouteUpdate(routeId, newModule.Route) + (function handleRouteUpdate(routeId, newRoute) { + const router = window.__TSR_ROUTER__; + const oldRoute = router.routesById[routeId]; + if (!oldRoute) { + return; + } + ; + const removedKeys = new Set(); + Object.keys(oldRoute.options).forEach(key => { + if (!(key in newRoute.options)) { + removedKeys.add(key); + delete oldRoute.options[key]; + } + }); + const componentKeys = ["component", "shellComponent", "pendingComponent", "errorComponent", "notFoundComponent"]; + componentKeys.forEach(key => { + if (key in oldRoute.options && key in newRoute.options) { + newRoute.options[key] = oldRoute.options[key]; + } + }); + oldRoute.options = newRoute.options; + oldRoute.update(newRoute.options); + oldRoute._componentsPromise = undefined; + oldRoute._lazyPromise = undefined; + router.routesById[oldRoute.id] = oldRoute; + router.routesByPath[oldRoute.fullPath] = oldRoute; + router.processedTree.matchCache.clear(); + router.processedTree.flatCache?.clear(); + router.processedTree.singleCache.clear(); + router.resolvePathCache.clear(); + walkReplaceSegmentTree(oldRoute, router.processedTree.segmentTree); + const filter = m => m.routeId === oldRoute.id; + const activeMatch = router.stores.activeMatchesSnapshot.state.find(filter); + const pendingMatch = router.stores.pendingMatchesSnapshot.state.find(filter); + const cachedMatches = router.stores.cachedMatchesSnapshot.state.filter(filter); + if (activeMatch || pendingMatch || cachedMatches.length > 0) { + if (removedKeys.has("loader") || removedKeys.has("beforeLoad")) { + const matchIds = [activeMatch?.id, pendingMatch?.id, ...cachedMatches.map(match => match.id)].filter(Boolean); + router.batch(() => { + for (const matchId of matchIds) { + const store = router.stores.pendingMatchStoresById.get(matchId) || router.stores.activeMatchStoresById.get(matchId) || router.stores.cachedMatchStoresById.get(matchId); + if (store) { + store.setState(prev => { + const next = { + ...prev + }; + if (removedKeys.has("loader")) { + next.loaderData = undefined; + } + ; + if (removedKeys.has("beforeLoad")) { + next.__beforeLoadContext = undefined; + } + ; + return next; + }); + } + } + }); + } + ; + router.invalidate({ + filter, + sync: true + }); + } + ; + function walkReplaceSegmentTree(route, node) { + if (node.route?.id === route.id) node.route = route; + if (node.index) walkReplaceSegmentTree(route, node.index); + node.static?.forEach(child => walkReplaceSegmentTree(route, child)); + node.staticInsensitive?.forEach(child => walkReplaceSegmentTree(route, child)); + node.dynamic?.forEach(child => walkReplaceSegmentTree(route, child)); + node.optional?.forEach(child => walkReplaceSegmentTree(route, child)); + node.wildcard?.forEach(child => walkReplaceSegmentTree(route, child)); + } + })(routeId, newModule.Route); } - }) -} + }); +} \ No newline at end of file diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/function-declaration@false.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/function-declaration@false.tsx index e2b672f7b8..5d7e2181f5 100644 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/function-declaration@false.tsx +++ b/packages/router-plugin/tests/add-hmr/snapshots/react/function-declaration@false.tsx @@ -1,10 +1,9 @@ -const $$splitComponentImporter = () => - import('function-declaration.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import * as React from 'react' -import { createFileRoute } from '@tanstack/react-router' -import { fetchPosts } from '../posts' +const $$splitComponentImporter = () => import('function-declaration.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import * as React from 'react'; +import { createFileRoute } from '@tanstack/react-router'; +import { fetchPosts } from '../posts'; export const Route = createFileRoute('/posts')({ loader: fetchPosts, - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/function-declaration@true.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/function-declaration@true.tsx index 614c38c954..006868554a 100644 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/function-declaration@true.tsx +++ b/packages/router-plugin/tests/add-hmr/snapshots/react/function-declaration@true.tsx @@ -1,115 +1,118 @@ -const $$splitComponentImporter = () => - import('function-declaration.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import * as React from 'react' -import { createFileRoute } from '@tanstack/react-router' -import { fetchPosts } from '../posts' -const TSRSplitComponent = (() => { - const hot = import.meta.hot - const hotData = hot ? (hot.data ??= {}) : undefined - return ( - hotData?.['tsr-split-component:component'] ?? - lazyRouteComponent($$splitComponentImporter, 'component') - ) -})() +const $$splitComponentImporter = () => import('function-declaration.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import * as React from 'react'; +import { createFileRoute } from '@tanstack/react-router'; +import { fetchPosts } from '../posts'; +const TSRSplitComponent = import.meta.hot?.data?.["tsr-split-component:component"] ?? lazyRouteComponent($$splitComponentImporter, "component"); if (import.meta.hot) { - ;(import.meta.hot.data ??= {})['tsr-split-component:component'] = - TSRSplitComponent + import.meta.hot.data["tsr-split-component:component"] = TSRSplitComponent; } export const Route = createFileRoute('/posts')({ loader: fetchPosts, - component: TSRSplitComponent, -}) + component: TSRSplitComponent +}); if (import.meta.hot && typeof window !== 'undefined') { - import.meta.hot.data ??= {} - const tsrReactRefresh = (window.__TSR_REACT_REFRESH__ ??= (() => { - const ignoredExportsById = new Map() - const previousGetIgnoredExports = window.__getReactRefreshIgnoredExports - window.__getReactRefreshIgnoredExports = (ctx) => { - const ignoredExports = previousGetIgnoredExports?.(ctx) ?? [] - const moduleIgnored = ignoredExportsById.get(ctx.id) ?? [] - return [...ignoredExports, ...moduleIgnored] - } - return { ignoredExportsById } - })()) - tsrReactRefresh.ignoredExportsById.set('function-declaration.tsx', ['Route']) + const tsrReactRefresh = window.__TSR_REACT_REFRESH__ ??= (() => { + const ignoredExportsById = new Map(); + const previousGetIgnoredExports = window.__getReactRefreshIgnoredExports; + window.__getReactRefreshIgnoredExports = ctx => { + const ignoredExports = previousGetIgnoredExports?.(ctx) ?? []; + const moduleIgnored = ignoredExportsById.get(ctx.id) ?? []; + return [...ignoredExports, ...moduleIgnored]; + }; + return { + ignoredExportsById + }; + })(); + tsrReactRefresh.ignoredExportsById.set("function-declaration.tsx", ['Route']); } export function TSRFastRefreshAnchor() { - return null + return null; } if (import.meta.hot) { - const hotData = (import.meta.hot.data ??= {}) - const handleRouteUpdate = function handleRouteUpdate(routeId, newRoute) { - const router = window.__TSR_ROUTER__ - const oldRoute = router.routesById[routeId] - if (!oldRoute) { - return - } - const generatedRouteOptionKeys = new Set(['id', 'path', 'getParentRoute']) - const generatedRouteOptions = {} - generatedRouteOptionKeys.forEach((key) => { - if (key in oldRoute.options) { - generatedRouteOptions[key] = oldRoute.options[key] - } - }) - const oldHasShellComponent = 'shellComponent' in oldRoute.options - const newHasShellComponent = 'shellComponent' in newRoute.options - const preserveComponentIdentity = - oldHasShellComponent === newHasShellComponent - const componentKeys = [ - 'component', - 'shellComponent', - 'pendingComponent', - 'errorComponent', - 'notFoundComponent', - ] - if (preserveComponentIdentity) { - componentKeys.forEach((key) => { - if (key in oldRoute.options && key in newRoute.options) { - newRoute.options[key] = oldRoute.options[key] - } - }) - } - const nextOptions = { ...newRoute.options, ...generatedRouteOptions } - oldRoute.options = nextOptions - oldRoute.update(nextOptions) - router._replaceRouteChunk(oldRoute, newRoute.lazyFn) - router.setRoutes(router.buildRouteTree()) - syncHotRouteExport(oldRoute) - router.resolvePathCache.clear() - void router._refreshRoute?.() - function syncHotRouteExport(liveRoute) { - newRoute.options = liveRoute.options - newRoute.parentRoute = liveRoute.parentRoute - newRoute._path = liveRoute._path - newRoute._id = liveRoute._id - newRoute._fullPath = liveRoute._fullPath - newRoute._to = liveRoute._to - } - } - const initialRouteId = Route.id ?? hotData['tsr-route-id'] - if (initialRouteId) { - hotData['tsr-route-id'] = initialRouteId - } - const existingRoute = - typeof window !== 'undefined' && initialRouteId - ? window.__TSR_ROUTER__?.routesById?.[initialRouteId] - : undefined - if (initialRouteId && existingRoute && existingRoute !== Route) { - handleRouteUpdate(initialRouteId, Route) - hotData['tsr-route-update-handled'] = Route - } - import.meta.hot.accept((newModule) => { + import.meta.hot.accept(newModule => { if (Route && newModule && newModule.Route) { - const routeId = hotData['tsr-route-id'] ?? Route.id + const routeId = import.meta.hot.data['tsr-route-id'] ?? Route.id; if (routeId) { - hotData['tsr-route-id'] = routeId + import.meta.hot.data['tsr-route-id'] = routeId; } - if (hotData['tsr-route-update-handled'] === newModule.Route) { - delete hotData['tsr-route-update-handled'] - return - } - handleRouteUpdate(routeId, newModule.Route) + (function handleRouteUpdate(routeId, newRoute) { + const router = window.__TSR_ROUTER__; + const oldRoute = router.routesById[routeId]; + if (!oldRoute) { + return; + } + ; + const removedKeys = new Set(); + Object.keys(oldRoute.options).forEach(key => { + if (!(key in newRoute.options)) { + removedKeys.add(key); + delete oldRoute.options[key]; + } + }); + const componentKeys = ["component", "shellComponent", "pendingComponent", "errorComponent", "notFoundComponent"]; + componentKeys.forEach(key => { + if (key in oldRoute.options && key in newRoute.options) { + newRoute.options[key] = oldRoute.options[key]; + } + }); + oldRoute.options = newRoute.options; + oldRoute.update(newRoute.options); + oldRoute._componentsPromise = undefined; + oldRoute._lazyPromise = undefined; + router.routesById[oldRoute.id] = oldRoute; + router.routesByPath[oldRoute.fullPath] = oldRoute; + router.processedTree.matchCache.clear(); + router.processedTree.flatCache?.clear(); + router.processedTree.singleCache.clear(); + router.resolvePathCache.clear(); + walkReplaceSegmentTree(oldRoute, router.processedTree.segmentTree); + const filter = m => m.routeId === oldRoute.id; + const activeMatch = router.stores.activeMatchesSnapshot.state.find(filter); + const pendingMatch = router.stores.pendingMatchesSnapshot.state.find(filter); + const cachedMatches = router.stores.cachedMatchesSnapshot.state.filter(filter); + if (activeMatch || pendingMatch || cachedMatches.length > 0) { + if (removedKeys.has("loader") || removedKeys.has("beforeLoad")) { + const matchIds = [activeMatch?.id, pendingMatch?.id, ...cachedMatches.map(match => match.id)].filter(Boolean); + router.batch(() => { + for (const matchId of matchIds) { + const store = router.stores.pendingMatchStoresById.get(matchId) || router.stores.activeMatchStoresById.get(matchId) || router.stores.cachedMatchStoresById.get(matchId); + if (store) { + store.setState(prev => { + const next = { + ...prev + }; + if (removedKeys.has("loader")) { + next.loaderData = undefined; + } + ; + if (removedKeys.has("beforeLoad")) { + next.__beforeLoadContext = undefined; + } + ; + return next; + }); + } + } + }); + } + ; + router.invalidate({ + filter, + sync: true + }); + } + ; + function walkReplaceSegmentTree(route, node) { + if (node.route?.id === route.id) node.route = route; + if (node.index) walkReplaceSegmentTree(route, node.index); + node.static?.forEach(child => walkReplaceSegmentTree(route, child)); + node.staticInsensitive?.forEach(child => walkReplaceSegmentTree(route, child)); + node.dynamic?.forEach(child => walkReplaceSegmentTree(route, child)); + node.optional?.forEach(child => walkReplaceSegmentTree(route, child)); + node.wildcard?.forEach(child => walkReplaceSegmentTree(route, child)); + } + })(routeId, newModule.Route); } - }) -} + }); +} \ No newline at end of file diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/multi-component@false.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/multi-component@false.tsx index 456134aadc..653c0c21f5 100644 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/multi-component@false.tsx +++ b/packages/router-plugin/tests/add-hmr/snapshots/react/multi-component@false.tsx @@ -1,16 +1,11 @@ -const $$splitErrorComponentImporter = () => - import('multi-component.tsx?tsr-split=errorComponent') -const $$splitComponentImporter = () => - import('multi-component.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import * as React from 'react' -import { createFileRoute } from '@tanstack/react-router' -import { fetchPosts } from '../posts' +const $$splitErrorComponentImporter = () => import('multi-component.tsx?tsr-split=errorComponent'); +const $$splitComponentImporter = () => import('multi-component.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import * as React from 'react'; +import { createFileRoute } from '@tanstack/react-router'; +import { fetchPosts } from '../posts'; export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: lazyRouteComponent($$splitComponentImporter, 'component'), - errorComponent: lazyRouteComponent( - $$splitErrorComponentImporter, - 'errorComponent', - ), -}) + errorComponent: lazyRouteComponent($$splitErrorComponentImporter, 'errorComponent') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/multi-component@true.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/multi-component@true.tsx index 871bf352e0..df4236c39e 100644 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/multi-component@true.tsx +++ b/packages/router-plugin/tests/add-hmr/snapshots/react/multi-component@true.tsx @@ -1,130 +1,124 @@ -const $$splitErrorComponentImporter = () => - import('multi-component.tsx?tsr-split=errorComponent') -const $$splitComponentImporter = () => - import('multi-component.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import * as React from 'react' -import { createFileRoute } from '@tanstack/react-router' -import { fetchPosts } from '../posts' -const TSRSplitComponent = (() => { - const hot = import.meta.hot - const hotData = hot ? (hot.data ??= {}) : undefined - return ( - hotData?.['tsr-split-component:component'] ?? - lazyRouteComponent($$splitComponentImporter, 'component') - ) -})() +const $$splitErrorComponentImporter = () => import('multi-component.tsx?tsr-split=errorComponent'); +const $$splitComponentImporter = () => import('multi-component.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import * as React from 'react'; +import { createFileRoute } from '@tanstack/react-router'; +import { fetchPosts } from '../posts'; +const TSRSplitComponent = import.meta.hot?.data?.["tsr-split-component:component"] ?? lazyRouteComponent($$splitComponentImporter, "component"); if (import.meta.hot) { - ;(import.meta.hot.data ??= {})['tsr-split-component:component'] = - TSRSplitComponent + import.meta.hot.data["tsr-split-component:component"] = TSRSplitComponent; } -const TSRSplitErrorComponent = (() => { - const hot = import.meta.hot - const hotData = hot ? (hot.data ??= {}) : undefined - return ( - hotData?.['tsr-split-component:errorComponent'] ?? - lazyRouteComponent($$splitErrorComponentImporter, 'errorComponent') - ) -})() +const TSRSplitErrorComponent = import.meta.hot?.data?.["tsr-split-component:errorComponent"] ?? lazyRouteComponent($$splitErrorComponentImporter, "errorComponent"); if (import.meta.hot) { - ;(import.meta.hot.data ??= {})['tsr-split-component:errorComponent'] = - TSRSplitErrorComponent + import.meta.hot.data["tsr-split-component:errorComponent"] = TSRSplitErrorComponent; } export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: TSRSplitComponent, - errorComponent: TSRSplitErrorComponent, -}) + errorComponent: TSRSplitErrorComponent +}); if (import.meta.hot && typeof window !== 'undefined') { - import.meta.hot.data ??= {} - const tsrReactRefresh = (window.__TSR_REACT_REFRESH__ ??= (() => { - const ignoredExportsById = new Map() - const previousGetIgnoredExports = window.__getReactRefreshIgnoredExports - window.__getReactRefreshIgnoredExports = (ctx) => { - const ignoredExports = previousGetIgnoredExports?.(ctx) ?? [] - const moduleIgnored = ignoredExportsById.get(ctx.id) ?? [] - return [...ignoredExports, ...moduleIgnored] - } - return { ignoredExportsById } - })()) - tsrReactRefresh.ignoredExportsById.set('multi-component.tsx', ['Route']) + const tsrReactRefresh = window.__TSR_REACT_REFRESH__ ??= (() => { + const ignoredExportsById = new Map(); + const previousGetIgnoredExports = window.__getReactRefreshIgnoredExports; + window.__getReactRefreshIgnoredExports = ctx => { + const ignoredExports = previousGetIgnoredExports?.(ctx) ?? []; + const moduleIgnored = ignoredExportsById.get(ctx.id) ?? []; + return [...ignoredExports, ...moduleIgnored]; + }; + return { + ignoredExportsById + }; + })(); + tsrReactRefresh.ignoredExportsById.set("multi-component.tsx", ['Route']); } export function TSRFastRefreshAnchor() { - return null + return null; } if (import.meta.hot) { - const hotData = (import.meta.hot.data ??= {}) - const handleRouteUpdate = function handleRouteUpdate(routeId, newRoute) { - const router = window.__TSR_ROUTER__ - const oldRoute = router.routesById[routeId] - if (!oldRoute) { - return - } - const generatedRouteOptionKeys = new Set(['id', 'path', 'getParentRoute']) - const generatedRouteOptions = {} - generatedRouteOptionKeys.forEach((key) => { - if (key in oldRoute.options) { - generatedRouteOptions[key] = oldRoute.options[key] - } - }) - const oldHasShellComponent = 'shellComponent' in oldRoute.options - const newHasShellComponent = 'shellComponent' in newRoute.options - const preserveComponentIdentity = - oldHasShellComponent === newHasShellComponent - const componentKeys = [ - 'component', - 'shellComponent', - 'pendingComponent', - 'errorComponent', - 'notFoundComponent', - ] - if (preserveComponentIdentity) { - componentKeys.forEach((key) => { - if (key in oldRoute.options && key in newRoute.options) { - newRoute.options[key] = oldRoute.options[key] - } - }) - } - const nextOptions = { ...newRoute.options, ...generatedRouteOptions } - oldRoute.options = nextOptions - oldRoute.update(nextOptions) - router._replaceRouteChunk(oldRoute, newRoute.lazyFn) - router.setRoutes(router.buildRouteTree()) - syncHotRouteExport(oldRoute) - router.resolvePathCache.clear() - void router._refreshRoute?.() - function syncHotRouteExport(liveRoute) { - newRoute.options = liveRoute.options - newRoute.parentRoute = liveRoute.parentRoute - newRoute._path = liveRoute._path - newRoute._id = liveRoute._id - newRoute._fullPath = liveRoute._fullPath - newRoute._to = liveRoute._to - } - } - const initialRouteId = Route.id ?? hotData['tsr-route-id'] - if (initialRouteId) { - hotData['tsr-route-id'] = initialRouteId - } - const existingRoute = - typeof window !== 'undefined' && initialRouteId - ? window.__TSR_ROUTER__?.routesById?.[initialRouteId] - : undefined - if (initialRouteId && existingRoute && existingRoute !== Route) { - handleRouteUpdate(initialRouteId, Route) - hotData['tsr-route-update-handled'] = Route - } - import.meta.hot.accept((newModule) => { + import.meta.hot.accept(newModule => { if (Route && newModule && newModule.Route) { - const routeId = hotData['tsr-route-id'] ?? Route.id + const routeId = import.meta.hot.data['tsr-route-id'] ?? Route.id; if (routeId) { - hotData['tsr-route-id'] = routeId + import.meta.hot.data['tsr-route-id'] = routeId; } - if (hotData['tsr-route-update-handled'] === newModule.Route) { - delete hotData['tsr-route-update-handled'] - return - } - handleRouteUpdate(routeId, newModule.Route) + (function handleRouteUpdate(routeId, newRoute) { + const router = window.__TSR_ROUTER__; + const oldRoute = router.routesById[routeId]; + if (!oldRoute) { + return; + } + ; + const removedKeys = new Set(); + Object.keys(oldRoute.options).forEach(key => { + if (!(key in newRoute.options)) { + removedKeys.add(key); + delete oldRoute.options[key]; + } + }); + const componentKeys = ["component", "shellComponent", "pendingComponent", "errorComponent", "notFoundComponent"]; + componentKeys.forEach(key => { + if (key in oldRoute.options && key in newRoute.options) { + newRoute.options[key] = oldRoute.options[key]; + } + }); + oldRoute.options = newRoute.options; + oldRoute.update(newRoute.options); + oldRoute._componentsPromise = undefined; + oldRoute._lazyPromise = undefined; + router.routesById[oldRoute.id] = oldRoute; + router.routesByPath[oldRoute.fullPath] = oldRoute; + router.processedTree.matchCache.clear(); + router.processedTree.flatCache?.clear(); + router.processedTree.singleCache.clear(); + router.resolvePathCache.clear(); + walkReplaceSegmentTree(oldRoute, router.processedTree.segmentTree); + const filter = m => m.routeId === oldRoute.id; + const activeMatch = router.stores.activeMatchesSnapshot.state.find(filter); + const pendingMatch = router.stores.pendingMatchesSnapshot.state.find(filter); + const cachedMatches = router.stores.cachedMatchesSnapshot.state.filter(filter); + if (activeMatch || pendingMatch || cachedMatches.length > 0) { + if (removedKeys.has("loader") || removedKeys.has("beforeLoad")) { + const matchIds = [activeMatch?.id, pendingMatch?.id, ...cachedMatches.map(match => match.id)].filter(Boolean); + router.batch(() => { + for (const matchId of matchIds) { + const store = router.stores.pendingMatchStoresById.get(matchId) || router.stores.activeMatchStoresById.get(matchId) || router.stores.cachedMatchStoresById.get(matchId); + if (store) { + store.setState(prev => { + const next = { + ...prev + }; + if (removedKeys.has("loader")) { + next.loaderData = undefined; + } + ; + if (removedKeys.has("beforeLoad")) { + next.__beforeLoadContext = undefined; + } + ; + return next; + }); + } + } + }); + } + ; + router.invalidate({ + filter, + sync: true + }); + } + ; + function walkReplaceSegmentTree(route, node) { + if (node.route?.id === route.id) node.route = route; + if (node.index) walkReplaceSegmentTree(route, node.index); + node.static?.forEach(child => walkReplaceSegmentTree(route, child)); + node.staticInsensitive?.forEach(child => walkReplaceSegmentTree(route, child)); + node.dynamic?.forEach(child => walkReplaceSegmentTree(route, child)); + node.optional?.forEach(child => walkReplaceSegmentTree(route, child)); + node.wildcard?.forEach(child => walkReplaceSegmentTree(route, child)); + } + })(routeId, newModule.Route); } - }) -} + }); +} \ No newline at end of file diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/string-literal-keys@false.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/string-literal-keys@false.tsx index cfb23b03d2..4fc3129e14 100644 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/string-literal-keys@false.tsx +++ b/packages/router-plugin/tests/add-hmr/snapshots/react/string-literal-keys@false.tsx @@ -1,16 +1,11 @@ -const $$splitErrorComponentImporter = () => - import('string-literal-keys.tsx?tsr-split=errorComponent') -const $$splitComponentImporter = () => - import('string-literal-keys.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import * as React from 'react' -import { createFileRoute } from '@tanstack/react-router' -import { fetchPosts } from '../posts' +const $$splitErrorComponentImporter = () => import('string-literal-keys.tsx?tsr-split=errorComponent'); +const $$splitComponentImporter = () => import('string-literal-keys.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import * as React from 'react'; +import { createFileRoute } from '@tanstack/react-router'; +import { fetchPosts } from '../posts'; export const Route = createFileRoute('/posts')({ loader: fetchPosts, - component: lazyRouteComponent($$splitComponentImporter, 'component'), - errorComponent: lazyRouteComponent( - $$splitErrorComponentImporter, - 'errorComponent', - ), -}) + 'component': lazyRouteComponent($$splitComponentImporter, 'component'), + 'errorComponent': lazyRouteComponent($$splitErrorComponentImporter, 'errorComponent') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/string-literal-keys@true.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/string-literal-keys@true.tsx index 6d5b2a1fd3..3c45803585 100644 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/string-literal-keys@true.tsx +++ b/packages/router-plugin/tests/add-hmr/snapshots/react/string-literal-keys@true.tsx @@ -1,130 +1,124 @@ -const $$splitErrorComponentImporter = () => - import('string-literal-keys.tsx?tsr-split=errorComponent') -const $$splitComponentImporter = () => - import('string-literal-keys.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import * as React from 'react' -import { createFileRoute } from '@tanstack/react-router' -import { fetchPosts } from '../posts' -const TSRSplitComponent = (() => { - const hot = import.meta.hot - const hotData = hot ? (hot.data ??= {}) : undefined - return ( - hotData?.['tsr-split-component:component'] ?? - lazyRouteComponent($$splitComponentImporter, 'component') - ) -})() +const $$splitErrorComponentImporter = () => import('string-literal-keys.tsx?tsr-split=errorComponent'); +const $$splitComponentImporter = () => import('string-literal-keys.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import * as React from 'react'; +import { createFileRoute } from '@tanstack/react-router'; +import { fetchPosts } from '../posts'; +const TSRSplitComponent = import.meta.hot?.data?.["tsr-split-component:component"] ?? lazyRouteComponent($$splitComponentImporter, "component"); if (import.meta.hot) { - ;(import.meta.hot.data ??= {})['tsr-split-component:component'] = - TSRSplitComponent + import.meta.hot.data["tsr-split-component:component"] = TSRSplitComponent; } -const TSRSplitErrorComponent = (() => { - const hot = import.meta.hot - const hotData = hot ? (hot.data ??= {}) : undefined - return ( - hotData?.['tsr-split-component:errorComponent'] ?? - lazyRouteComponent($$splitErrorComponentImporter, 'errorComponent') - ) -})() +const TSRSplitErrorComponent = import.meta.hot?.data?.["tsr-split-component:errorComponent"] ?? lazyRouteComponent($$splitErrorComponentImporter, "errorComponent"); if (import.meta.hot) { - ;(import.meta.hot.data ??= {})['tsr-split-component:errorComponent'] = - TSRSplitErrorComponent + import.meta.hot.data["tsr-split-component:errorComponent"] = TSRSplitErrorComponent; } export const Route = createFileRoute('/posts')({ loader: fetchPosts, - component: TSRSplitComponent, - errorComponent: TSRSplitErrorComponent, -}) + 'component': TSRSplitComponent, + 'errorComponent': TSRSplitErrorComponent +}); if (import.meta.hot && typeof window !== 'undefined') { - import.meta.hot.data ??= {} - const tsrReactRefresh = (window.__TSR_REACT_REFRESH__ ??= (() => { - const ignoredExportsById = new Map() - const previousGetIgnoredExports = window.__getReactRefreshIgnoredExports - window.__getReactRefreshIgnoredExports = (ctx) => { - const ignoredExports = previousGetIgnoredExports?.(ctx) ?? [] - const moduleIgnored = ignoredExportsById.get(ctx.id) ?? [] - return [...ignoredExports, ...moduleIgnored] - } - return { ignoredExportsById } - })()) - tsrReactRefresh.ignoredExportsById.set('string-literal-keys.tsx', ['Route']) + const tsrReactRefresh = window.__TSR_REACT_REFRESH__ ??= (() => { + const ignoredExportsById = new Map(); + const previousGetIgnoredExports = window.__getReactRefreshIgnoredExports; + window.__getReactRefreshIgnoredExports = ctx => { + const ignoredExports = previousGetIgnoredExports?.(ctx) ?? []; + const moduleIgnored = ignoredExportsById.get(ctx.id) ?? []; + return [...ignoredExports, ...moduleIgnored]; + }; + return { + ignoredExportsById + }; + })(); + tsrReactRefresh.ignoredExportsById.set("string-literal-keys.tsx", ['Route']); } export function TSRFastRefreshAnchor() { - return null + return null; } if (import.meta.hot) { - const hotData = (import.meta.hot.data ??= {}) - const handleRouteUpdate = function handleRouteUpdate(routeId, newRoute) { - const router = window.__TSR_ROUTER__ - const oldRoute = router.routesById[routeId] - if (!oldRoute) { - return - } - const generatedRouteOptionKeys = new Set(['id', 'path', 'getParentRoute']) - const generatedRouteOptions = {} - generatedRouteOptionKeys.forEach((key) => { - if (key in oldRoute.options) { - generatedRouteOptions[key] = oldRoute.options[key] - } - }) - const oldHasShellComponent = 'shellComponent' in oldRoute.options - const newHasShellComponent = 'shellComponent' in newRoute.options - const preserveComponentIdentity = - oldHasShellComponent === newHasShellComponent - const componentKeys = [ - 'component', - 'shellComponent', - 'pendingComponent', - 'errorComponent', - 'notFoundComponent', - ] - if (preserveComponentIdentity) { - componentKeys.forEach((key) => { - if (key in oldRoute.options && key in newRoute.options) { - newRoute.options[key] = oldRoute.options[key] - } - }) - } - const nextOptions = { ...newRoute.options, ...generatedRouteOptions } - oldRoute.options = nextOptions - oldRoute.update(nextOptions) - router._replaceRouteChunk(oldRoute, newRoute.lazyFn) - router.setRoutes(router.buildRouteTree()) - syncHotRouteExport(oldRoute) - router.resolvePathCache.clear() - void router._refreshRoute?.() - function syncHotRouteExport(liveRoute) { - newRoute.options = liveRoute.options - newRoute.parentRoute = liveRoute.parentRoute - newRoute._path = liveRoute._path - newRoute._id = liveRoute._id - newRoute._fullPath = liveRoute._fullPath - newRoute._to = liveRoute._to - } - } - const initialRouteId = Route.id ?? hotData['tsr-route-id'] - if (initialRouteId) { - hotData['tsr-route-id'] = initialRouteId - } - const existingRoute = - typeof window !== 'undefined' && initialRouteId - ? window.__TSR_ROUTER__?.routesById?.[initialRouteId] - : undefined - if (initialRouteId && existingRoute && existingRoute !== Route) { - handleRouteUpdate(initialRouteId, Route) - hotData['tsr-route-update-handled'] = Route - } - import.meta.hot.accept((newModule) => { + import.meta.hot.accept(newModule => { if (Route && newModule && newModule.Route) { - const routeId = hotData['tsr-route-id'] ?? Route.id + const routeId = import.meta.hot.data['tsr-route-id'] ?? Route.id; if (routeId) { - hotData['tsr-route-id'] = routeId + import.meta.hot.data['tsr-route-id'] = routeId; } - if (hotData['tsr-route-update-handled'] === newModule.Route) { - delete hotData['tsr-route-update-handled'] - return - } - handleRouteUpdate(routeId, newModule.Route) + (function handleRouteUpdate(routeId, newRoute) { + const router = window.__TSR_ROUTER__; + const oldRoute = router.routesById[routeId]; + if (!oldRoute) { + return; + } + ; + const removedKeys = new Set(); + Object.keys(oldRoute.options).forEach(key => { + if (!(key in newRoute.options)) { + removedKeys.add(key); + delete oldRoute.options[key]; + } + }); + const componentKeys = ["component", "shellComponent", "pendingComponent", "errorComponent", "notFoundComponent"]; + componentKeys.forEach(key => { + if (key in oldRoute.options && key in newRoute.options) { + newRoute.options[key] = oldRoute.options[key]; + } + }); + oldRoute.options = newRoute.options; + oldRoute.update(newRoute.options); + oldRoute._componentsPromise = undefined; + oldRoute._lazyPromise = undefined; + router.routesById[oldRoute.id] = oldRoute; + router.routesByPath[oldRoute.fullPath] = oldRoute; + router.processedTree.matchCache.clear(); + router.processedTree.flatCache?.clear(); + router.processedTree.singleCache.clear(); + router.resolvePathCache.clear(); + walkReplaceSegmentTree(oldRoute, router.processedTree.segmentTree); + const filter = m => m.routeId === oldRoute.id; + const activeMatch = router.stores.activeMatchesSnapshot.state.find(filter); + const pendingMatch = router.stores.pendingMatchesSnapshot.state.find(filter); + const cachedMatches = router.stores.cachedMatchesSnapshot.state.filter(filter); + if (activeMatch || pendingMatch || cachedMatches.length > 0) { + if (removedKeys.has("loader") || removedKeys.has("beforeLoad")) { + const matchIds = [activeMatch?.id, pendingMatch?.id, ...cachedMatches.map(match => match.id)].filter(Boolean); + router.batch(() => { + for (const matchId of matchIds) { + const store = router.stores.pendingMatchStoresById.get(matchId) || router.stores.activeMatchStoresById.get(matchId) || router.stores.cachedMatchStoresById.get(matchId); + if (store) { + store.setState(prev => { + const next = { + ...prev + }; + if (removedKeys.has("loader")) { + next.loaderData = undefined; + } + ; + if (removedKeys.has("beforeLoad")) { + next.__beforeLoadContext = undefined; + } + ; + return next; + }); + } + } + }); + } + ; + router.invalidate({ + filter, + sync: true + }); + } + ; + function walkReplaceSegmentTree(route, node) { + if (node.route?.id === route.id) node.route = route; + if (node.index) walkReplaceSegmentTree(route, node.index); + node.static?.forEach(child => walkReplaceSegmentTree(route, child)); + node.staticInsensitive?.forEach(child => walkReplaceSegmentTree(route, child)); + node.dynamic?.forEach(child => walkReplaceSegmentTree(route, child)); + node.optional?.forEach(child => walkReplaceSegmentTree(route, child)); + node.wildcard?.forEach(child => walkReplaceSegmentTree(route, child)); + } + })(routeId, newModule.Route); } - }) -} + }); +} \ No newline at end of file diff --git a/packages/router-plugin/tests/add-hmr/snapshots/solid/arrow-function@false.tsx b/packages/router-plugin/tests/add-hmr/snapshots/solid/arrow-function@false.tsx index 10bedc87f0..b09548da57 100644 --- a/packages/router-plugin/tests/add-hmr/snapshots/solid/arrow-function@false.tsx +++ b/packages/router-plugin/tests/add-hmr/snapshots/solid/arrow-function@false.tsx @@ -1,9 +1,8 @@ -const $$splitComponentImporter = () => - import('arrow-function.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/solid-router' -import { createFileRoute } from '@tanstack/solid-router' -import { fetchPosts } from '../posts' +const $$splitComponentImporter = () => import('arrow-function.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/solid-router'; +import { createFileRoute } from '@tanstack/solid-router'; +import { fetchPosts } from '../posts'; export const Route = createFileRoute('/posts')({ loader: fetchPosts, - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/add-hmr/snapshots/solid/arrow-function@true.tsx b/packages/router-plugin/tests/add-hmr/snapshots/solid/arrow-function@true.tsx index bc531f9000..b084d4c71b 100644 --- a/packages/router-plugin/tests/add-hmr/snapshots/solid/arrow-function@true.tsx +++ b/packages/router-plugin/tests/add-hmr/snapshots/solid/arrow-function@true.tsx @@ -1,79 +1,95 @@ -const $$splitComponentImporter = () => - import('arrow-function.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/solid-router' -import { createFileRoute } from '@tanstack/solid-router' -import { fetchPosts } from '../posts' +const $$splitComponentImporter = () => import('arrow-function.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/solid-router'; +import { createFileRoute } from '@tanstack/solid-router'; +import { fetchPosts } from '../posts'; export const Route = createFileRoute('/posts')({ loader: fetchPosts, - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); if (import.meta.hot) { - const hotData = (import.meta.hot.data ??= {}) - const handleRouteUpdate = function handleRouteUpdate(routeId, newRoute) { - const router = window.__TSR_ROUTER__ - const oldRoute = router.routesById[routeId] - if (!oldRoute) { - return - } - const generatedRouteOptionKeys = new Set(['id', 'path', 'getParentRoute']) - const generatedRouteOptions = {} - generatedRouteOptionKeys.forEach((key) => { - if (key in oldRoute.options) { - generatedRouteOptions[key] = oldRoute.options[key] - } - }) - const oldHasShellComponent = 'shellComponent' in oldRoute.options - const newHasShellComponent = 'shellComponent' in newRoute.options - const preserveComponentIdentity = - oldHasShellComponent === newHasShellComponent - const componentKeys = [] - if (preserveComponentIdentity) { - componentKeys.forEach((key) => { - if (key in oldRoute.options && key in newRoute.options) { - newRoute.options[key] = oldRoute.options[key] - } - }) - } - const nextOptions = { ...newRoute.options, ...generatedRouteOptions } - oldRoute.options = nextOptions - oldRoute.update(nextOptions) - router._replaceRouteChunk(oldRoute, newRoute.lazyFn) - router.setRoutes(router.buildRouteTree()) - syncHotRouteExport(oldRoute) - router.resolvePathCache.clear() - void router._refreshRoute?.() - function syncHotRouteExport(liveRoute) { - newRoute.options = liveRoute.options - newRoute.parentRoute = liveRoute.parentRoute - newRoute._path = liveRoute._path - newRoute._id = liveRoute._id - newRoute._fullPath = liveRoute._fullPath - newRoute._to = liveRoute._to - } - } - const initialRouteId = Route.id ?? hotData['tsr-route-id'] - if (initialRouteId) { - hotData['tsr-route-id'] = initialRouteId - } - const existingRoute = - typeof window !== 'undefined' && initialRouteId - ? window.__TSR_ROUTER__?.routesById?.[initialRouteId] - : undefined - if (initialRouteId && existingRoute && existingRoute !== Route) { - handleRouteUpdate(initialRouteId, Route) - hotData['tsr-route-update-handled'] = Route - } - import.meta.hot.accept((newModule) => { + import.meta.hot.accept(newModule => { if (Route && newModule && newModule.Route) { - const routeId = hotData['tsr-route-id'] ?? Route.id + const routeId = import.meta.hot.data['tsr-route-id'] ?? Route.id; if (routeId) { - hotData['tsr-route-id'] = routeId + import.meta.hot.data['tsr-route-id'] = routeId; } - if (hotData['tsr-route-update-handled'] === newModule.Route) { - delete hotData['tsr-route-update-handled'] - return - } - handleRouteUpdate(routeId, newModule.Route) + (function handleRouteUpdate(routeId, newRoute) { + const router = window.__TSR_ROUTER__; + const oldRoute = router.routesById[routeId]; + if (!oldRoute) { + return; + } + ; + const removedKeys = new Set(); + Object.keys(oldRoute.options).forEach(key => { + if (!(key in newRoute.options)) { + removedKeys.add(key); + delete oldRoute.options[key]; + } + }); + const componentKeys = []; + componentKeys.forEach(key => { + if (key in oldRoute.options && key in newRoute.options) { + newRoute.options[key] = oldRoute.options[key]; + } + }); + oldRoute.options = newRoute.options; + oldRoute.update(newRoute.options); + oldRoute._componentsPromise = undefined; + oldRoute._lazyPromise = undefined; + router.routesById[oldRoute.id] = oldRoute; + router.routesByPath[oldRoute.fullPath] = oldRoute; + router.processedTree.matchCache.clear(); + router.processedTree.flatCache?.clear(); + router.processedTree.singleCache.clear(); + router.resolvePathCache.clear(); + walkReplaceSegmentTree(oldRoute, router.processedTree.segmentTree); + const filter = m => m.routeId === oldRoute.id; + const activeMatch = router.stores.activeMatchesSnapshot.state.find(filter); + const pendingMatch = router.stores.pendingMatchesSnapshot.state.find(filter); + const cachedMatches = router.stores.cachedMatchesSnapshot.state.filter(filter); + if (activeMatch || pendingMatch || cachedMatches.length > 0) { + if (removedKeys.has("loader") || removedKeys.has("beforeLoad")) { + const matchIds = [activeMatch?.id, pendingMatch?.id, ...cachedMatches.map(match => match.id)].filter(Boolean); + router.batch(() => { + for (const matchId of matchIds) { + const store = router.stores.pendingMatchStoresById.get(matchId) || router.stores.activeMatchStoresById.get(matchId) || router.stores.cachedMatchStoresById.get(matchId); + if (store) { + store.setState(prev => { + const next = { + ...prev + }; + if (removedKeys.has("loader")) { + next.loaderData = undefined; + } + ; + if (removedKeys.has("beforeLoad")) { + next.__beforeLoadContext = undefined; + } + ; + return next; + }); + } + } + }); + } + ; + router.invalidate({ + filter, + sync: true + }); + } + ; + function walkReplaceSegmentTree(route, node) { + if (node.route?.id === route.id) node.route = route; + if (node.index) walkReplaceSegmentTree(route, node.index); + node.static?.forEach(child => walkReplaceSegmentTree(route, child)); + node.staticInsensitive?.forEach(child => walkReplaceSegmentTree(route, child)); + node.dynamic?.forEach(child => walkReplaceSegmentTree(route, child)); + node.optional?.forEach(child => walkReplaceSegmentTree(route, child)); + node.wildcard?.forEach(child => walkReplaceSegmentTree(route, child)); + } + })(routeId, newModule.Route); } - }) -} + }); +} \ No newline at end of file diff --git a/packages/router-plugin/tests/add-hmr/test-files/react/createFileRoute-lowercase-components.tsx b/packages/router-plugin/tests/add-hmr/test-files/react/createFileRoute-lowercase-components.tsx deleted file mode 100644 index a09f8d24e2..0000000000 --- a/packages/router-plugin/tests/add-hmr/test-files/react/createFileRoute-lowercase-components.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/lowercase-components')({ - pendingComponent: pendingComponent, - errorComponent: errorComponent, - component: component, -}) - -function pendingComponent() { - return <div>Pending</div> -} - -function errorComponent() { - return <div>Error</div> -} - -function component() { - return <div>Hello</div> -} diff --git a/packages/router-plugin/tests/add-hmr/test-files/react/createRootRoute-lowercase-components.tsx b/packages/router-plugin/tests/add-hmr/test-files/react/createRootRoute-lowercase-components.tsx deleted file mode 100644 index 20c9a07798..0000000000 --- a/packages/router-plugin/tests/add-hmr/test-files/react/createRootRoute-lowercase-components.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import * as React from 'react' -import { createRootRoute } from '@tanstack/react-router' - -export const Route = createRootRoute({ - shellComponent: shellComponent, - pendingComponent: pendingComponent, - errorComponent: errorComponent, - component: component, -}) - -function shellComponent({ children }: { children: React.ReactNode }) { - return <html>{children}</html> -} - -function pendingComponent() { - return <div>Pending</div> -} - -function errorComponent() { - return <div>Error</div> -} - -function component() { - return <div>Hello</div> -} diff --git a/packages/router-plugin/tests/add-hmr/test-files/react/createRootRoute.tsx b/packages/router-plugin/tests/add-hmr/test-files/react/createRootRoute.tsx deleted file mode 100644 index e967791f8d..0000000000 --- a/packages/router-plugin/tests/add-hmr/test-files/react/createRootRoute.tsx +++ /dev/null @@ -1,10 +0,0 @@ -import * as React from 'react' -import { createRootRoute } from '@tanstack/react-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return <div>Hello</div> -} diff --git a/packages/router-plugin/tests/add-hmr/test-files/react/createRootRouteWithContext-type-args.tsx b/packages/router-plugin/tests/add-hmr/test-files/react/createRootRouteWithContext-type-args.tsx deleted file mode 100644 index 0feadacab5..0000000000 --- a/packages/router-plugin/tests/add-hmr/test-files/react/createRootRouteWithContext-type-args.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import * as React from 'react' -import { createRootRouteWithContext } from '@tanstack/react-router' - -interface MyRouterContext { - auth: boolean -} - -export const Route = createRootRouteWithContext<MyRouterContext>()({ - component: RootComponent, -}) - -function RootComponent() { - return <div>Hello</div> -} diff --git a/packages/router-plugin/tests/code-splitter-dead-code.test.ts b/packages/router-plugin/tests/code-splitter-dead-code.test.ts deleted file mode 100644 index 038f323caf..0000000000 --- a/packages/router-plugin/tests/code-splitter-dead-code.test.ts +++ /dev/null @@ -1,462 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - compileRouteModules, - declarationOf, - evaluateModule, - expectValidModules, - head, - importSources, - importedNames, - transformWithRouteHmrPlugin, -} from './regression-helpers' - -const sharedModule = 'route.tsx?tsr-shared=1' - -/** Whether a module declares `name` or imports it from the shared module. */ -function binds(module: string, name: string) { - return ( - declarationOf(name).test(module) || - importedNames(module, sharedModule).includes(name) - ) -} - -/** - * The reference module, compiled without and with React HMR: HMR rewrites the - * route options (hoisted components, refresh anchor) before dead code is - * removed, so the removal runs on a different program. - */ -function referenceModules(code: string) { - return { - reference: compileRouteModules(code).modules.reference!, - 'reference with HMR': compileRouteModules(code, { hmr: true }).modules - .reference!, - } -} - -/** - * Renders the split component the way an app loads it: the shared module (if - * any) and the reference module run first, then the component chunk, all - * linked to one instance of the shared module. A top-level statement may then - * reach the component by moving into its chunk or by staying in the - * reference module and writing to a shared binding. - */ -async function renderSplitComponent(modules: Record<string, string>) { - const stubs: Record<string, Record<string, unknown>> = {} - if (modules.shared) { - stubs[sharedModule] = await evaluateModule(modules.shared) - } - await evaluateModule(modules.reference!, { - ...stubs, - '@tanstack/react-router': { - createFileRoute: () => (options: unknown) => ({ options }), - lazyRouteComponent: () => () => null, - }, - }) - const chunk = await evaluateModule(modules['virtual component']!, stubs) - return chunk.component!() -} - -describe('the reference module only drops code that splitting left unused', () => { - it.each([ - { - name: 'a store subscription that unsubscribes itself', - setup: `import { store } from './store' -const unsubscribe = store.subscribe(() => { - if (store.state.done) unsubscribe() -})`, - declared: ['unsubscribe'], - }, - { - name: 'mutually-referencing declarations', - setup: `import { createPersister } from './persist' -const persister = createPersister({ onRestore: () => restore() }) -function restore() { - persister.restore() -}`, - declared: ['persister', 'restore'], - }, - { - // Source: babel-dead-code-elimination dead-code-elimination.test.ts "only - // eliminates newly unreferenced identifiers", "unexported circular references" - // and "SCC with external caller used -> all preserved" - name: 'unused functions, one calling a helper of the split component', - setup: `function helper() { return 'helper' } -function unused() { return helper() } -function ping(): number { return pong() } -function pong(): number { return ping() }`, - component: '<p>{helper()}</p>', - declared: ['helper', 'unused', 'ping', 'pong'], - }, - ])( - 'keeps $name that nothing used before splitting', - async ({ setup, component = '<div />', declared }) => { - const code = `${head}${setup} -export const Route = createFileRoute('/')({ component: () => ${component} }) -` - const modules = referenceModules(code) - // The validator does not report references to undeclared names. A - // binding the split component reads may come from the shared module. - for (const [module, reference] of Object.entries(modules)) { - for (const name of declared) { - expect(binds(reference, name), `${module} binds ${name}`).toBe(true) - } - } - await expectValidModules(modules) - }, - ) - - // Source: babel-dead-code-elimination dead-code-elimination.test.ts "SCC dead - // code elimination" > "arrow functions in mutual recursion -> removed" - it('moves mutually recursive helpers only the component uses, and their imports, into its chunk', async () => { - const code = `${head}import { dep } from './dep' -const ping = (n: number): number => (n > 0 ? pong(n - 1) : 0) -const pong = function (n: number): number { return n > 0 ? ping(n - 1) : dep } -export const Route = createFileRoute('/')({ - loader: () => 'data', - component: () => <p>{ping(3)}</p>, -}) -` - for (const reference of Object.values(referenceModules(code))) { - expect(reference).not.toMatch(declarationOf('ping')) - expect(reference).not.toMatch(declarationOf('pong')) - expect(importSources(reference)).not.toContain('./dep') - } - const { modules } = compileRouteModules(code) - expect(modules['virtual component']).toMatch(declarationOf('ping')) - expect(modules['virtual component']).toMatch(declarationOf('pong')) - await expectValidModules(modules) - }) - - // Source: Next.js ssg/getStaticProps/should-remove-re-exported-function-declarations-dependents-variables-functions-imports - it('keeps the import specifiers nothing used before splitting', async () => { - const { modules } = - compileRouteModules(`${head}import { used, preUnused } from 'bar' -const b = function apples() { return used } -export const Route = createFileRoute('/')({ - loader: () => 'data', - component: () => <p>{b()}</p>, -}) -`) - expect(importedNames(modules.reference!, 'bar')).toEqual(['preUnused']) - expect(modules.reference).not.toContain('apples') - expect(modules['virtual component']).toMatch(declarationOf('b')) - expect(importedNames(modules['virtual component']!, 'bar')).toContain( - 'used', - ) - await expectValidModules(modules) - }) - - // Source: React Router route-chunks-test.ts "shared imports across chunks but - // not main chunk with shared side effect usage" - it('runs a top-level call only in the reference module, even when the chunks import its callee', async () => { - const { modules } = - compileRouteModules(`${head}import { shared } from './shared' -shared('side-effect-marker') -export const Route = createFileRoute('/')({ - component: () => <div>{shared('component')}</div>, - errorComponent: () => <div>{shared('error')}</div>, -}) -`) - expect(modules.reference).toContain('side-effect-marker') - expect(modules['virtual component']).not.toContain('side-effect-marker') - expect(modules['virtual errorComponent']).not.toContain( - 'side-effect-marker', - ) - await expectValidModules(modules) - }) - - // TypeScript erases type positions, so a declaration whose binding only - // appears in a type is still live code that runs when the route loads. - it.each([ - { - name: 'the reference module', - compile: (code: string) => compileRouteModules(code).modules.reference!, - }, - { - name: 'a route module compiled for HMR', - compile: (code: string) => transformWithRouteHmrPlugin(code), - }, - ])( - 'keeps a declaration only referenced from types in $name', - async ({ compile }) => { - const output = - compile(`${head}import { registerAnalytics } from './analytics' -const analytics = registerAnalytics('/posts') -declare module './analytics' { - interface Registry { - posts: typeof analytics - } -} -export const Route = createFileRoute('/posts')({ - component: () => <p>posts</p>, -}) -`) - expect(output).toMatch(declarationOf('analytics')) - expect(output).toContain('registerAnalytics(') - await expectValidModules({ output }) - }, - ) -}) - -describe('code a split option needs moves with it', () => { - // Source: Qwik optimizer test.rs should_not_move_over_side_effects, - // example_drop_side_effects; Turbopack tree-shaker analyzer/route-kind - it.each([ - { - name: 'a compound component member assignment', - setup: `function Card({ children }) { return <div>{children}</div> } -Card.Title = function Title() { return <h1>t</h1> }`, - render: '<Card><Card.Title /></Card>', - rendered: '<div><h1>t</h1></div>', - }, - { - name: 'a registry filled by a top-level call', - setup: `const registry = new Map() -registry.set('a', 'A')`, - render: `<p>{registry.get('a')}</p>`, - rendered: '<p>A</p>', - }, - { - name: 'a compiled enum initializing a var', - setup: `var Kind: any -;(function (Kind: any) { - Kind['A'] = 'a' -})(Kind || (Kind = {}))`, - render: '<p>{Kind.A}</p>', - rendered: '<p>a</p>', - }, - ])( - 'renders a split component that relies on $name', - async ({ setup, render, rendered }) => { - const { modules } = compileRouteModules(`${head}${setup} -export const Route = createFileRoute('/')({ - component: () => ${render}, -}) -`) - await expectValidModules(modules) - expect(await renderSplitComponent(modules)).toBe(rendered) - }, - ) - - // Source: React Compiler hook-ref-callback.js and - // dont-memoize-primitive-function-call-non-escaping.js: a function shared by - // the loader and the split component declares a local it never reads. - it.each([ - { name: 'a call', initializer: 'track(id)' }, - { name: 'an optional call', initializer: 'track?.(id)' }, - ])( - 'keeps an unused local initialized by $name in a shared function', - async ({ initializer }) => { - const { modules } = - compileRouteModules(`${head}import { track } from './track' -function useShared(id) { - const unused = ${initializer} - return id -} -export const Route = createFileRoute('/')({ - loader: () => useShared('loader'), - component: () => <p>{useShared('component')}</p>, -}) -`) - const calls: Array<string> = [] - const shared = await evaluateModule(modules.shared!, { - './track': { track: (label: string) => calls.push(label) }, - }) - expect(shared.useShared!('render')).toBe('render') - expect(calls).toEqual(['render']) - }, - ) - - // Source: babel-dead-code-elimination dead-code-elimination.test.ts "object - // pattern" > "within function param" - it('keeps empty destructuring parameters of helpers moved into the chunk', async () => { - const { modules } = - compileRouteModules(`${head}function f(a: any, {}: any) { return a } -const g = (a: any, []: any) => a -export const Route = createFileRoute('/')({ - loader: () => 'data', - component: () => <p>{f.length}{g.length}</p>, -}) -`) - const chunk = await evaluateModule(modules['virtual component']!) - expect(chunk.component!()).toBe('<p>22</p>') - }) - - // Source: React Router remove-exports-test.ts "iife with dependencies" - it('moves a component created by an IIFE with its dependencies and shares the helper the loader uses too', async () => { - const { modules, sharedBindings } = - compileRouteModules(`${head}import { removedLib } from 'removed-lib' -import { keptLib } from 'kept-lib' -import { sharedLib } from 'shared-lib' -const sharedUtil = (value?: unknown) => sharedLib(value) -const removedUtil = () => sharedUtil(removedLib()) -const keptUtil = () => sharedUtil(keptLib()) -const Page = (() => { - const message = removedUtil() - return () => <div>{String(message)}</div> -})() -export const Route = createFileRoute('/')({ - loader: () => keptUtil(), - component: Page, -}) -`) - expect(sharedBindings).toEqual(['sharedUtil']) - expect(importSources(modules.reference!)).toEqual([ - '@tanstack/react-router', - 'kept-lib', - 'route.tsx?tsr-shared=1', - ]) - expect(modules.reference).not.toContain('removedUtil') - expect(importSources(modules['virtual component']!)).toEqual([ - 'removed-lib', - 'route.tsx?tsr-shared=1', - ]) - expect(modules['virtual component']).toMatch(declarationOf('Page')) - expect(importSources(modules.shared!)).toEqual(['shared-lib']) - await expectValidModules(modules) - }) - - // Source: React Router route-chunks-test.ts "isolated exported variable - // declarations sharing an export statement"; Next.js - // ssg/getStaticProps/should-remove-re-exported-variable-declarations-safe - it.each([ - { - name: 'plain declarators', - declarations: `const Page = () => <div>{chunkMessage}</div>, - main = mainMessage`, - }, - { - name: 'destructured declarators', - declarations: `const { Page } = { Page: () => <div>{chunkMessage}</div> }, - { main } = { main: mainMessage }`, - }, - ])( - 'gives each of the $name of one statement to the module that reads it', - async ({ declarations }) => { - const { modules, sharedBindings } = - compileRouteModules(`${head}import { chunkMessage, mainMessage } from './messages' -${declarations} -export const Route = createFileRoute('/')({ - loader: () => main, - component: Page, -}) -`) - expect(sharedBindings).toEqual([]) - expect(importedNames(modules.reference!, './messages')).toEqual([ - 'mainMessage', - ]) - expect(modules.reference).not.toMatch(/\bPage\b/) - expect( - importedNames(modules['virtual component']!, './messages'), - ).toEqual(['chunkMessage']) - expect(modules['virtual component']).not.toMatch(/\bmain\b/) - await expectValidModules(modules) - }, - ) - - // Source: React Router route-chunks-test.ts "exported variable declarations - // sharing an export statement" - it('shares a declarator that a sibling declarator reads', async () => { - const { modules, sharedBindings } = - compileRouteModules(`${head}import { sharedMessage } from './messages' -const Page = () => <div>{sharedMessage}</div>, - Preview = Page -export const Route = createFileRoute('/')({ - loader: () => Preview.name, - component: Page, -}) -`) - expect(sharedBindings).toEqual(['Page']) - expect(modules.shared).toMatch(declarationOf('Page')) - expect(modules.reference).toMatch(declarationOf('Preview')) - expect(importedNames(modules.reference!, sharedModule)).toEqual(['Page']) - expect(modules.reference).not.toMatch(declarationOf('Page')) - expect(modules['virtual component']).not.toMatch(declarationOf('Page')) - await expectValidModules(modules) - }) -}) - -describe('var declarations nested in top-level statements', () => { - it.each([ - { - name: 'a for loop head', - setup: 'for (var value = 0; value < 3; value++) {}', - }, - { name: 'a for-of head', setup: "for (var value of ['a']) {}" }, - { - name: 'an if block', - setup: "if (typeof window === 'undefined') { var value = 'server' }", - }, - ])( - 'stay bound in every module when $name declares a binding the loader and the component read', - async ({ setup }) => { - const { modules } = compileRouteModules(`${head}${setup} -export const Route = createFileRoute('/')({ - loader: () => value, - component: () => <div>{value}</div>, -}) -`) - // Known limitation on main: the statement runs in both modules instead - // of once in the shared module; only check that each module binds `value`. - for (const name of ['reference', 'virtual component']) { - expect(binds(modules[name]!, 'value'), `${name} binds value`).toBe(true) - } - await expectValidModules(modules) - }, - ) - - it('stay bound in the reference module when exported and read by the component', async () => { - const { modules } = - compileRouteModules(`${head}if (typeof window === 'undefined') { var flag = 'server' } -export { flag } -export const Route = createFileRoute('/')({ - component: () => <div>{flag}</div>, -}) -`) - expect(binds(modules.reference!, 'flag')).toBe(true) - await expectValidModules(modules) - }) - - // Source: babel-dead-code-elimination dead-code-elimination.test.ts "variable" - // (var bindings declared inside nested statements) - it('follow the only option that reads them', async () => { - const { modules } = - compileRouteModules(`${head}import { compute, connect } from './lib' -if (typeof window !== 'undefined') { - var flag = compute() -} -for (var index = 0; index < 3; index++) {} -{ - var block = connect() -} -export const Route = createFileRoute('/')({ - loader: () => block, - component: () => <p>{String(flag)}{index}</p>, -}) -`) - expect(modules.reference).not.toContain('compute()') - expect(modules.reference).toMatch(declarationOf('block')) - const chunk = modules['virtual component']! - expect(chunk).toMatch(declarationOf('flag')) - expect(chunk).toMatch(declarationOf('index')) - expect(chunk).not.toContain('connect()') - await expectValidModules(modules) - }) -}) - -describe('robustness', () => { - it('compiles a route with a long method chain', async () => { - // Builder APIs (schemas, query builders) produce deep left-nested calls - const chain = Array.from({ length: 200 }, (_, i) => `.add(${i})`).join('') - const { modules } = - compileRouteModules(`${head}import { builder } from './builder' -const schema = builder()${chain} -export const Route = createFileRoute('/')({ - loader: () => schema, - component: () => <div>{String(schema)}</div>, -}) -`) - expect(modules.shared).toContain('.add(199)') - await expectValidModules(modules) - }) -}) diff --git a/packages/router-plugin/tests/code-splitter-imports-exports.test.ts b/packages/router-plugin/tests/code-splitter-imports-exports.test.ts deleted file mode 100644 index e7c7a504d3..0000000000 --- a/packages/router-plugin/tests/code-splitter-imports-exports.test.ts +++ /dev/null @@ -1,359 +0,0 @@ -import { transformWithOxc } from 'vite' -import { describe, expect, it } from 'vitest' -import { - buildAndRun, - compileRouteModules, - componentChunk, - declarationOf, - evaluateModule, - expectValidModules, - exportedNames, - head, - importSources, - importedNames, - transformWithRouteHmrPlugin, -} from './regression-helpers' - -describe('each module imports only the specifiers it reads', () => { - // Source: React Router route-chunks-test.ts "functions referencing their own - // identifiers"; babel-dead-code-elimination dead-code-elimination.test.ts - // "import" > "mixed default and named" and "namespace" - it('splits default, named and namespace specifiers between the modules', async () => { - const { modules, sharedBindings } = - compileRouteModules(`${head}import defaultMessage, { targetMessage, otherMessage } from './messages' -import * as messages from './messages' -import other, * as ns from './other' -const getDefault = () => defaultMessage -const getTarget = () => targetMessage -const getOther = () => otherMessage -function getNamespaced() { - return messages.namespaced -} -export const Route = createFileRoute('/')({ - loader: () => [getOther(), other], - component: () => <div>{getDefault()}{ns.x}</div>, - errorComponent: () => <div>{getNamespaced()}</div>, - notFoundComponent: () => <div>{getTarget()}</div>, -}) -`) - expect(sharedBindings).toEqual([]) - const imports = (module: string, source: string) => - importedNames(modules[module]!, source) - expect(imports('reference', './messages')).toEqual(['otherMessage']) - expect(imports('reference', './other')).toEqual(['default']) - expect(imports('virtual component', './messages')).toEqual(['default']) - expect(imports('virtual component', './other')).toEqual(['*']) - expect(imports('virtual errorComponent', './messages')).toEqual(['*']) - expect(imports('virtual notFoundComponent', './messages')).toEqual([ - 'targetMessage', - ]) - await expectValidModules(modules) - }) - - it('moves a specifier with a string name into the chunk', async () => { - const { modules } = - compileRouteModules(`${head}import { "kebab-name" as Kebab } from './icons' -export const Route = createFileRoute('/')({ - loader: () => 'data', - component: () => <Kebab />, -}) -`) - expect(importedNames(modules['virtual component']!, './icons')).toEqual([ - 'kebab-name', - ]) - expect(importSources(modules.reference!)).not.toContain('./icons') - await expectValidModules(modules) - }) - - // Source: babel-dead-code-elimination dead-code-elimination.test.ts "import" > - // "mixed default and named: none used" and "side-effect" - it('removes an import whose specifiers all moved instead of leaving a side-effect import', async () => { - const code = `${head}import a, { b } from 'pkg' -import './styles.css' -export const Route = createFileRoute('/')({ - loader: () => 'data', - component: () => <p>{a}{b}</p>, -}) -` - const { modules } = compileRouteModules(code) - // React HMR rewrites the reference module before unused code is removed. - const hmrReference = compileRouteModules(code, { hmr: true }).modules - .reference! - for (const reference of [modules.reference!, hmrReference]) { - expect(importSources(reference)).toContain('./styles.css') - expect(importSources(reference)).not.toContain('pkg') - } - expect(importedNames(modules['virtual component']!, 'pkg')).toEqual([ - 'b', - 'default', - ]) - await expectValidModules(modules) - }) - - // With React's classic JSX runtime (`jsx: "react"` in tsconfig), JSX - // compiles to `React.createElement`, so a React import that the TypeScript - // code only uses in types must stay. - it.each([ - { name: 'split chunk', compile: componentChunk }, - { - name: 'route module compiled for HMR', - compile: (code: string) => transformWithRouteHmrPlugin(code), - }, - ])( - 'keeps the React import of the $name for classic JSX', - async ({ compile }) => { - const output = compile(`import * as React from 'react' -${head}function Page({ title = 'classic' }: { title?: React.ReactNode }) { - return <p>{title}</p> -} -export const Route = createFileRoute('/')({ component: Page }) -`) - const { code } = await transformWithOxc(output, 'module.tsx', { - jsx: { runtime: 'classic' }, - }) - expect(importedNames(code, 'react')).toEqual(['*']) - }, - ) -}) - -describe('exports of the route file', () => { - it.each([ - { name: 'as-is', exports: 'export { Foo }' }, - { name: 'renamed', exports: 'export { Foo as Bar }' }, - ])( - 'are not redeclared when they re-export an import $name', - async ({ exports }) => { - const { modules } = - compileRouteModules(`${head}import { Foo } from './foo' -${exports} -export const Route = createFileRoute('/')({ component: Page }) -function Page() { - return <Foo /> -} -`) - await expectValidModules(modules) - }, - ) - - it('are not redeclared when destructured next to a non-exported binding', async () => { - const { modules } = compileRouteModules(`${head}const { a, b } = getStuff() -export { a } -export const Route = createFileRoute('/')({ - component: () => <div>{a}{b}</div>, -}) -`) - await expectValidModules(modules) - }) - - it.each([ - { name: 'function', declaration: 'function () {\n return null\n}' }, - { name: 'class', declaration: 'class {\n x = 1\n}' }, - ])( - 'keep an anonymous default-exported $name valid in every module', - async ({ declaration }) => { - const { modules } = compileRouteModules(`${head}const cache = new Map() -function Page() { - return <div>{cache.size}</div> -} -export const Route = createFileRoute('/')({ - loader: () => cache.get('x'), - component: Page, -}) -export default ${declaration} -`) - expect(Object.keys(modules)).toContain('shared') - await expectValidModules(modules) - }, - ) - - // Source: Next.js ssg/getStaticProps/issue-31855 and multi-declarator-export - it('are imported by the chunk when declared in one statement', async () => { - const { modules } = compileRouteModules(`${head}export const a = 1, - b = 2 -export const Route = createFileRoute('/')({ - component: () => <div>{a + b}</div>, -}) -`) - expect(exportedNames(modules.reference!)).toEqual(['Route', 'a', 'b']) - const chunk = modules['virtual component']! - // From the route module, or from the shared module the route module - // re-exports them from. - expect( - [ - ...importedNames(chunk, 'route.tsx'), - ...importedNames(chunk, 'route.tsx?tsr-shared=1'), - ].sort(), - ).toEqual(['a', 'b']) - expect(chunk).not.toMatch(declarationOf('a')) - expect(chunk).not.toMatch(declarationOf('b')) - await expectValidModules(modules) - }) - - it('keep module-level re-exports in the reference module', async () => { - const { modules } = compileRouteModules(`${head}export * from './lib' -export * as lib from './lib' -export {} -const cache = new Map() -export const Route = createFileRoute('/')({ - loader: () => cache.size, - component: () => <div>{cache.size}</div>, -}) -`) - expect(modules.reference).toMatch(/export \* from ['"]\.\/lib['"]/) - expect(modules.reference).toMatch(/export \* as lib from ['"]\.\/lib['"]/) - await expectValidModules(modules) - }) -}) - -describe('TypeScript-only syntax', () => { - it('erases type-only imports and exports from the split modules', async () => { - const { modules } = - compileRouteModules(`${head}import type { User } from './types' -import { type Settings, defaults } from './settings' -export type * from './types' -export type { User } -const current: User | Settings = defaults -export const Route = createFileRoute('/')({ - loader: () => current, - component: () => <div>{String(current)}</div>, -}) -`) - expect(importedNames(modules['virtual component']!, './types')).toEqual([]) - expect(importedNames(modules.shared!, './types')).toEqual([]) - expect(importedNames(modules.shared!, './settings')).toEqual(['defaults']) - await expectValidModules(modules) - }) - - // Ambient declarations (`declare ...`) have no runtime binding: the - // environment provides the value (a <script> tag, a bundler define, a global). - it.each([ - { - name: 'a declare function', - declaration: 'declare function track(event: string): void', - use: 'track("x")', - }, - { - name: 'an exported declare function', - declaration: 'export declare function track(event: string): void', - use: 'track("x")', - }, - { - name: 'a declare enum', - declaration: 'declare enum Flags { On = 1 }', - use: 'Flags.On', - }, - { - name: 'a declare namespace', - declaration: - 'declare namespace Analytics { function track(event: string): void }', - use: 'Analytics.track("x")', - }, - ])( - 'does not share $name that the loader and the component read', - async ({ declaration, use }) => { - const { modules, sharedBindings } = - compileRouteModules(`${head}${declaration} -export const Route = createFileRoute('/ambient')({ - loader: () => ${use}, - component: () => <button onClick={() => ${use}}>track</button>, -}) -`) - expect(sharedBindings).toEqual([]) - await expectValidModules(modules) - }, - ) - - it('keeps the namespace import that an import alias refers to', () => { - const chunk = componentChunk(`${head}import * as lib from './lib' -import Helper = lib.Helper -export const Route = createFileRoute('/')({ - component: () => <div>{Helper.x}</div>, -}) -`) - expect(importedNames(chunk, './lib')).toEqual(['*']) - expect(chunk).toMatch(/\bHelper\s*=\s*lib\.Helper\b/) - }) - - // Source: Qwik optimizer test.rs example_ts_enums, example_exports - it('gives the split component the enum and the overloaded function it uses', async () => { - const { modules } = compileRouteModules(`${head}enum Tone { Loud = 'LOUD' } -function label(value: string): string -function label(value: unknown) { return 'label:' + String(value) } -export const Route = createFileRoute('/')({ - loader: () => 'data', - component: () => <p>{[Tone.Loud, label('x')].join('|')}</p>, -}) -`) - await expectValidModules(modules) - const chunk = await evaluateModule(modules['virtual component']!) - expect(chunk.component!()).toBe('<p>LOUD|label:x</p>') - }) - - // TypeScript lets a type and a value share a name; exporting both is valid. - it.each([ - { - name: 'a type alias and an export specifier', - exports: `export type Post = { id: string } -function Post(id: string): Post { - return { id } -} -export { Post }`, - }, - { - name: 'a type re-export and a value re-export', - exports: `export type { Post } from './post-types' -export { Post } from './post-values'`, - }, - ])( - 'exports a type and a value with the same name: $name', - async ({ exports }) => { - const code = `${head}${exports} -export const Route = createFileRoute('/posts')({ - component: () => <p>posts</p>, -}) -` - const { modules } = compileRouteModules(code) - expect(exportedNames(modules.reference!)).toContain('Post') - expect(exportedNames(transformWithRouteHmrPlugin(code))).toContain('Post') - await expectValidModules(modules) - }, - ) - - it('keeps decorators before `export` for legacy decorator transforms', () => { - // TypeScript `experimentalDecorators` and Babel `decorators-legacy` only - // accept decorators before the `export` keyword. - const { reference } = - compileRouteModules(`${head}@observable export class Store { @observable count = 0 } -export const Route = createFileRoute('/')({ component: () => <div /> }) -`).modules - expect(reference).toMatch(/@observable\s+export class Store\b/) - }) - - it('compiles a decorator after `export`', async () => { - // TypeScript accepts `export @dec class` with or without - // `experimentalDecorators`; the tsconfig makes Vite lower the decorator - // so the built app runs in Node. The route file is read and its - // component split. - const result = await buildAndRun( - `${head}function tag(value: any) { - value.label = 'decorated' - return value -} -export @tag class Store {} -export const Route = createFileRoute('/')({ - component: () => <p>{(Store as any).label}</p>, -}) -`, - `const component = entry.Route.options.component -return [entry.Store.label, typeof component.preload, await entry.render(component)]`, - { - files: { - 'tsconfig.json': JSON.stringify({ - compilerOptions: { experimentalDecorators: true }, - }), - }, - }, - ) - expect(result).toEqual(['decorated', 'function', '<p>decorated</p>']) - }) -}) diff --git a/packages/router-plugin/tests/code-splitter-jsx.test.ts b/packages/router-plugin/tests/code-splitter-jsx.test.ts deleted file mode 100644 index 0718a5da2a..0000000000 --- a/packages/router-plugin/tests/code-splitter-jsx.test.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' -import path from 'node:path' -import { createServer } from 'vite' -import { expect, it } from 'vitest' -import { tanstackRouter } from '../src/vite' - -it.each(['Widget', '_Widget', '$Widget'])( - 'preserves the shared JSX component %s across separate loader and component chunks', - async (name) => { - // Keep the temporary app inside the package so runtime imports resolve. - const root = await mkdtemp(path.join(__dirname, '.jsx-reference-')) - let server: Awaited<ReturnType<typeof createServer>> | undefined - try { - await mkdir(path.join(root, 'routes')) - await writeFile( - path.join(root, 'routes/__root.tsx'), - `import { createRootRoute } from '@tanstack/react-router' -export const Route = createRootRoute({})`, - ) - await writeFile( - path.join(root, 'routes/widget.tsx'), - `import React from 'react' -import { createFileRoute } from '@tanstack/react-router' -const ${name} = () => 'hello' -export const Route = createFileRoute('/widget')({ - loader: () => ${name}, - component: () => <${name} />, -})`, - ) - server = await createServer({ - root, - configFile: false, - logLevel: 'silent', - server: { watch: null }, - plugins: [ - tanstackRouter({ - target: 'react', - routesDirectory: './routes', - generatedRouteTree: './routeTree.gen.ts', - autoCodeSplitting: true, - codeSplittingOptions: { - addHmr: false, - defaultBehavior: [['loader'], ['component']], - }, - }), - ], - }) - // The physical module establishes shared ownership before chunks load. - await server.ssrLoadModule('/routes/widget.tsx') - const componentModule = await server.ssrLoadModule( - '/routes/widget.tsx?tsr-split=component', - ) - const loaderModule = await server.ssrLoadModule( - '/routes/widget.tsx?tsr-split=loader', - ) - const element = componentModule.component() - expect(typeof element.type).toBe('function') - expect(element.type()).toBe('hello') - expect(loaderModule.loader()()).toBe('hello') - } finally { - await server?.close() - await rm(root, { recursive: true, force: true }) - } - }, - 30_000, -) diff --git a/packages/router-plugin/tests/code-splitter-module-state.test.ts b/packages/router-plugin/tests/code-splitter-module-state.test.ts deleted file mode 100644 index e9da5473cf..0000000000 --- a/packages/router-plugin/tests/code-splitter-module-state.test.ts +++ /dev/null @@ -1,175 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - buildAndRun, - compileRouteModules, - declarationOf, - expectValidModules, - head, - importSources, -} from './regression-helpers' - -/** How many times `pattern` occurs across all emitted modules. */ -function countAcrossModules(modules: Record<string, string>, pattern: RegExp) { - return Object.values(modules).reduce( - (count, code) => - count + (code.match(new RegExp(pattern.source, 'g'))?.length ?? 0), - 0, - ) -} - -describe('split chunks keep the module state the route relies on', () => { - // Route files commonly export a store or helpers over private state next to - // the route and use them from the route component as well. - it('renders a split component using exported bindings over private state like the unsplit route', async () => { - const result = await buildAndRun( - `${head}const state = { count: 0 } -export function increment() { - return ++state.count -} -let renders = 0 -export function getRenders() { - return renders -} -const initial = 0 -export const store = { count: initial } -function Page() { - increment() - renders++ - store.count++ - return <p>{[state.count, getRenders(), store.count - initial].join('/')}</p> -} -export const Route = createFileRoute('/')({ component: Page }) -`, - `const component = entry.Route.options.component -return [await entry.render(component), await entry.render(component), entry.store.count]`, - ) - // Known limitation on main: the chunk gets its own copy of `state` and - // `renders`, so callers of the exported functions are not checked here. - // `store.count` is 2: the chunk mutated the store the route module exports - expect(result).toEqual(['<p>1/1/1</p>', '<p>2/2/2</p>', 2]) - }, 30_000) - - // Source: Qwik optimizer test.rs - // should_keep_non_migrated_binding_from_shared_destructuring_declarator_with_default (+ _with_rest) - it('evaluates a destructuring split between the loader and the component once', async () => { - const { modules } = - compileRouteModules(`${head}import { makeConfig } from './config' -const { a = 'A', ...b } = makeConfig() -export const Route = createFileRoute('/')({ - loader: () => a, - component: () => <div>{JSON.stringify(b)}</div>, -}) -`) - expect(countAcrossModules(modules, /makeConfig\(\)/)).toBe(1) - await expectValidModules(modules) - }) - - // Source: Qwik optimizer test.rs root_level_self_referential_qrl, - // example_self_referential_component_migration - it('declares mutually recursive components used by two lazy chunks once', async () => { - const { modules } = - compileRouteModules(`${head}function A({ depth }) { return depth ? <B depth={depth - 1} /> : <i>a</i> } -function B({ depth }) { return <b><A depth={depth} /></b> } -export const Route = createFileRoute('/')({ - component: () => <A depth={1} />, - errorComponent: () => <B depth={0} />, -}) -`) - expect(countAcrossModules(modules, /function A\b/)).toBe(1) - expect(countAcrossModules(modules, /function B\b/)).toBe(1) - await expectValidModules(modules) - }) - - it('shares a class with a static block and private members', async () => { - const { modules, sharedBindings } = - compileRouteModules(`${head}class Counter { - static created = 0 - static { Counter.created = 1 } - #n = 0 - increment() { return ++this.#n } - static owns(value: object) { return #n in value } -} -const counter = new Counter() -export const Route = createFileRoute('/')({ - loader: () => counter.increment(), - component: () => <div>{String(Counter.owns(counter))}</div>, -}) -`) - expect(sharedBindings).toEqual(['Counter', 'counter']) - expect(modules['virtual component']).not.toMatch(declarationOf('Counter')) - await expectValidModules(modules) - }) - - // Source: Turbopack tree-shaker analyzer/nanoid, analyzer/let-bug-1 - it('shares a let that a shared helper reassigns', async () => { - const { modules, sharedBindings } = - compileRouteModules(`${head}let pool: Array<number> = [], offset = 0 -const fill = () => { pool = [offset++] } -export const Route = createFileRoute('/')({ - loader: () => { fill(); return pool }, - component: () => { fill(); return <p>{pool.join()}</p> }, -}) -`) - expect(sharedBindings).toEqual(['fill', 'offset', 'pool']) - expect(modules.reference).not.toMatch(declarationOf('pool')) - expect(modules['virtual component']).not.toMatch(declarationOf('pool')) - await expectValidModules(modules) - }) -}) - -describe('split chunks keep reassigned bindings next to their writers', () => { - // Source: React Router route-chunks-test.ts "reassignment"; babel-dead-code-elimination - // find-removable-bindings.test.ts "constant violations mark as external" - it('moves a binding that only the split component reassigns into its chunk', async () => { - const { modules, sharedBindings } = - compileRouteModules(`${head}import { next } from './next' -let current = 'initial-marker' -export const Route = createFileRoute('/')({ - loader: () => 'data', - component: () => { - current = next - return <p>{current}</p> - }, -}) -`) - expect(sharedBindings).toEqual([]) - expect(modules.reference).not.toContain('initial-marker') - expect(importSources(modules.reference!)).not.toContain('./next') - expect(modules['virtual component']).toMatch(declarationOf('current')) - expect(modules['virtual component']).toContain('initial-marker') - await expectValidModules(modules) - }) - - // Source: Next.js ssg/getStaticProps/should-support-babel-style-memoized-function - it.each([ - { name: 'the component', loader: `'data'`, shared: [] }, - { - name: 'the loader and the component', - loader: 'fetchData()', - shared: ['fetchData'], - }, - ])( - 'keeps a self-reassigning function used by $name valid', - async ({ loader, shared }) => { - const { modules, sharedBindings } = - compileRouteModules(`${head}function fetchData() { - fetchData = function () { - return 'memoized' - } - return fetchData.apply(this, arguments as any) -} -export const Route = createFileRoute('/')({ - loader: () => ${loader}, - component: () => <div>{fetchData()}</div>, -}) -`) - expect(sharedBindings).toEqual(shared) - const owner = shared.length - ? modules.shared! - : modules['virtual component']! - expect(owner).toMatch(declarationOf('fetchData')) - expect(owner).toContain('fetchData = function') - await expectValidModules(modules) - }, - ) -}) diff --git a/packages/router-plugin/tests/code-splitter-plugin-pipeline.test.ts b/packages/router-plugin/tests/code-splitter-plugin-pipeline.test.ts deleted file mode 100644 index dca96bfa28..0000000000 --- a/packages/router-plugin/tests/code-splitter-plugin-pipeline.test.ts +++ /dev/null @@ -1,231 +0,0 @@ -import path from 'node:path' -import { describe, expect, it } from 'vitest' -import { normalizePath } from '../src/core/utils' -import { - createCodeSplitterTransforms, - expectValidModules, - importSources, - routeFile, - transformWithRouteHmrPlugin, -} from './regression-helpers' -import { getModuleErrors } from './validate-module' -import type { Config } from '../src/core/config' -import type { HmrStyle } from '../src/core/hmr' - -const routeSource = (name: string) => ` -import { createFileRoute } from '@tanstack/react-router' -const state = { name: ${JSON.stringify(name)} } -export const Route = createFileRoute('/${name}')({ - loader: () => state, - head: () => ({ meta: [{ title: state.name }] }), - component: () => <p>{state.name}</p>, - errorComponent: () => <p>error in ${name}</p>, -}) -` - -describe('code-splitter plugin pipeline', () => { - it('compiles a split module the same way when its id has extra query parameters', async () => { - const file = routeFile('query') - const code = routeSource('query') - const splitter = await createCodeSplitterTransforms( - {}, - { [file]: '/query' }, - ) - expect(splitter.reference(code, file)).toContain('tsr-split=component') - - const virtual = splitter.virtual(code, `${file}?tsr-split=component`) - expect(virtual).toContain('state.name') - expect(splitter.virtual(code, `${file}?tsr-split=component&t=123`)).toBe( - virtual, - ) - expect(splitter.virtual(code, `${file}?t=123&tsr-split=component`)).toBe( - virtual, - ) - const shared = splitter.shared(code, `${file}?tsr-shared=1`) - expect(shared).toContain('"query"') - expect(splitter.shared(code, `${file}?tsr-shared=1&t=123`)).toBe(shared) - }) - - it('compiles the split modules of a route with its own shared bindings after another route', async () => { - const files = { - shared: routeFile('shared'), - unshared: routeFile('unshared'), - } - const splitter = await createCodeSplitterTransforms( - {}, - { [files.shared]: '/shared', [files.unshared]: '/unshared' }, - ) - const code = routeSource('shared') - // Bundlers transform the route modules first, then the chunks they import. - splitter.reference(code, files.shared) - splitter.reference( - `import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/unshared')({ component: () => <p /> }) -`, - files.unshared, - ) - const component = splitter.virtual( - code, - `${files.shared}?tsr-split=component`, - )! - expect(importSources(component)).toContain(`${files.shared}?tsr-shared=1`) - expect(splitter.shared(code, `${files.shared}?tsr-shared=1`)).toContain( - '"shared"', - ) - }) - - it('splits by the plugin-level splitBehavior for the route id', async () => { - const file = routeFile('behavior') - const code = routeSource('behavior') - const splitter = await createCodeSplitterTransforms( - { - codeSplittingOptions: { - splitBehavior: ({ routeId }) => - routeId === '/behavior' - ? [['loader', 'component', 'errorComponent']] - : undefined, - }, - }, - { [file]: '/behavior' }, - ) - const reference = splitter.reference(code, file)! - expect(reference).toContain('tsr-split=component---errorComponent---loader') - expect(reference).not.toMatch(/tsr-split=component["']/) - const virtual = splitter.virtual( - code, - `${file}?tsr-split=component---errorComponent---loader`, - )! - expect(virtual).toContain('error in behavior') - expect(await getModuleErrors(virtual)).toEqual([]) - }) - - it('rejects invalid splitBehavior groupings', async () => { - const file = routeFile('invalid') - const splitter = await createCodeSplitterTransforms( - { - codeSplittingOptions: { - splitBehavior: () => [['component'], ['component']], - }, - }, - { [file]: '/invalid' }, - ) - expect(() => splitter.reference(routeSource('invalid'), file)).toThrow( - 'The groupings returned when using `splitBehavior` for the route', - ) - }) - - it('passes the deleteNodes option to the reference compiler', async () => { - const file = routeFile('deleted') - const splitter = await createCodeSplitterTransforms( - { codeSplittingOptions: { deleteNodes: ['head'] } }, - { [file]: '/deleted' }, - ) - const reference = splitter.reference(routeSource('deleted'), file)! - expect(reference).not.toContain('head') - expect(reference).toContain('loader') - }) - - it('reports a split module id without a split value', async () => { - const file = routeFile('missing') - const splitter = await createCodeSplitterTransforms( - {}, - { [file]: '/missing' }, - ) - expect(() => - splitter.virtual(routeSource('missing'), `${file}?tsr-split=`), - ).toThrow('The split value for the virtual route') - }) - - it('leaves a shared module id alone when its route has no shared bindings', async () => { - const file = routeFile('unshared') - const code = ` -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/unshared')({ - component: () => <p>unshared</p>, -}) -` - const splitter = await createCodeSplitterTransforms( - {}, - { [file]: '/unshared' }, - ) - expect(splitter.reference(code, file)).toContain('tsr-split=component') - expect(splitter.shared(code, `${file}?tsr-shared=1`)).toBeNull() - }) - - // File names from real apps: optional segments, pathless groups and escaped dots. - it.each([ - 'src/routes/{-$locale}/changelog.tsx', - 'src/routes/(marketing)/about.tsx', - 'src/routes/api/[.]well-known/security[.]txt.tsx', - ])('imports the split modules of %s by its id', async (name) => { - const file = normalizePath(path.join(process.cwd(), name)) - const code = routeSource('route') - const splitter = await createCodeSplitterTransforms( - {}, - { [file]: '/route' }, - ) - const modules = { - reference: splitter.reference(code, file)!, - component: splitter.virtual(code, `${file}?tsr-split=component`)!, - shared: splitter.shared(code, `${file}?tsr-shared=1`)!, - } - expect(modules.reference).toContain(`${file}?tsr-split=component`) - expect(importSources(modules.reference)).toContain(`${file}?tsr-shared=1`) - expect(importSources(modules.component)).toContain(`${file}?tsr-shared=1`) - await expectValidModules(modules) - }) - - it('only checks the plugin order when the router plugin is in the resolved config', async () => { - const reactPlugin = { name: 'vite:react-babel' } - const routerPlugin = { - name: 'tanstack-router:code-splitter:compile-reference-file', - } - await expect( - createCodeSplitterTransforms({}, {}, [reactPlugin]), - ).resolves.toBeDefined() - await expect( - createCodeSplitterTransforms({}, {}, [reactPlugin, routerPlugin]), - ).rejects.toThrow('Plugin order error') - }) -}) - -describe('route HMR plugin without code splitting', () => { - function transformWith( - options: Partial<Config> & { target: 'solid' | 'vue' }, - hmrStyle?: HmrStyle, - ) { - const code = ` -import { createFileRoute } from '@tanstack/${options.target}-router' -export const Route = createFileRoute('/hmr')({ - component: () => <p>hmr</p>, -}) -` - return transformWithRouteHmrPlugin( - code, - options, - { file: routeFile('hmr'), routeId: '/hmr' }, - hmrStyle, - ) - } - - it.each(['solid', 'vue'] as const)( - 'appends Vite HMR handling to %s routes without changing them', - async (target) => { - const output = transformWith({ target }) - expect(output).toContain('import.meta.hot') - expect(output).toContain('"/hmr"') - expect(output).toContain('<p>hmr</p>') - expect(output).not.toContain('TSRComponent') - expect(await getModuleErrors(output)).toEqual([]) - }, - ) - - it('uses webpack HMR with the generated route id for non-React routes', async () => { - const output = transformWith({ target: 'solid' }, 'webpack') - expect(output).toContain('import.meta.webpackHot') - expect(output).not.toContain('import.meta.hot.') - expect(output).toContain('"/hmr"') - expect(output).not.toContain('__react_refresh_utils__') - expect(await getModuleErrors(output)).toEqual([]) - }) -}) diff --git a/packages/router-plugin/tests/code-splitter-pragmas.test.ts b/packages/router-plugin/tests/code-splitter-pragmas.test.ts deleted file mode 100644 index 265a787bb0..0000000000 --- a/packages/router-plugin/tests/code-splitter-pragmas.test.ts +++ /dev/null @@ -1,124 +0,0 @@ -import { transformWithOxc } from 'vite' -import { describe, expect, it } from 'vitest' -import { - compileRouteModules, - componentChunk, - head, - transformWithRouteHmrPlugin, -} from './regression-helpers' - -const styledRoute = ( - header: string, -) => `${header}export const Route = createFileRoute('/pragma')({ - component: () => <div css={{ color: 'red' }}>styled</div>, -}) -` - -/** Compiles JSX like Vite 8 (Oxc) does, with React's automatic runtime by default. */ -async function compileJsx(code: string) { - const { code: javascript } = await transformWithOxc(code, 'chunk.tsx', { - jsx: { runtime: 'automatic', importSource: 'react' }, - }) - return javascript -} - -/** The JSX runtime module a compiled module imports, if any. */ -async function jsxRuntimeOf(code: string) { - return (await compileJsx(code)).match( - /from ["']([^"']+\/jsx-(?:dev-)?runtime)["']/, - )?.[1] -} - -// JSX pragmas apply per module: the code splitter runs before the bundler's -// JSX transform, which then runs on each split module separately, so a module -// without the pragma compiles its JSX with the project default runtime (e.g. -// `css` props are no longer handled by Emotion). -describe('split modules keep file-level JSX pragmas', () => { - it.each([ - ['on the first import', `/** @jsxImportSource @emotion/react */\n${head}`], - ['as a line comment', `// @jsxImportSource @emotion/react\n${head}`], - [ - 'inside a file header', - `/**\n * Header\n * @jsxImportSource @emotion/react\n */\n${head}`, - ], - ])('keeps @jsxImportSource %s in effect', async (_, header) => { - const chunk = componentChunk(styledRoute(header)) - expect(chunk).toContain('@jsxImportSource @emotion/react') - expect(await jsxRuntimeOf(chunk)).toBe('@emotion/react/jsx-runtime') - }) - - it('keeps @jsxImportSource written after the imports', () => { - // Oxc only reads leading pragmas; esbuild and Babel read them anywhere. - const chunk = componentChunk( - styledRoute(`${head}/** @jsxImportSource @emotion/react */\n`), - ) - expect(chunk).toContain('@jsxImportSource @emotion/react') - }) - - it('keeps @jsxRuntime classic and @jsx pragmas in effect', async () => { - const chunk = componentChunk( - styledRoute(`/** @jsxRuntime classic */ -/** @jsx jsx */ -${head}import { jsx } from '@emotion/react' -`), - ) - expect(await jsxRuntimeOf(chunk)).toBeUndefined() - expect(await compileJsx(chunk)).toMatch(/\bjsx\(\s*["']div["']/) - }) - - it('keeps the pragma in effect in a shared module that contains JSX', async () => { - const { shared } = - compileRouteModules(`/** @jsxImportSource @emotion/react */ -${head}const icon = <svg css={{ width: 1 }} /> -export const Route = createFileRoute('/pragma')({ - loader: () => ({ icon }), - component: () => <div css={{ color: 'red' }}>{icon}</div>, -}) -`).modules - expect(await jsxRuntimeOf(shared!)).toBe('@emotion/react/jsx-runtime') - }) -}) - -// React Refresh and solid-refresh read these comments per module, so every -// module holding route code must keep them. -describe('split modules keep HMR pragma comments', () => { - const solidHead = `import { createFileRoute } from '@tanstack/solid-router'\n` - const page = `function Page() { - return <p>page</p> -} -export const Route = createFileRoute('/')({ component: Page }) -` - it.each([ - { - // Source: React Refresh ReactFreshIntegration-test "resets state on every - // edit with @refresh reset annotation" - name: 'a /* @refresh reset */ file header for React Refresh', - target: 'react', - code: `/* @refresh reset */\n${head}${page}`, - pragma: '@refresh reset', - }, - { - // Source: solid-refresh tests/client/vite.test.ts "@refresh reload should work" - name: 'a // @refresh reload file header for solid-refresh', - target: 'solid', - code: `// @refresh reload\n${solidHead}${page}`, - pragma: '@refresh reload', - }, - { - // Source: solid-refresh tests/client/vite.test.ts "should skip - // FunctionDeclaration with @refresh reload" - name: 'a // @refresh reload comment above the split component', - target: 'solid', - code: `${solidHead}// @refresh reload\n${page}`, - pragma: '@refresh reload', - }, - ] as const)('keeps $name', ({ target, code, pragma }) => { - expect(transformWithRouteHmrPlugin(code, { target })).toContain(pragma) - const { modules } = compileRouteModules(code, { - hmr: true, - targetFramework: target, - }) - expect(modules.reference).toContain(pragma) - expect(modules['virtual component']).toContain(pragma) - }) -}) diff --git a/packages/router-plugin/tests/code-splitter-route-options.test.ts b/packages/router-plugin/tests/code-splitter-route-options.test.ts deleted file mode 100644 index 84d24392d1..0000000000 --- a/packages/router-plugin/tests/code-splitter-route-options.test.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - compileRouteModules, - declarationOf, - expectValidModules, - head, - importSources, - importedNames, -} from './regression-helpers' - -describe('route options', () => { - it('are split when declared in a variable', async () => { - const { modules } = - compileRouteModules(`${head}import { fetchPosts } from './api' -function Posts() { - return <ul>{Route.useLoaderData().length}</ul> -} -const options = { - loader: () => fetchPosts(), - component: Posts, -} -export const Route = createFileRoute('/posts')(options) -`) - expect(modules.reference).toContain('tsr-split=component') - expect(modules.reference).not.toMatch(declarationOf('Posts')) - expect(importedNames(modules.reference!, './api')).toEqual(['fetchPosts']) - const chunk = modules['virtual component']! - expect(chunk).toMatch(declarationOf('Posts')) - // The split component reads the Route singleton from the reference module - expect(importedNames(chunk, 'route.tsx')).toEqual(['Route']) - expect(importSources(chunk)).not.toContain('./api') - await expectValidModules(modules) - }) - - it('that repeat a split key are split like the runtime object: the last one wins', async () => { - const { modules } = - compileRouteModules(`${head}export const Route = createFileRoute('/')({ - component: () => <div>first-marker</div>, - component: () => <div>last-marker</div>, -}) -`) - expect(modules['virtual component']).toContain('last-marker') - expect(modules['virtual component']).not.toContain('first-marker') - await expectValidModules(modules) - }) -}) - -describe('split options that read the Route singleton', () => { - // `Route` stays in the reference module, so reading it from a split option - // must not attribute every dependency of the route options to that option. - it.each([ - { - name: 'an inline arrow component', - component: `() => <p>{format(Route.useLoaderData().length)}</p>`, - }, - { - name: 'an inline named function component', - component: `function Posts() { - const { page } = Route.useSearch() - return <p>{format(page)}</p> - }`, - }, - ])( - 'share only what the loader and $name both read', - async ({ component }) => { - const { modules, sharedBindings } = - compileRouteModules(`${head}const format = (value: unknown) => String(value) -const prefix = 'post:' -function fetchPosts() { - return [prefix + 1] -} -export const Route = createFileRoute('/posts')({ - loader: () => [fetchPosts(), format(0)], - component: ${component}, -}) -`) - expect(sharedBindings).toEqual(['format']) - expect(modules.reference).toMatch(declarationOf('fetchPosts')) - expect(modules.reference).toMatch(declarationOf('prefix')) - await expectValidModules(modules) - }, - ) - - it('do not turn a reassigned loader-only binding into an import', () => { - const { modules, sharedBindings } = - compileRouteModules(`${head}let label = 'initial' -label = 'updated' -export const Route = createFileRoute('/label')({ - loader: () => label, - component: () => <p>{Route.useLoaderData()}</p>, -}) -`) - expect(sharedBindings).toEqual([]) - // An imported binding is read-only: `label = ...` would throw at runtime - expect(modules.reference).toMatch(declarationOf('label')) - expect(importSources(modules.reference!)).toEqual([ - '@tanstack/react-router', - ]) - }) - - it('never share a destructuring whose sibling depends on Route', async () => { - const { modules, sharedBindings } = - compileRouteModules(`${head}const getRoute = () => Route -const [cache, routeGetter] = [new Map(), getRoute] -export const Route = createFileRoute('/')({ - loader: () => cache.size, - component: () => <div>{cache.size}{typeof routeGetter}</div>, -}) -`) - // Intended trade-off (packages/router-plugin/AGENTS.md): bindings that - // depend on `Route` are never shared, so each module that reads `cache` - // creates its own copy. - expect(sharedBindings).toEqual([]) - await expectValidModules(modules) - }) -}) diff --git a/packages/router-plugin/tests/code-splitter-runtime.test.ts b/packages/router-plugin/tests/code-splitter-runtime.test.ts deleted file mode 100644 index 0eb9b52ea5..0000000000 --- a/packages/router-plugin/tests/code-splitter-runtime.test.ts +++ /dev/null @@ -1,161 +0,0 @@ -import { execFile } from 'node:child_process' -import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' -import path from 'node:path' -import { promisify } from 'node:util' -import { pathToFileURL } from 'node:url' -import { build } from 'vite' -import { expect, it } from 'vitest' -import { tanstackRouter } from '../src/vite' -import type { CodeSplitGroupings } from '../src/core/constants' - -const runNode = promisify(execFile) -const fixture = path.resolve( - __dirname, - 'code-splitter/test-files/react/shared-runtime.tsx', -) - -const groupings: Array<{ name: string; groupings: CodeSplitGroupings }> = [ - { name: 'eager loader', groupings: [['component']] }, - { name: 'separate lazy loader', groupings: [['component'], ['loader']] }, - { name: 'combined lazy loader', groupings: [['component', 'loader']] }, -] - -it.each(groupings)( - 'preserves executable route contracts with $name', - assertRuntimeContracts, - 30_000, -) - -// Shared extraction currently duplicates named default function declarations and -// drops TypeScript enum/namespace dependencies. Keep their intended contracts. -it.fails.each(['named-default', 'enum', 'namespace'] as const)( - 'preserves executable route contracts with shared %s declarations', - async (syntax) => { - await assertRuntimeContracts({ - groupings: [['component'], ['loader']], - syntax, - }) - }, - 30_000, -) - -async function assertRuntimeContracts({ - groupings, - syntax, -}: { - groupings: CodeSplitGroupings - syntax?: 'named-default' | 'enum' | 'namespace' -}) { - // Keep the temporary app inside the package so real runtime imports resolve. - const root = await mkdtemp(path.join(__dirname, '.runtime-contract-')) - try { - await mkdir(path.join(root, 'routes')) - let source = await readFile(fixture, 'utf8') - if (syntax === 'named-default') { - source = source - .replace( - 'function createSeed()', - 'export default function createSeed()', - ) - .replace('export default createSeed', '') - } else if (syntax === 'enum') { - source = source.replace( - 'const Count = { Initial: 0 }', - 'enum Count { Initial = 0 }', - ) - } else if (syntax === 'namespace') { - source = source.replace( - "const Labels = { component: 'count' }", - "namespace Labels { export const component = 'count' }", - ) - } - await writeFile(path.join(root, 'routes/shared-runtime.tsx'), source) - await writeFile( - path.join(root, 'routes/__root.tsx'), - `import { createRootRoute } from '@tanstack/react-router' -export const Route = createRootRoute({})`, - ) - await writeFile( - path.join(root, 'entry.ts'), - `import { createElement } from 'react' -import { renderToString } from 'react-dom/server' -import { Route } from './routes/shared-runtime' -export { Route, firstState, secondState, 'odd-name' } from './routes/shared-runtime' -export function render() { - return renderToString(createElement(Route.options.component)) -}`, - ) - - await build({ - root, - configFile: false, - logLevel: 'silent', - plugins: [ - tanstackRouter({ - target: 'react', - routesDirectory: './routes', - generatedRouteTree: './routeTree.gen.ts', - autoCodeSplitting: true, - codeSplittingOptions: { - addHmr: false, - defaultBehavior: groupings, - }, - }), - ], - build: { - ssr: path.join(root, 'entry.ts'), - outDir: 'dist', - minify: false, - sourcemap: true, - rollupOptions: { - output: { - entryFileNames: 'entry.mjs', - chunkFileNames: '[name].mjs', - }, - }, - }, - }) - - const throwLine = - source.split('\n').findIndex((line) => line.includes('throw new Error')) + - 1 - const entryUrl = pathToFileURL(path.join(root, 'dist/entry.mjs')).href - const combined = groupings.some( - (group) => group.includes('component') && group.includes('loader'), - ) - const { stdout } = await runNode(process.execPath, [ - '--enable-source-maps', - '--input-type=module', - '--eval', - `import assert from 'node:assert/strict' -const messages = [] -console.log = (message) => messages.push(message) -const { Route, render, firstState, secondState, 'odd-name': oddState } = await import(${JSON.stringify(entryUrl)}) -assert.deepEqual(messages, ['shared-runtime:seed', 'shared-runtime:state', 'shared-runtime:reference']) -const state = Route.options.beforeLoad({}) -assert.strictEqual(firstState, state) -assert.strictEqual(secondState, state) -assert.strictEqual(oddState, state) -assert.equal(state.count, 0) -assert.strictEqual(await Route.options.loader({}), state) -assert.equal(state.count, 1) -assert.deepEqual(messages, ${JSON.stringify(combined ? ['shared-runtime:seed', 'shared-runtime:state', 'shared-runtime:reference', 'shared-runtime:component'] : ['shared-runtime:seed', 'shared-runtime:state', 'shared-runtime:reference'])}) -await Route.options.component.preload() -assert.equal(render(), 'count:1') -assert.strictEqual(await Route.options.loader({}), state) -assert.equal(render(), 'count:2') -await Route.options.component.preload() -assert.deepEqual(messages, ['shared-runtime:seed', 'shared-runtime:state', 'shared-runtime:reference', 'shared-runtime:component']) -await Route.options.loader({}) -assert.throws(render, (error) => { - assert.equal(error.message, 'route source-map contract') - assert.match(error.stack, /shared-runtime\\.tsx(?:\\?[^\\n:]+)?:${throwLine}:/) - return true -}) -process.stdout.write('route contracts passed')`, - ]) - expect(stdout).toBe('route contracts passed') - } finally { - await rm(root, { recursive: true, force: true }) - } -} diff --git a/packages/router-plugin/tests/code-splitter-scope.test.ts b/packages/router-plugin/tests/code-splitter-scope.test.ts deleted file mode 100644 index 95cb80a9f9..0000000000 --- a/packages/router-plugin/tests/code-splitter-scope.test.ts +++ /dev/null @@ -1,339 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - compileRouteModules, - declarationOf, - evaluateModule, - expectValidModules, - head, - importSources, - importedNames, -} from './regression-helpers' - -const pageRoute = (body: string) => `${head}${body} -export const Route = createFileRoute('/')({ component: Page }) -` - -describe('a split component keeps the module bindings it reads', () => { - it.each([ - { - // Source: @vitejs/plugin-rsc hoist/function-hoist-block.js - name: 'past a function declared in a nested block', - body: `const value = 'outer' -function Page() { - const seen = value - { - function value() {} - } - return seen -}`, - 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', - body: `const value = 'outer' -function Page(props, seen = value) { - var value = 'inner' - return seen + ':' + value -}`, - expected: 'outer:inner', - }, - { - // Source: @vitejs/plugin-rsc scope/label.js - name: 'next to a label of the same name', - body: `const value = 'outer' -function Page() { - value: for (const item of [1]) { - if (item) { - break value - } - } - return value -}`, - expected: 'outer', - }, - { - // Source: @vitejs/plugin-rsc hoist/catch-binding-shadow.js; React Compiler try-catch-* fixtures - name: 'next to a catch parameter of the same name', - body: `const err = { message: 'outer' } -function Page() { - const readOuter = () => err.message - try { - throw new Error('inner') - } catch (err) { - return err.message + ':' + readOuter() - } -}`, - expected: 'inner:outer', - }, - { - // Source: @vitejs/plugin-rsc hoist/computed-destructuring-key-captures-outer-binding.js - name: 'through a computed destructuring key', - body: `const key = 'value' -function Page() { - const { [key]: picked } = { value: 'picked' } - return picked -}`, - expected: 'picked', - }, - { - // Source: React Compiler destructure-*-default fixtures - name: 'from parameter destructuring defaults', - body: `const fallback = 'fb' -function Page({ title = fallback, items: [first = fallback.toUpperCase()] = [] }) { - return <p>{title}{first}</p> -}`, - expected: '<p>fbFB</p>', - }, - { - // Source: React Compiler optional-call-chain-*.js - name: 'through optional call chains', - body: `const helpers = { format: (v) => '[' + v + ']' } -function Page() { - return <p>{helpers?.format?.('a')}{helpers.missing?.(1) ?? '-'}</p> -}`, - expected: '<p>[a]-</p>', - }, - { - // Source: React Compiler tagged-template-literal.js - name: 'as a template tag', - body: `const tag = (strings, ...values) => strings.raw.join('|') + values.join(',') -function Page() { - return <p>{tag\`a\${1}b\${2}c\`}</p> -}`, - expected: '<p>a|b|c1,2</p>', - }, - { - // Source: React Compiler class fixtures; @vitejs/plugin-rsc hoist/class-declaration-in-body.js - name: 'from the static block of a local class', - body: `const base = 2 -function Page() { - class Counter { - static start - static { - Counter.start = base * 2 - } - #n = Counter.start - get n() { - return this.#n - } - } - return <p>{new Counter().n}</p> -}`, - expected: '<p>4</p>', - }, - ])('$name', async ({ body, expected }) => { - const { modules } = compileRouteModules(pageRoute(body)) - await expectValidModules(modules) - const chunk = await evaluateModule(modules['virtual component']!) - expect(chunk.component!({})).toBe(expected) - }) -}) - -describe('names a route option declares itself do not reference module bindings', () => { - it.each([ - { - // Source: Next.js ssg/getStaticProps/should-not-mix-up-bindings - name: 'locals and a named function expression in the split component', - options: `loader: () => [label, format()], - component: () => { - const label = 'local' - const obj = { a: function format(x: number) { return x } } - return <div>{label}{obj.a(1)}</div> - },`, - }, - { - // Source: Next.js ssg/getServerSideProps/query-usage - name: 'a local in the loader', - options: `loader: () => { - const label = 'local' - return label - }, - component: () => <div>{label}{format()}</div>,`, - }, - { - // Source: Next.js ssg/getServerSideProps/query-usage - name: 'destructured parameters', - options: `loader: ({ label }: any) => [label, format()], - component: ({ format }: any) => <div>{format}{label}</div>,`, - }, - { - // Source: Qwik optimizer test.rs should_not_auto_export_var_shadowed_in_{catch,do_while,switch,labeled_block} - name: 'block-scoped names in the split component', - options: `loader: () => [label, format()], - component: ({ kind }: any) => { - try { JSON.parse(kind) } catch (label) { console.log(label) } - let i = 0 - do { const label = i; i += label + 1 } while (i < 3) - switch (kind) { case 'a': { const label = 'case'; console.log(label) } } - block: { const format = 'labeled'; if (format) break block } - return <p>{i}</p> - },`, - }, - ])('$name', async ({ options }) => { - const { modules, sharedBindings } = - compileRouteModules(`${head}import { load } from './load' -const label = load() -function format() { return 'format' } -export const Route = createFileRoute('/')({ - ${options} -}) -`) - // A name both options really read would be shared between them. - expect(sharedBindings).toEqual([]) - await expectValidModules(modules) - }) - - // Source: Next.js ssg/getStaticProps/should-not-remove-import-used-in-render - it('neither do intrinsic tag and attribute names, unlike component tags and JSX expressions', async () => { - const { modules, sharedBindings } = - compileRouteModules(`${head}import { A, B } from './ui' -import { load } from './load' -const a = load() -const p = load() -const label = load() -export const Route = createFileRoute('/')({ - loader: () => [a, p, label], - component: () => ( - <p label="x" title={<A />}> - <a href="/">home</a> - <B.Deep.C /> - </p> - ), -}) -`) - expect(sharedBindings).toEqual([]) - expect(importedNames(modules['virtual component']!, './ui')).toEqual([ - 'A', - 'B', - ]) - expect(importSources(modules.reference!)).not.toContain('./ui') - await expectValidModules(modules) - }) - - // Source: React Router route-chunks-test.ts "computed object property" - it('neither do object keys, unlike computed keys', async () => { - const { modules, sharedBindings } = - compileRouteModules(`${head}import { load } from './load' -const label = load() -const kind = 'kind' -export const Route = createFileRoute('/')({ - loader: () => [label, kind], - component: () => { - const obj = { label: 1, [kind]: 2 } - return <div>{obj.label}</div> - }, -}) -`) - expect(sharedBindings).toEqual(['kind']) - await expectValidModules(modules) - }) -}) - -describe('imports read in nested positions follow the code that reads them', () => { - // Source: React Router route-chunks-test.ts "default argument", "destructured - // argument with default value", "for...of with destructuring and default - // value", "try catch" and "generator function"; Turbopack tree-shaker analyzer/typeof-1 - it.each([ - { - name: 'a default parameter', - helper: 'const read = (value = x) => value', - }, - { - name: 'a destructuring default', - helper: 'const read = ([{ value }] = [{ value: x }]) => value', - }, - { - name: 'a for-of destructuring default', - helper: `const read = () => { - for (const { value = x } of [{}]) { - return value - } -}`, - }, - { - name: 'a catch clause', - helper: `const read = () => { - try { - throw 0 - } catch { - return x - } -}`, - }, - { name: 'a generator', helper: 'const read = function* () { yield x }' }, - { name: 'a typeof operand', helper: 'const read = () => typeof x' }, - ])('$name', async ({ helper }) => { - const { modules } = compileRouteModules(`${head}import { x } from './x' -${helper} -export const Route = createFileRoute('/')({ - loader: () => 'data', - component: () => <p>{String(read())}</p>, -}) -`) - expect(modules['virtual component']).toMatch(declarationOf('read')) - expect(importedNames(modules['virtual component']!, './x')).toEqual(['x']) - expect(importSources(modules.reference!)).not.toContain('./x') - await expectValidModules(modules) - }) - - it.each([ - { - // Source: @vitejs/plugin-rsc hoist/function-hoist-block.js - name: 'past a function declared in a nested block', - loader: `() => { - { - function store() {} - } - return store.value -}`, - }, - { - // Source: @vitejs/plugin-rsc scope/param-default-var-hoisting.js - name: 'from a parameter default next to a var of the same name', - loader: `(ctx, value = store.value) => { - var store = 'local' - return value -}`, - }, - { - // Source: @vitejs/plugin-rsc hoist/catch-binding-shadow.js - name: 'in a try block whose catch parameter shadows it', - loader: `() => { - try { - return store.value - } catch (store) { - return store - } -}`, - }, - ])('keeps an import the loader reads $name', async ({ loader }) => { - const { modules } = - compileRouteModules(`${head}import { store } from './store' -function Page() { - return 'page' -} -export const Route = createFileRoute('/')({ loader: ${loader}, component: Page }) -`) - expect(importedNames(modules.reference!, './store')).toEqual(['store']) - await expectValidModules(modules) - }) -}) - -describe('plain JavaScript route files', () => { - // In JavaScript, `a < b > (c)` is two comparisons, not a call with a type - // argument, so `b` is a value the expression reads. - it('reads every operand of a chained comparison', () => { - const { sharedBindings } = compileRouteModules( - `${head}const a = 1, b = 2, c = 3 -const r = a < b > (c) -export const Route = createFileRoute('/compare')({ - loader: () => r, - component: () => <p>{String(r)}</p>, -}) -`, - { filename: 'route.js' }, - ) - expect(sharedBindings).toEqual(['a', 'b', 'c', 'r']) - }) -}) diff --git a/packages/router-plugin/tests/code-splitter.test.ts b/packages/router-plugin/tests/code-splitter.test.ts index 96807e4d42..5a68f9453f 100644 --- a/packages/router-plugin/tests/code-splitter.test.ts +++ b/packages/router-plugin/tests/code-splitter.test.ts @@ -18,11 +18,9 @@ import { expandTransitively, removeBindingsDependingOnRoute, } from '../src/core/code-splitter/compilers' -import { createIdentifier } from '@tanstack/router-utils' +import { createIdentifier } from '../src/core/code-splitter/path-ids' import { defaultCodeSplitGroupings } from '../src/core/constants' -import { getFrameworkHmrCompilerPlugins } from '../src/core/code-splitter/plugins/framework-plugins' import { frameworks } from './constants' -import { formatSnapshot } from './format-snapshot' import type { CodeSplitGroupings } from '../src/core/constants' function getFrameworkDir(framework: string) { @@ -88,9 +86,7 @@ describe('code-splitter works', () => { sharedBindings.size > 0 ? sharedBindings : undefined, }) - await expect( - await formatSnapshot(compileResult?.code || code, filename), - ).toMatchFileSnapshot( + await expect(compileResult?.code || code).toMatchFileSnapshot( path.join(dirs.snapshots, groupName, filename), ) }, @@ -123,9 +119,9 @@ describe('code-splitter works', () => { groupName, `${filename.replace('.tsx', '')}@${ident}.tsx`, ) - await expect( - await formatSnapshot(splitResult.code, filename), - ).toMatchFileSnapshot(snapshotFilename) + await expect(splitResult.code).toMatchFileSnapshot( + snapshotFilename, + ) } }, ) @@ -159,9 +155,9 @@ describe('code-splitter works', () => { filename: `${filename}?tsr-shared=1`, }) - await expect( - await formatSnapshot(sharedResult.code, filename), - ).toMatchFileSnapshot(snapshotFilename) + await expect(sharedResult.code).toMatchFileSnapshot( + snapshotFilename, + ) }, ) }, @@ -169,62 +165,6 @@ describe('code-splitter works', () => { }) }) -describe('React Refresh virtual route compiler plugin', () => { - const splitComponentCases = [ - { splitType: 'component', splitIdentifier: 'SplitComponent' }, - { - splitType: 'pendingComponent', - splitIdentifier: 'SplitPendingComponent', - }, - { splitType: 'errorComponent', splitIdentifier: 'SplitErrorComponent' }, - ] as const - - function createRouteCode(splitType: string) { - return ` -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/')({ ${splitType} }) - -function ${splitType}() { - return <div>lowercase function declaration</div> -} -` - } - - it.each(splitComponentCases)( - 'renames a lowercase $splitType binding when HMR is enabled', - ({ splitType, splitIdentifier }) => { - const result = compileCodeSplitVirtualRoute({ - code: createRouteCode(splitType), - filename: `lowercase-function-declaration.tsx?tsr-split=${splitType}`, - splitTargets: [splitType], - compilerPlugins: getFrameworkHmrCompilerPlugins({ - targetFramework: 'react', - }), - }) - - expect(result.code).toContain(`function ${splitIdentifier}()`) - expect(result.code).toContain( - `export { ${splitIdentifier} as ${splitType} }`, - ) - }, - ) - - it.each(splitComponentCases)( - 'keeps a lowercase $splitType binding when HMR is disabled', - ({ splitType }) => { - const result = compileCodeSplitVirtualRoute({ - code: createRouteCode(splitType), - filename: `lowercase-function-declaration.tsx?tsr-split=${splitType}`, - splitTargets: [splitType], - }) - - expect(result.code).toContain(`function ${splitType}()`) - expect(result.code).toContain(`export { ${splitType} }`) - }, - ) -}) - describe('computeSharedBindings fast paths', () => { it('returns empty when only one split group is present (default groupings)', () => { const code = ` diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/arrow-function.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/arrow-function.tsx index 994c89e7b2..48e3768224 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/arrow-function.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/arrow-function.tsx @@ -1,10 +1,9 @@ -const $$splitComponentImporter = () => - import('arrow-function.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import * as React from 'react' -import { createFileRoute } from '@tanstack/react-router' -import { fetchPosts } from '../posts' +const $$splitComponentImporter = () => import('arrow-function.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import * as React from 'react'; +import { createFileRoute } from '@tanstack/react-router'; +import { fetchPosts } from '../posts'; export const Route = createFileRoute('/posts')({ loader: fetchPosts, - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/arrow-function@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/arrow-function@component.tsx index e36e48f495..7fe3edee11 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/arrow-function@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/arrow-function@component.tsx @@ -1,31 +1,27 @@ -import * as React from 'react' -import { Link, Outlet } from '@tanstack/react-router' -import { Route } from 'arrow-function.tsx' +import * as React from 'react'; +import { Link, Outlet } from '@tanstack/react-router'; +import { Route } from "arrow-function.tsx"; const PostsComponent = () => { - const posts = Route.useLoaderData() - return ( - <div className="p-2 flex gap-2"> + const posts = Route.useLoaderData(); + return <div className="p-2 flex gap-2"> <ul className="list-disc pl-4"> - {[...posts, { id: 'i-do-not-exist', title: 'Non-existent Post' }]?.map( - (post) => { - return ( - <li key={post.id} className="whitespace-nowrap"> - <Link - to="/posts/$postId" - params={{ postId: post.id }} - className="block py-1 text-blue-800 hover:text-blue-600" - activeProps={{ className: 'text-black font-bold' }} - > + {[...posts, { + id: 'i-do-not-exist', + title: 'Non-existent Post' + }]?.map(post => { + return <li key={post.id} className="whitespace-nowrap"> + <Link to="/posts/$postId" params={{ + postId: post.id + }} className="block py-1 text-blue-800 hover:text-blue-600" activeProps={{ + className: 'text-black font-bold' + }}> <div>{post.title.substring(0, 20)}</div> </Link> - </li> - ) - }, - )} + </li>; + })} </ul> <hr /> <Outlet /> - </div> - ) -} -export { PostsComponent as component } + </div>; +}; +export { PostsComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/arrow-function@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/arrow-function@errorComponent.tsx index 371dc65868..5f67a6fff1 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/arrow-function@errorComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/arrow-function@errorComponent.tsx @@ -1 +1 @@ -import * as React from 'react' +import * as React from 'react'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/arrow-function@notFoundComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/arrow-function@notFoundComponent.tsx index 371dc65868..5f67a6fff1 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/arrow-function@notFoundComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/arrow-function@notFoundComponent.tsx @@ -1 +1 @@ -import * as React from 'react' +import * as React from 'react'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/boolean-null-literals.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/boolean-null-literals.tsx index 5544bb15d4..771fd14f8b 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/boolean-null-literals.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/boolean-null-literals.tsx @@ -1,11 +1,13 @@ -const $$splitComponentImporter = () => - import('boolean-null-literals.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/router' +const $$splitComponentImporter = () => import('boolean-null-literals.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/router'; + // Test errorComponent with false literal export const Route = createFileRoute('/test')({ component: lazyRouteComponent($$splitComponentImporter, 'component'), errorComponent: false, pendingComponent: null, - loader: async () => ({ data: 'test' }), -}) + loader: async () => ({ + data: 'test' + }) +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/boolean-null-literals@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/boolean-null-literals@component.tsx index 557105b6a3..c49c9e93a3 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/boolean-null-literals@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/boolean-null-literals@component.tsx @@ -1,3 +1,3 @@ // Test errorComponent with false literal -const SplitComponent = () => <div>Test Component</div> -export { SplitComponent as component } +const SplitComponent = () => <div>Test Component</div>; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/chinese.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/chinese.tsx index 35a6bda2b1..2ffcfaa9a2 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/chinese.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/chinese.tsx @@ -1,10 +1,10 @@ -const $$splitComponentImporter = () => import('chinese.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import * as React from 'react' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('chinese.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import * as React from 'react'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/')({ - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); interface DemoProps { - title: string -} + title: string; +} \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/chinese@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/chinese@component.tsx index 2ac1fa54ff..003ca944a1 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/chinese@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/chinese@component.tsx @@ -1,27 +1,23 @@ -import * as React from 'react' +import * as React from 'react'; function HomeComponent() { - return ( - <div className="p-2"> + return <div className="p-2"> <Demo title="标题很好看,谁说不是呢?" /> <Demo title="The title looks great, who can deny that?" /> - </div> - ) + </div>; } interface DemoProps { - title: string + title: string; } -function Demo({ title }: DemoProps) { - return ( - <h1 - style={{ - color: '#2969ff', - fontSize: '2rem', - fontWeight: 'bold', - letterSpacing: '3px', - }} - > +function Demo({ + title +}: DemoProps) { + return <h1 style={{ + color: '#2969ff', + fontSize: '2rem', + fontWeight: 'bold', + letterSpacing: '3px' + }}> {title} - </h1> - ) + </h1>; } -export { HomeComponent as component } +export { HomeComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/chinese@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/chinese@errorComponent.tsx index cbcea8cc40..b4de370f4e 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/chinese@errorComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/chinese@errorComponent.tsx @@ -1,4 +1,4 @@ -import * as React from 'react' +import * as React from 'react'; interface DemoProps { - title: string -} + title: string; +} \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/chinese@notFoundComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/chinese@notFoundComponent.tsx index cbcea8cc40..b4de370f4e 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/chinese@notFoundComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/chinese@notFoundComponent.tsx @@ -1,4 +1,4 @@ -import * as React from 'react' +import * as React from 'react'; interface DemoProps { - title: string -} + title: string; +} \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/circular-reference-arrow-function.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/circular-reference-arrow-function.tsx index d367391005..6ec23e8d1c 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/circular-reference-arrow-function.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/circular-reference-arrow-function.tsx @@ -1,7 +1,6 @@ -const $$splitComponentImporter = () => - import('circular-reference-arrow-function.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('circular-reference-arrow-function.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/')({ - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/circular-reference-arrow-function@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/circular-reference-arrow-function@component.tsx index 59c5b5eec2..39ace71ebe 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/circular-reference-arrow-function@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/circular-reference-arrow-function@component.tsx @@ -1,17 +1,19 @@ function getComponentName(obj: Record<string, unknown>): string { - return Object.keys(obj)[0] + return Object.keys(obj)[0]; } const App = () => { - const componentName = getComponentName({ App }) - return ( - <div> + const componentName = getComponentName({ + App + }); + return <div> Component Name is {componentName} <OtherComponent /> - </div> - ) -} + </div>; +}; function OtherComponent() { - const componentName = getComponentName({ App }) - return <div>App component name is {componentName}</div> + const componentName = getComponentName({ + App + }); + return <div>App component name is {componentName}</div>; } -export { App as component } +export { App as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/circular-reference-function.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/circular-reference-function.tsx index f2e0c96476..202ef21eb3 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/circular-reference-function.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/circular-reference-function.tsx @@ -1,7 +1,6 @@ -const $$splitComponentImporter = () => - import('circular-reference-function.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('circular-reference-function.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/')({ - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/circular-reference-function@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/circular-reference-function@component.tsx index 22fbb8669f..96a753ad8a 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/circular-reference-function@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/circular-reference-function@component.tsx @@ -1,17 +1,19 @@ function getComponentName(obj: Record<string, unknown>): string { - return Object.keys(obj)[0] + return Object.keys(obj)[0]; } function App() { - const componentName = getComponentName({ App }) - return ( - <div> + const componentName = getComponentName({ + App + }); + return <div> Component Name is {componentName} <OtherComponent /> - </div> - ) + </div>; } function OtherComponent() { - const componentName = getComponentName({ App }) - return <div>App component name is {componentName}</div> + const componentName = getComponentName({ + App + }); + return <div>App component name is {componentName}</div>; } -export { App as component } +export { App as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/conditional-properties.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/conditional-properties.tsx index 927bb2e738..70385cd749 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/conditional-properties.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/conditional-properties.tsx @@ -1,11 +1,10 @@ -const $$splitComponentImporter = () => - import('conditional-properties.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' -import { isEnabled } from '@features/feature-flags' -import TrueImport from '@modules/true-component' -import { falseLoader } from '@modules/false-component' +const $$splitComponentImporter = () => import('conditional-properties.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; +import { isEnabled } from '@features/feature-flags'; +import TrueImport from '@modules/true-component'; +import { falseLoader } from '@modules/false-component'; export const Route = createFileRoute('/posts')({ component: lazyRouteComponent($$splitComponentImporter, 'component'), - loader: isEnabled ? TrueImport.loader : falseLoader, -}) + loader: isEnabled ? TrueImport.loader : falseLoader +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/conditional-properties@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/conditional-properties@component.tsx index e460c54467..aaf3410c69 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/conditional-properties@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/conditional-properties@component.tsx @@ -1,5 +1,5 @@ -import { isEnabled } from '@features/feature-flags' -import TrueImport from '@modules/true-component' -import { FalseComponent } from '@modules/false-component' -const SplitComponent = isEnabled ? TrueImport.Component : FalseComponent -export { SplitComponent as component } +import { isEnabled } from '@features/feature-flags'; +import TrueImport from '@modules/true-component'; +import { FalseComponent } from '@modules/false-component'; +const SplitComponent = isEnabled ? TrueImport.Component : FalseComponent; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-export-multiple.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-export-multiple.tsx index 31c6033aae..dcf67bfcb4 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-export-multiple.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-export-multiple.tsx @@ -1,13 +1,15 @@ -const $$splitComponentImporter = () => - import('destructured-export-multiple.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('destructured-export-multiple.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const getConfig = () => ({ baseUrl: 'https://api.example.com', - timeout: 5000, -}) -export const { baseUrl, timeout } = getConfig() -export const [first, second] = [1, 2] + timeout: 5000 +}); +export const { + baseUrl, + timeout +} = getConfig(); +export const [first, second] = [1, 2]; export const Route = createFileRoute('/about')({ - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-export-multiple@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-export-multiple@component.tsx index 6a15a59c0a..9441b5a689 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-export-multiple@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-export-multiple@component.tsx @@ -1,10 +1,8 @@ -import { baseUrl, timeout } from 'destructured-export-multiple.tsx' +import { baseUrl, timeout } from "destructured-export-multiple.tsx"; function AboutComponent() { - return ( - <div> + return <div> <p>Base URL: {baseUrl}</p> <p>Timeout: {timeout}</p> - </div> - ) + </div>; } -export { AboutComponent as component } +export { AboutComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-export-nested.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-export-nested.tsx index 5022580478..6793123b2f 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-export-nested.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-export-nested.tsx @@ -1,16 +1,19 @@ -const $$splitComponentImporter = () => - import('destructured-export-nested.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('destructured-export-nested.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; const getConfig = () => ({ - api: { baseUrl: 'https://api.example.com' }, + api: { + baseUrl: 'https://api.example.com' + }, timeout: 5000, - extra: 'data', -}) + extra: 'data' +}); export const { - api: { baseUrl }, + api: { + baseUrl + }, ...rest -} = getConfig() +} = getConfig(); export const Route = createFileRoute('/about')({ - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-export-nested@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-export-nested@component.tsx index 9bc538525f..8ba46e33e1 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-export-nested@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-export-nested@component.tsx @@ -1,9 +1,7 @@ -import { baseUrl } from 'destructured-export-nested.tsx' +import { baseUrl } from "destructured-export-nested.tsx"; function AboutComponent() { - return ( - <div> + return <div> <p>Base URL: {baseUrl}</p> - </div> - ) + </div>; } -export { AboutComponent as component } +export { AboutComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-export.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-export.tsx index 282110d045..31b1bfbe8b 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-export.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-export.tsx @@ -1,11 +1,17 @@ -const $$splitComponentImporter = () => - import('destructured-export.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('destructured-export.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export function getObjectCallback() { - return { getObject: () => ({ constA: 10, constB: 5 }) } + return { + getObject: () => ({ + constA: 10, + constB: 5 + }) + }; } -export const { getObject } = getObjectCallback() +export const { + getObject +} = getObjectCallback(); export const Route = createFileRoute('/about')({ - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-export@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-export@component.tsx index b0abbd2e6e..f58942d5af 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-export@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-export@component.tsx @@ -1,11 +1,14 @@ export function getObjectCallback() { - return { getObject: () => ({ constA: 10, constB: 5 }) } + return { + getObject: () => ({ + constA: 10, + constB: 5 + }) + }; } function AboutComponent() { - return ( - <div className="p-2"> + return <div className="p-2"> <h3>About</h3> - </div> - ) + </div>; } -export { AboutComponent as component } +export { AboutComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-export@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-export@errorComponent.tsx index 024e0e620e..45fb19eecd 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-export@errorComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-export@errorComponent.tsx @@ -1,3 +1,8 @@ export function getObjectCallback() { - return { getObject: () => ({ constA: 10, constB: 5 }) } -} + return { + getObject: () => ({ + constA: 10, + constB: 5 + }) + }; +} \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-export@notFoundComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-export@notFoundComponent.tsx index 024e0e620e..45fb19eecd 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-export@notFoundComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-export@notFoundComponent.tsx @@ -1,3 +1,8 @@ export function getObjectCallback() { - return { getObject: () => ({ constA: 10, constB: 5 }) } -} + return { + getObject: () => ({ + constA: 10, + constB: 5 + }) + }; +} \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-react-memo-imported-component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-react-memo-imported-component.tsx index 9ae1904cf4..ee2af1cf9b 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-react-memo-imported-component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-react-memo-imported-component.tsx @@ -1,9 +1,8 @@ -const $$splitComponentImporter = () => - import('destructured-react-memo-imported-component.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' -import { importedLoader } from '../../shared/imported' +const $$splitComponentImporter = () => import('destructured-react-memo-imported-component.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; +import { importedLoader } from '../../shared/imported'; export const Route = createFileRoute('/')({ component: lazyRouteComponent($$splitComponentImporter, 'component'), - loader: importedLoader, -}) + loader: importedLoader +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-react-memo-imported-component@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-react-memo-imported-component@component.tsx index 88dcdf6e48..446d55e26b 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-react-memo-imported-component@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-react-memo-imported-component@component.tsx @@ -1,6 +1,6 @@ -import { memo } from 'react' +import { memo } from 'react'; function Component() { - return <div>Component</div> + return <div>Component</div>; } -const SplitComponent = memo(Component) -export { SplitComponent as component } +const SplitComponent = memo(Component); +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-route-options-defaults.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-route-options-defaults.tsx index c789ea861e..7c54a2c145 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-route-options-defaults.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-route-options-defaults.tsx @@ -1,9 +1,8 @@ -import { loader } from 'destructured-route-options-defaults.tsx?tsr-shared=1' -const $$splitComponentImporter = () => - import('destructured-route-options-defaults.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +import { loader } from "destructured-route-options-defaults.tsx?tsr-shared=1"; +const $$splitComponentImporter = () => import('destructured-route-options-defaults.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/about')({ component: lazyRouteComponent($$splitComponentImporter, 'component'), - loader, -}) + loader +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-route-options-defaults@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-route-options-defaults@component.tsx index c26d6be33d..c73696ff32 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-route-options-defaults@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-route-options-defaults@component.tsx @@ -1,2 +1,2 @@ -import { MyComponent } from 'destructured-route-options-defaults.tsx?tsr-shared=1' -export { MyComponent as component } +import { MyComponent } from "destructured-route-options-defaults.tsx?tsr-shared=1"; +export { MyComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-route-options-defaults@shared.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-route-options-defaults@shared.tsx index a7dee6af52..fdc9acef5b 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-route-options-defaults@shared.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructured-route-options-defaults@shared.tsx @@ -1,23 +1,22 @@ function defaultLoader() { - return { message: 'default' } + return { + message: 'default' + }; } function DefaultComponent() { - return <div>Default</div> + return <div>Default</div>; } const createBits = () => ({ component: ActualComponent, - loader: () => ({ message: 'hello' }), -}) -const { component: MyComponent = DefaultComponent, loader = defaultLoader } = - createBits() + loader: () => ({ + message: 'hello' + }) +}); +const { + component: MyComponent = DefaultComponent, + loader = defaultLoader +} = createBits(); function ActualComponent() { - return <div>About</div> -} -export { - ActualComponent, - createBits, - DefaultComponent, - defaultLoader, - loader, - MyComponent, + return <div>About</div>; } +export { ActualComponent, createBits, DefaultComponent, defaultLoader, loader, MyComponent }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructuring.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructuring.tsx index 112fded569..d80f17484f 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructuring.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructuring.tsx @@ -1,9 +1,11 @@ import thing from 'thing' + export function test() { const { foo: { bar: { destructured }, }, } = thing + return destructured } diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructuring@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructuring@component.tsx index 112fded569..858c5c0e05 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructuring@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructuring@component.tsx @@ -1,9 +1,11 @@ -import thing from 'thing' +import thing from 'thing'; export function test() { const { foo: { - bar: { destructured }, - }, - } = thing - return destructured -} + bar: { + destructured + } + } + } = thing; + return destructured; +} \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructuring@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructuring@errorComponent.tsx index 112fded569..858c5c0e05 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructuring@errorComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructuring@errorComponent.tsx @@ -1,9 +1,11 @@ -import thing from 'thing' +import thing from 'thing'; export function test() { const { foo: { - bar: { destructured }, - }, - } = thing - return destructured -} + bar: { + destructured + } + } + } = thing; + return destructured; +} \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructuring@notFoundComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructuring@notFoundComponent.tsx index 112fded569..858c5c0e05 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructuring@notFoundComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/destructuring@notFoundComponent.tsx @@ -1,9 +1,11 @@ -import thing from 'thing' +import thing from 'thing'; export function test() { const { foo: { - bar: { destructured }, - }, - } = thing - return destructured -} + bar: { + destructured + } + } + } = thing; + return destructured; +} \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/directive-prologue.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/directive-prologue.tsx index 5a116073c1..68f8be0364 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/directive-prologue.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/directive-prologue.tsx @@ -1,8 +1,8 @@ -'use client' -const $$splitComponentImporter = () => - import('directive-prologue.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +'use client'; + +const $$splitComponentImporter = () => import('directive-prologue.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/directive')({ - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/directive-prologue@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/directive-prologue@component.tsx index 9ee4bd8f4c..ce7cd5e5ee 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/directive-prologue@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/directive-prologue@component.tsx @@ -1,5 +1,6 @@ -'use client' +'use client'; + const SplitComponent = () => { - return <div>directive preserved</div> -} -export { SplitComponent as component } + return <div>directive preserved</div>; +}; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/explicit-undefined-component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/explicit-undefined-component.tsx index 8109a89624..4fdd9d1c68 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/explicit-undefined-component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/explicit-undefined-component.tsx @@ -1,3 +1,6 @@ import React from 'react' import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/')({ component: undefined }) + +export const Route = createFileRoute('/')({ + component: undefined, +}) diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/explicit-undefined-component@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/explicit-undefined-component@component.tsx index b45dfaa8f0..b01f5e7863 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/explicit-undefined-component@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/explicit-undefined-component@component.tsx @@ -1 +1 @@ -import React from 'react' +import React from 'react'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/explicit-undefined-component@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/explicit-undefined-component@errorComponent.tsx index b45dfaa8f0..b01f5e7863 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/explicit-undefined-component@errorComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/explicit-undefined-component@errorComponent.tsx @@ -1 +1 @@ -import React from 'react' +import React from 'react'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/explicit-undefined-component@notFoundComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/explicit-undefined-component@notFoundComponent.tsx index b45dfaa8f0..b01f5e7863 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/explicit-undefined-component@notFoundComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/explicit-undefined-component@notFoundComponent.tsx @@ -1 +1 @@ -import React from 'react' +import React from 'react'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/export-default-component-and-normal-notFound.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/export-default-component-and-normal-notFound.tsx index 7154b79acd..da4daa9a3f 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/export-default-component-and-normal-notFound.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/export-default-component-and-normal-notFound.tsx @@ -1,23 +1,15 @@ -console.warn( - '[tanstack-router] These exports from "export-default-component-and-normal-notFound.tsx" will not be code-split and will increase your bundle size:\n- Home\nFor the best optimization, these items should either have their export statements removed, or be imported from another location that is not a route file.', -) -const $$splitNotFoundComponentImporter = () => - import('export-default-component-and-normal-notFound.tsx?tsr-split=notFoundComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import React, { useState } from 'react' -import { createFileRoute } from '@tanstack/react-router' +console.warn("[tanstack-router] These exports from \"export-default-component-and-normal-notFound.tsx\" will not be code-split and will increase your bundle size:\n- Home\nFor the best optimization, these items should either have their export statements removed, or be imported from another location that is not a route file."); +const $$splitNotFoundComponentImporter = () => import('export-default-component-and-normal-notFound.tsx?tsr-split=notFoundComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import React, { useState } from 'react'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/home')({ component: Home, - notFoundComponent: lazyRouteComponent( - $$splitNotFoundComponentImporter, - 'notFoundComponent', - ), -}) + notFoundComponent: lazyRouteComponent($$splitNotFoundComponentImporter, 'notFoundComponent') +}); export default function Home() { - const [one, setOne] = useState('this is from a state') - return ( - <div> + const [one, setOne] = useState('this is from a state'); + return <div> <h1>{one}</h1> - </div> - ) -} + </div>; +} \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/export-default-component-and-normal-notFound@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/export-default-component-and-normal-notFound@component.tsx index b45dfaa8f0..b01f5e7863 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/export-default-component-and-normal-notFound@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/export-default-component-and-normal-notFound@component.tsx @@ -1 +1 @@ -import React from 'react' +import React from 'react'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/export-default-component-and-normal-notFound@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/export-default-component-and-normal-notFound@errorComponent.tsx index b45dfaa8f0..b01f5e7863 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/export-default-component-and-normal-notFound@errorComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/export-default-component-and-normal-notFound@errorComponent.tsx @@ -1 +1 @@ -import React from 'react' +import React from 'react'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/export-default-component-and-normal-notFound@notFoundComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/export-default-component-and-normal-notFound@notFoundComponent.tsx index 3da924c04c..62cd0a1036 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/export-default-component-and-normal-notFound@notFoundComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/export-default-component-and-normal-notFound@notFoundComponent.tsx @@ -1,5 +1,5 @@ -import React from 'react' +import React from 'react'; function NotFoundComponent() { - return <div>Not Found</div> + return <div>Not Found</div>; } -export { NotFoundComponent as notFoundComponent } +export { NotFoundComponent as notFoundComponent }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/export-default-component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/export-default-component.tsx index de2d748c91..c5198b9e00 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/export-default-component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/export-default-component.tsx @@ -1,8 +1,13 @@ import React, { useState } from 'react' import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/home')({ component: Home }) + +export const Route = createFileRoute('/home')({ + component: Home, +}) + export default function Home() { const [one, setOne] = useState('this is from a state') + return ( <div> <h1>{one}</h1> diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/export-default-component@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/export-default-component@component.tsx index b45dfaa8f0..b01f5e7863 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/export-default-component@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/export-default-component@component.tsx @@ -1 +1 @@ -import React from 'react' +import React from 'react'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/export-default-component@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/export-default-component@errorComponent.tsx index b45dfaa8f0..b01f5e7863 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/export-default-component@errorComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/export-default-component@errorComponent.tsx @@ -1 +1 @@ -import React from 'react' +import React from 'react'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/export-default-component@notFoundComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/export-default-component@notFoundComponent.tsx index b45dfaa8f0..b01f5e7863 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/export-default-component@notFoundComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/export-default-component@notFoundComponent.tsx @@ -1 +1 @@ -import React from 'react' +import React from 'react'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/function-as-parameter.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/function-as-parameter.tsx index 817b89d69a..3ae9710cd5 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/function-as-parameter.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/function-as-parameter.tsx @@ -1,20 +1,29 @@ import * as React from 'react' // @ts-expect-error import { useMemo } from 'tan-react' + const useUsedVar = 'i-am-unused' + const ReactUseMemoCall1 = React.useMemo(function performAction() { return 'true' }, []) + console.info(ReactUseMemoCall1) + const ReactUseMemoCall2 = React.useMemo(() => { return 'true' }, []) + console.info(ReactUseMemoCall2) + const UseMemoCall1 = useMemo(function performAction() { return 'true' }, []) + console.info(UseMemoCall1) + const UseMemoCall2 = useMemo(() => { return 'true' }, []) + console.info(UseMemoCall2) diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/function-as-parameter@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/function-as-parameter@component.tsx index 817b89d69a..23e2cd0f03 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/function-as-parameter@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/function-as-parameter@component.tsx @@ -1,20 +1,20 @@ -import * as React from 'react' +import * as React from 'react'; // @ts-expect-error -import { useMemo } from 'tan-react' -const useUsedVar = 'i-am-unused' +import { useMemo } from 'tan-react'; +const useUsedVar = 'i-am-unused'; const ReactUseMemoCall1 = React.useMemo(function performAction() { - return 'true' -}, []) -console.info(ReactUseMemoCall1) + return 'true'; +}, []); +console.info(ReactUseMemoCall1); const ReactUseMemoCall2 = React.useMemo(() => { - return 'true' -}, []) -console.info(ReactUseMemoCall2) + return 'true'; +}, []); +console.info(ReactUseMemoCall2); const UseMemoCall1 = useMemo(function performAction() { - return 'true' -}, []) -console.info(UseMemoCall1) + return 'true'; +}, []); +console.info(UseMemoCall1); const UseMemoCall2 = useMemo(() => { - return 'true' -}, []) -console.info(UseMemoCall2) + return 'true'; +}, []); +console.info(UseMemoCall2); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/function-as-parameter@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/function-as-parameter@errorComponent.tsx index 817b89d69a..23e2cd0f03 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/function-as-parameter@errorComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/function-as-parameter@errorComponent.tsx @@ -1,20 +1,20 @@ -import * as React from 'react' +import * as React from 'react'; // @ts-expect-error -import { useMemo } from 'tan-react' -const useUsedVar = 'i-am-unused' +import { useMemo } from 'tan-react'; +const useUsedVar = 'i-am-unused'; const ReactUseMemoCall1 = React.useMemo(function performAction() { - return 'true' -}, []) -console.info(ReactUseMemoCall1) + return 'true'; +}, []); +console.info(ReactUseMemoCall1); const ReactUseMemoCall2 = React.useMemo(() => { - return 'true' -}, []) -console.info(ReactUseMemoCall2) + return 'true'; +}, []); +console.info(ReactUseMemoCall2); const UseMemoCall1 = useMemo(function performAction() { - return 'true' -}, []) -console.info(UseMemoCall1) + return 'true'; +}, []); +console.info(UseMemoCall1); const UseMemoCall2 = useMemo(() => { - return 'true' -}, []) -console.info(UseMemoCall2) + return 'true'; +}, []); +console.info(UseMemoCall2); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/function-as-parameter@notFoundComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/function-as-parameter@notFoundComponent.tsx index 817b89d69a..23e2cd0f03 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/function-as-parameter@notFoundComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/function-as-parameter@notFoundComponent.tsx @@ -1,20 +1,20 @@ -import * as React from 'react' +import * as React from 'react'; // @ts-expect-error -import { useMemo } from 'tan-react' -const useUsedVar = 'i-am-unused' +import { useMemo } from 'tan-react'; +const useUsedVar = 'i-am-unused'; const ReactUseMemoCall1 = React.useMemo(function performAction() { - return 'true' -}, []) -console.info(ReactUseMemoCall1) + return 'true'; +}, []); +console.info(ReactUseMemoCall1); const ReactUseMemoCall2 = React.useMemo(() => { - return 'true' -}, []) -console.info(ReactUseMemoCall2) + return 'true'; +}, []); +console.info(ReactUseMemoCall2); const UseMemoCall1 = useMemo(function performAction() { - return 'true' -}, []) -console.info(UseMemoCall1) + return 'true'; +}, []); +console.info(UseMemoCall1); const UseMemoCall2 = useMemo(() => { - return 'true' -}, []) -console.info(UseMemoCall2) + return 'true'; +}, []); +console.info(UseMemoCall2); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/function-declaration.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/function-declaration.tsx index e2b672f7b8..5d7e2181f5 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/function-declaration.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/function-declaration.tsx @@ -1,10 +1,9 @@ -const $$splitComponentImporter = () => - import('function-declaration.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import * as React from 'react' -import { createFileRoute } from '@tanstack/react-router' -import { fetchPosts } from '../posts' +const $$splitComponentImporter = () => import('function-declaration.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import * as React from 'react'; +import { createFileRoute } from '@tanstack/react-router'; +import { fetchPosts } from '../posts'; export const Route = createFileRoute('/posts')({ loader: fetchPosts, - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/function-declaration@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/function-declaration@component.tsx index a0ebf07dee..3476c52d54 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/function-declaration@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/function-declaration@component.tsx @@ -1,31 +1,27 @@ -import * as React from 'react' -import { Link, Outlet } from '@tanstack/react-router' -import { Route } from 'function-declaration.tsx' +import * as React from 'react'; +import { Link, Outlet } from '@tanstack/react-router'; +import { Route } from "function-declaration.tsx"; function PostsComponent() { - const posts = Route.useLoaderData() - return ( - <div className="p-2 flex gap-2"> + const posts = Route.useLoaderData(); + return <div className="p-2 flex gap-2"> <ul className="list-disc pl-4"> - {[...posts, { id: 'i-do-not-exist', title: 'Non-existent Post' }]?.map( - (post) => { - return ( - <li key={post.id} className="whitespace-nowrap"> - <Link - to="/posts/$postId" - params={{ postId: post.id }} - className="block py-1 text-blue-800 hover:text-blue-600" - activeProps={{ className: 'text-black font-bold' }} - > + {[...posts, { + id: 'i-do-not-exist', + title: 'Non-existent Post' + }]?.map(post => { + return <li key={post.id} className="whitespace-nowrap"> + <Link to="/posts/$postId" params={{ + postId: post.id + }} className="block py-1 text-blue-800 hover:text-blue-600" activeProps={{ + className: 'text-black font-bold' + }}> <div>{post.title.substring(0, 20)}</div> </Link> - </li> - ) - }, - )} + </li>; + })} </ul> <hr /> <Outlet /> - </div> - ) + </div>; } -export { PostsComponent as component } +export { PostsComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/function-declaration@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/function-declaration@errorComponent.tsx index 371dc65868..5f67a6fff1 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/function-declaration@errorComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/function-declaration@errorComponent.tsx @@ -1 +1 @@ -import * as React from 'react' +import * as React from 'react'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/function-declaration@notFoundComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/function-declaration@notFoundComponent.tsx index 371dc65868..5f67a6fff1 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/function-declaration@notFoundComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/function-declaration@notFoundComponent.tsx @@ -1 +1 @@ -import * as React from 'react' +import * as React from 'react'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/importAttribute.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/importAttribute.tsx index 82d7bb0cad..df71217488 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/importAttribute.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/importAttribute.tsx @@ -1,7 +1,6 @@ -const $$splitComponentImporter = () => - import('importAttribute.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('importAttribute.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/')({ - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/importAttribute@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/importAttribute@component.tsx index 88abef0c00..f34d3c6408 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/importAttribute@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/importAttribute@component.tsx @@ -1,3 +1,3 @@ -import { test } from './test' with { type: 'macro' } -const SplitComponent = () => test -export { SplitComponent as component } +import { test } from './test' with { type: 'macro' }; +const SplitComponent = () => test; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-default-component-destructured-loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-default-component-destructured-loader.tsx index 4818827c9c..2271ab4454 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-default-component-destructured-loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-default-component-destructured-loader.tsx @@ -1,9 +1,8 @@ -const $$splitComponentImporter = () => - import('imported-default-component-destructured-loader.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' -import { importedLoader } from '../../shared/imported' +const $$splitComponentImporter = () => import('imported-default-component-destructured-loader.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; +import { importedLoader } from '../../shared/imported'; export const Route = createFileRoute('/')({ component: lazyRouteComponent($$splitComponentImporter, 'component'), - loader: importedLoader, -}) + loader: importedLoader +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-default-component-destructured-loader@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-default-component-destructured-loader@component.tsx index 9350cda9e8..d21b198c98 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-default-component-destructured-loader@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-default-component-destructured-loader@component.tsx @@ -1,3 +1,3 @@ -import importedComponent from '../../shared/imported' -const SplitComponent = importedComponent -export { SplitComponent as component } +import importedComponent from '../../shared/imported'; +const SplitComponent = importedComponent; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-default-component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-default-component.tsx index d213c7c5af..dcd6f3d5e0 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-default-component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-default-component.tsx @@ -1,7 +1,6 @@ -const $$splitComponentImporter = () => - import('imported-default-component.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('imported-default-component.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/')({ - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-default-component@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-default-component@component.tsx index d356227040..31ccf07c52 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-default-component@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-default-component@component.tsx @@ -1,3 +1,3 @@ -import ImportedDefaultComponent from '../../shared/imported' -const SplitComponent = ImportedDefaultComponent -export { SplitComponent as component } +import ImportedDefaultComponent from '../../shared/imported'; +const SplitComponent = ImportedDefaultComponent; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-errorComponent.tsx index e3702ed63b..898e1b3618 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-errorComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-errorComponent.tsx @@ -1,13 +1,8 @@ -const $$splitErrorComponentImporter = () => - import('imported-errorComponent.tsx?tsr-split=errorComponent') -const $$splitComponentImporter = () => - import('imported-errorComponent.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitErrorComponentImporter = () => import('imported-errorComponent.tsx?tsr-split=errorComponent'); +const $$splitComponentImporter = () => import('imported-errorComponent.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/')({ component: lazyRouteComponent($$splitComponentImporter, 'component'), - errorComponent: lazyRouteComponent( - $$splitErrorComponentImporter, - 'errorComponent', - ), -}) + errorComponent: lazyRouteComponent($$splitErrorComponentImporter, 'errorComponent') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-errorComponent@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-errorComponent@component.tsx index d356227040..31ccf07c52 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-errorComponent@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-errorComponent@component.tsx @@ -1,3 +1,3 @@ -import ImportedDefaultComponent from '../../shared/imported' -const SplitComponent = ImportedDefaultComponent -export { SplitComponent as component } +import ImportedDefaultComponent from '../../shared/imported'; +const SplitComponent = ImportedDefaultComponent; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-errorComponent@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-errorComponent@errorComponent.tsx index 3f20c3e485..7a8654fb94 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-errorComponent@errorComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-errorComponent@errorComponent.tsx @@ -1,3 +1,3 @@ -import { importedErrorComponent } from '../../shared/imported' -const SplitErrorComponent = importedErrorComponent -export { SplitErrorComponent as errorComponent } +import { importedErrorComponent } from '../../shared/imported'; +const SplitErrorComponent = importedErrorComponent; +export { SplitErrorComponent as errorComponent }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-notFoundComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-notFoundComponent.tsx index 0a203d3cf9..4c5c19cfcf 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-notFoundComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-notFoundComponent.tsx @@ -1,13 +1,8 @@ -const $$splitNotFoundComponentImporter = () => - import('imported-notFoundComponent.tsx?tsr-split=notFoundComponent') -const $$splitComponentImporter = () => - import('imported-notFoundComponent.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitNotFoundComponentImporter = () => import('imported-notFoundComponent.tsx?tsr-split=notFoundComponent'); +const $$splitComponentImporter = () => import('imported-notFoundComponent.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/')({ component: lazyRouteComponent($$splitComponentImporter, 'component'), - notFoundComponent: lazyRouteComponent( - $$splitNotFoundComponentImporter, - 'notFoundComponent', - ), -}) + notFoundComponent: lazyRouteComponent($$splitNotFoundComponentImporter, 'notFoundComponent') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-notFoundComponent@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-notFoundComponent@component.tsx index d356227040..31ccf07c52 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-notFoundComponent@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-notFoundComponent@component.tsx @@ -1,3 +1,3 @@ -import ImportedDefaultComponent from '../../shared/imported' -const SplitComponent = ImportedDefaultComponent -export { SplitComponent as component } +import ImportedDefaultComponent from '../../shared/imported'; +const SplitComponent = ImportedDefaultComponent; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-notFoundComponent@notFoundComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-notFoundComponent@notFoundComponent.tsx index bfe9d4e1c9..c6cfd9797f 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-notFoundComponent@notFoundComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-notFoundComponent@notFoundComponent.tsx @@ -1,3 +1,3 @@ -import { importedNotFoundComponent } from '../../shared/imported' -const SplitNotFoundComponent = importedNotFoundComponent -export { SplitNotFoundComponent as notFoundComponent } +import { importedNotFoundComponent } from '../../shared/imported'; +const SplitNotFoundComponent = importedNotFoundComponent; +export { SplitNotFoundComponent as notFoundComponent }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-pendingComponent.tsx index 751e1c9a50..17adf19f06 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-pendingComponent.tsx @@ -1,9 +1,8 @@ -const $$splitComponentImporter = () => - import('imported-pendingComponent.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' -import { importedPendingComponent } from '../../shared/imported' +const $$splitComponentImporter = () => import('imported-pendingComponent.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; +import { importedPendingComponent } from '../../shared/imported'; export const Route = createFileRoute('/')({ component: lazyRouteComponent($$splitComponentImporter, 'component'), - pendingComponent: importedPendingComponent, -}) + pendingComponent: importedPendingComponent +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-pendingComponent@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-pendingComponent@component.tsx index d356227040..31ccf07c52 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-pendingComponent@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported-pendingComponent@component.tsx @@ -1,3 +1,3 @@ -import ImportedDefaultComponent from '../../shared/imported' -const SplitComponent = ImportedDefaultComponent -export { SplitComponent as component } +import ImportedDefaultComponent from '../../shared/imported'; +const SplitComponent = ImportedDefaultComponent; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported.tsx index 6ead4fbb5e..e92f76cf98 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported.tsx @@ -1,9 +1,8 @@ -const $$splitComponentImporter = () => - import('imported.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' -import { importedLoader } from '../../shared' +const $$splitComponentImporter = () => import('imported.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; +import { importedLoader } from '../../shared'; export const Route = createFileRoute('/')({ component: lazyRouteComponent($$splitComponentImporter, 'component'), - loader: importedLoader, -}) + loader: importedLoader +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported@component.tsx index e3c06dbe9e..5bc9da8d43 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/imported@component.tsx @@ -1,3 +1,3 @@ -import { importedComponent } from '../../shared' -const SplitComponent = importedComponent -export { SplitComponent as component } +import { importedComponent } from '../../shared'; +const SplitComponent = importedComponent; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/inline.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/inline.tsx index 7b39974d3a..c2b4dae416 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/inline.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/inline.tsx @@ -1,9 +1,9 @@ -const $$splitComponentImporter = () => import('inline.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import * as React from 'react' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('inline.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import * as React from 'react'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/')({ - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) -Route.addChildren([]) -export const test = 'test' + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); +Route.addChildren([]); +export const test = 'test'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/inline@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/inline@component.tsx index d28b872634..58ccfb2903 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/inline@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/inline@component.tsx @@ -1,18 +1,18 @@ -import * as React from 'react' -import * as styles from '../style.css' -import { TEST_DATA } from '../test.const' -const Button = (props: { children: any }) => { - return <button>{props.children}</button> -} -import { Route } from 'inline.tsx' -import { test } from 'inline.tsx' +import * as React from 'react'; +import * as styles from '../style.css'; +import { TEST_DATA } from '../test.const'; +const Button = (props: { + children: any; +}) => { + return <button>{props.children}</button>; +}; +import { Route } from "inline.tsx"; +import { test } from "inline.tsx"; const SplitComponent = () => { - return ( - <div className="p-2"> - {test} - <h3 className={styles.indexPageTitle}>{TEST_DATA.welcome}</h3> - <Button>Click me</Button> - </div> - ) -} -export { SplitComponent as component } + return <div className="p-2"> + {test} + <h3 className={styles.indexPageTitle}>{TEST_DATA.welcome}</h3> + <Button>Click me</Button> + </div>; +}; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/inline@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/inline@errorComponent.tsx index 23fab71edc..9236af6021 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/inline@errorComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/inline@errorComponent.tsx @@ -1,2 +1,2 @@ -import * as React from 'react' -import { Route } from 'inline.tsx' +import * as React from 'react'; +import { Route } from "inline.tsx"; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/inline@notFoundComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/inline@notFoundComponent.tsx index 23fab71edc..9236af6021 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/inline@notFoundComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/inline@notFoundComponent.tsx @@ -1,2 +1,2 @@ -import * as React from 'react' -import { Route } from 'inline.tsx' +import * as React from 'react'; +import { Route } from "inline.tsx"; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/lowercase-function-declaration.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/lowercase-function-declaration.tsx deleted file mode 100644 index 13cb142f27..0000000000 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/lowercase-function-declaration.tsx +++ /dev/null @@ -1,17 +0,0 @@ -const $$splitErrorComponentImporter = () => - import('lowercase-function-declaration.tsx?tsr-split=errorComponent') -const $$splitComponentImporter = () => - import('lowercase-function-declaration.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/')({ - component: lazyRouteComponent($$splitComponentImporter, 'component'), - pendingComponent, - errorComponent: lazyRouteComponent( - $$splitErrorComponentImporter, - 'errorComponent', - ), -}) -function pendingComponent() { - return <div>lowercase pending function declaration</div> -} diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/lowercase-function-declaration@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/lowercase-function-declaration@component.tsx deleted file mode 100644 index e53a2acebf..0000000000 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/lowercase-function-declaration@component.tsx +++ /dev/null @@ -1,4 +0,0 @@ -function component() { - return <div>lowercase function declaration</div> -} -export { component } diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/lowercase-function-declaration@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/lowercase-function-declaration@errorComponent.tsx deleted file mode 100644 index 9d411c1f0f..0000000000 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/lowercase-function-declaration@errorComponent.tsx +++ /dev/null @@ -1,4 +0,0 @@ -function errorComponent() { - return <div>lowercase error function declaration</div> -} -export { errorComponent } diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/lowercase-function-declaration@shared.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/lowercase-function-declaration@shared.tsx deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/random-number.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/random-number.tsx index c9e47e1145..0cb0a2e13b 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/random-number.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/random-number.tsx @@ -1,45 +1,32 @@ -const $$splitComponentImporter = () => - import('random-number.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import { Await, Link, createFileRoute, defer } from '@tanstack/react-router' -import { Carbon } from '~/components/Carbon' -import { twMerge } from 'tailwind-merge' -import { FaDiscord, FaGithub, FaTshirt } from 'react-icons/fa' -import { CgMusicSpeaker, CgSpinner } from 'react-icons/cg' -import { Footer } from '~/components/Footer' -import SponsorPack from '~/components/SponsorPack' -import { LogoColor } from '~/components/LogoColor' -import { getSponsorsForSponsorPack } from '~/server/sponsors' -import agGridImage from '~/images/ag-grid.png' -import nozzleImage from '~/images/nozzle.png' -import bytesImage from '~/images/bytes.svg' -import bytesUidotdevImage from '~/images/bytes-uidotdev.png' -export const textColors = [ - `text-rose-500`, - `text-yellow-500`, - `text-teal-500`, - `text-blue-500`, -] -export const gradients = [ - `from-rose-500 to-yellow-500`, - `from-yellow-500 to-teal-500`, - `from-teal-500 to-violet-500`, - `from-blue-500 to-pink-500`, -] -const courses = [ - { - name: 'The Official TanStack React Query Course', - cardStyles: `border-t-4 border-red-500 hover:(border-green-500)`, - href: 'https://query.gg/?s=tanstack', - description: `Learn how to build enterprise quality apps with TanStack's React Query the easy way with our brand new course.`, - }, -] +const $$splitComponentImporter = () => import('random-number.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { Await, Link, createFileRoute, defer } from '@tanstack/react-router'; +import { Carbon } from '~/components/Carbon'; +import { twMerge } from 'tailwind-merge'; +import { FaDiscord, FaGithub, FaTshirt } from 'react-icons/fa'; +import { CgMusicSpeaker, CgSpinner } from 'react-icons/cg'; +import { Footer } from '~/components/Footer'; +import SponsorPack from '~/components/SponsorPack'; +import { LogoColor } from '~/components/LogoColor'; +import { getSponsorsForSponsorPack } from '~/server/sponsors'; +import agGridImage from '~/images/ag-grid.png'; +import nozzleImage from '~/images/nozzle.png'; +import bytesImage from '~/images/bytes.svg'; +import bytesUidotdevImage from '~/images/bytes-uidotdev.png'; +export const textColors = [`text-rose-500`, `text-yellow-500`, `text-teal-500`, `text-blue-500`]; +export const gradients = [`from-rose-500 to-yellow-500`, `from-yellow-500 to-teal-500`, `from-teal-500 to-violet-500`, `from-blue-500 to-pink-500`]; +const courses = [{ + name: 'The Official TanStack React Query Course', + cardStyles: `border-t-4 border-red-500 hover:(border-green-500)`, + href: 'https://query.gg/?s=tanstack', + description: `Learn how to build enterprise quality apps with TanStack's React Query the easy way with our brand new course.` +}]; export const Route = createFileRoute('/')({ loader: () => { return { randomNumber: Math.random(), - sponsorsPromise: defer(getSponsorsForSponsorPack()), - } + sponsorsPromise: defer(getSponsorsForSponsorPack()) + }; }, - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/random-number@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/random-number@component.tsx index 26a9f9c142..9ed6d15184 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/random-number@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/random-number@component.tsx @@ -1,48 +1,61 @@ -import { Await, Link } from '@tanstack/react-router' -import { Carbon } from '~/components/Carbon' -import { twMerge } from 'tailwind-merge' -import { FaDiscord, FaGithub, FaTshirt } from 'react-icons/fa' -import { CgMusicSpeaker, CgSpinner } from 'react-icons/cg' -import { Footer } from '~/components/Footer' -import SponsorPack from '~/components/SponsorPack' -import { LogoColor } from '~/components/LogoColor' -import discordImage from '~/images/discord-logo-white.svg' -import agGridImage from '~/images/ag-grid.png' -import nozzleImage from '~/images/nozzle.png' -import bytesImage from '~/images/bytes.svg' -import bytesUidotdevImage from '~/images/bytes-uidotdev.png' -import { useMutation } from '~/hooks/useMutation' -import { sample } from '~/utils/utils' -import { textColors } from 'random-number.tsx' -import { gradients } from 'random-number.tsx' -const courses = [ - { - name: 'The Official TanStack React Query Course', - cardStyles: `border-t-4 border-red-500 hover:(border-green-500)`, - href: 'https://query.gg/?s=tanstack', - description: `Learn how to build enterprise quality apps with TanStack's React Query the easy way with our brand new course.`, - }, -] -import { Route } from 'random-number.tsx' -async function bytesSignupServerFn({ email }: { email: string }) { - 'use server' +import { Await, Link } from '@tanstack/react-router'; +import { Carbon } from '~/components/Carbon'; +import { twMerge } from 'tailwind-merge'; +import { FaDiscord, FaGithub, FaTshirt } from 'react-icons/fa'; +import { CgMusicSpeaker, CgSpinner } from 'react-icons/cg'; +import { Footer } from '~/components/Footer'; +import SponsorPack from '~/components/SponsorPack'; +import { LogoColor } from '~/components/LogoColor'; +import discordImage from '~/images/discord-logo-white.svg'; +import agGridImage from '~/images/ag-grid.png'; +import nozzleImage from '~/images/nozzle.png'; +import bytesImage from '~/images/bytes.svg'; +import bytesUidotdevImage from '~/images/bytes-uidotdev.png'; +import { useMutation } from '~/hooks/useMutation'; +import { sample } from '~/utils/utils'; +import { textColors } from "random-number.tsx"; +import { gradients } from "random-number.tsx"; +const courses = [{ + name: 'The Official TanStack React Query Course', + cardStyles: `border-t-4 border-red-500 hover:(border-green-500)`, + href: 'https://query.gg/?s=tanstack', + description: `Learn how to build enterprise quality apps with TanStack's React Query the easy way with our brand new course.` +}]; +import { Route } from "random-number.tsx"; +async function bytesSignupServerFn({ + email +}: { + email: string; +}) { + 'use server'; + return fetch(`https://bytes.dev/api/bytes-optin-cors`, { method: 'POST', - body: JSON.stringify({ email, influencer: 'tanstack' }), - headers: { Accept: 'application/json', 'Content-Type': 'application/json' }, - }) + body: JSON.stringify({ + email, + influencer: 'tanstack' + }), + headers: { + Accept: 'application/json', + 'Content-Type': 'application/json' + } + }); } function Index() { - const bytesSignupMutation = useMutation({ fn: bytesSignupServerFn }) - const { sponsorsPromise, randomNumber, testing2 } = Route.useLoaderData() - const gradient = sample(gradients, randomNumber) - const textColor = sample(textColors, randomNumber) - return ( - <> + const bytesSignupMutation = useMutation({ + fn: bytesSignupServerFn + }); + const { + sponsorsPromise, + randomNumber, + testing2 + } = Route.useLoaderData(); + const gradient = sample(gradients, randomNumber); + const textColor = sample(textColors, randomNumber); + return <> {discordImage} {gradient} {textColor} - </> - ) + </>; } -export { Index as component } +export { Index as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/random-number@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/random-number@errorComponent.tsx index 8e156eca17..cdf4d37891 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/random-number@errorComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/random-number@errorComponent.tsx @@ -1,20 +1,18 @@ -import { Await, Link } from '@tanstack/react-router' -import { Carbon } from '~/components/Carbon' -import { twMerge } from 'tailwind-merge' -import { FaDiscord, FaGithub, FaTshirt } from 'react-icons/fa' -import { CgMusicSpeaker, CgSpinner } from 'react-icons/cg' -import { Footer } from '~/components/Footer' -import SponsorPack from '~/components/SponsorPack' -import { LogoColor } from '~/components/LogoColor' -import agGridImage from '~/images/ag-grid.png' -import nozzleImage from '~/images/nozzle.png' -import bytesImage from '~/images/bytes.svg' -import bytesUidotdevImage from '~/images/bytes-uidotdev.png' -const courses = [ - { - name: 'The Official TanStack React Query Course', - cardStyles: `border-t-4 border-red-500 hover:(border-green-500)`, - href: 'https://query.gg/?s=tanstack', - description: `Learn how to build enterprise quality apps with TanStack's React Query the easy way with our brand new course.`, - }, -] +import { Await, Link } from '@tanstack/react-router'; +import { Carbon } from '~/components/Carbon'; +import { twMerge } from 'tailwind-merge'; +import { FaDiscord, FaGithub, FaTshirt } from 'react-icons/fa'; +import { CgMusicSpeaker, CgSpinner } from 'react-icons/cg'; +import { Footer } from '~/components/Footer'; +import SponsorPack from '~/components/SponsorPack'; +import { LogoColor } from '~/components/LogoColor'; +import agGridImage from '~/images/ag-grid.png'; +import nozzleImage from '~/images/nozzle.png'; +import bytesImage from '~/images/bytes.svg'; +import bytesUidotdevImage from '~/images/bytes-uidotdev.png'; +const courses = [{ + name: 'The Official TanStack React Query Course', + cardStyles: `border-t-4 border-red-500 hover:(border-green-500)`, + href: 'https://query.gg/?s=tanstack', + description: `Learn how to build enterprise quality apps with TanStack's React Query the easy way with our brand new course.` +}]; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/random-number@notFoundComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/random-number@notFoundComponent.tsx index 8e156eca17..cdf4d37891 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/random-number@notFoundComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/random-number@notFoundComponent.tsx @@ -1,20 +1,18 @@ -import { Await, Link } from '@tanstack/react-router' -import { Carbon } from '~/components/Carbon' -import { twMerge } from 'tailwind-merge' -import { FaDiscord, FaGithub, FaTshirt } from 'react-icons/fa' -import { CgMusicSpeaker, CgSpinner } from 'react-icons/cg' -import { Footer } from '~/components/Footer' -import SponsorPack from '~/components/SponsorPack' -import { LogoColor } from '~/components/LogoColor' -import agGridImage from '~/images/ag-grid.png' -import nozzleImage from '~/images/nozzle.png' -import bytesImage from '~/images/bytes.svg' -import bytesUidotdevImage from '~/images/bytes-uidotdev.png' -const courses = [ - { - name: 'The Official TanStack React Query Course', - cardStyles: `border-t-4 border-red-500 hover:(border-green-500)`, - href: 'https://query.gg/?s=tanstack', - description: `Learn how to build enterprise quality apps with TanStack's React Query the easy way with our brand new course.`, - }, -] +import { Await, Link } from '@tanstack/react-router'; +import { Carbon } from '~/components/Carbon'; +import { twMerge } from 'tailwind-merge'; +import { FaDiscord, FaGithub, FaTshirt } from 'react-icons/fa'; +import { CgMusicSpeaker, CgSpinner } from 'react-icons/cg'; +import { Footer } from '~/components/Footer'; +import SponsorPack from '~/components/SponsorPack'; +import { LogoColor } from '~/components/LogoColor'; +import agGridImage from '~/images/ag-grid.png'; +import nozzleImage from '~/images/nozzle.png'; +import bytesImage from '~/images/bytes.svg'; +import bytesUidotdevImage from '~/images/bytes-uidotdev.png'; +const courses = [{ + name: 'The Official TanStack React Query Course', + cardStyles: `border-t-4 border-red-500 hover:(border-green-500)`, + href: 'https://query.gg/?s=tanstack', + description: `Learn how to build enterprise quality apps with TanStack's React Query the easy way with our brand new course.` +}]; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/react-memo-component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/react-memo-component.tsx index 229a2d0f80..5fd96f8da1 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/react-memo-component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/react-memo-component.tsx @@ -1,9 +1,8 @@ -const $$splitComponentImporter = () => - import('react-memo-component.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' -import { importedLoader } from '../../shared/imported' +const $$splitComponentImporter = () => import('react-memo-component.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; +import { importedLoader } from '../../shared/imported'; export const Route = createFileRoute('/')({ component: lazyRouteComponent($$splitComponentImporter, 'component'), - loader: importedLoader, -}) + loader: importedLoader +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/react-memo-component@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/react-memo-component@component.tsx index 6bdb537fe9..dfef29c9e3 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/react-memo-component@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/react-memo-component@component.tsx @@ -1,6 +1,6 @@ -import React from 'react' +import React from 'react'; function Component() { - return <div>Component</div> + return <div>Component</div>; } -const SplitComponent = React.memo(Component) -export { SplitComponent as component } +const SplitComponent = React.memo(Component); +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/react-memo-imported-component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/react-memo-imported-component.tsx index 701826b3f6..69df0886db 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/react-memo-imported-component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/react-memo-imported-component.tsx @@ -1,9 +1,8 @@ -const $$splitComponentImporter = () => - import('react-memo-imported-component.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' -import { importedLoader } from '../../shared/imported' +const $$splitComponentImporter = () => import('react-memo-imported-component.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; +import { importedLoader } from '../../shared/imported'; export const Route = createFileRoute('/')({ component: lazyRouteComponent($$splitComponentImporter, 'component'), - loader: importedLoader, -}) + loader: importedLoader +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/react-memo-imported-component@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/react-memo-imported-component@component.tsx index d162a1aeaf..540812230e 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/react-memo-imported-component@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/react-memo-imported-component@component.tsx @@ -1,4 +1,4 @@ -import React from 'react' -import { importedComponent } from '../../shared/imported' -const SplitComponent = React.memo(importedComponent) -export { SplitComponent as component } +import React from 'react'; +import { importedComponent } from '../../shared/imported'; +const SplitComponent = React.memo(importedComponent); +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-export-component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-export-component.tsx index f2078a1757..1ae234de6f 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-export-component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-export-component.tsx @@ -4,6 +4,7 @@ import { importedComponent as ImportedComponent, importedLoader, } from '../../shared/imported' + export function Layout() { return ( <main> @@ -21,10 +22,12 @@ export function Layout() { </main> ) } + export const Route = createFileRoute('/_layout')({ component: Layout, loader: importedLoader, }) + const HEADER_HEIGHT = '63px' export const SIDEBAR_WIDTH = '150px' const SIDEBAR_MINI_WIDTH = '80px' diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-export-component@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-export-component@component.tsx index 8fb12f0c6b..5bb0ab5451 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-export-component@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-export-component@component.tsx @@ -1,3 +1,3 @@ -import * as React from 'react' -const SIDEBAR_MINI_WIDTH = '80px' -const ASIDE_WIDTH = '250px' +import * as React from 'react'; +const SIDEBAR_MINI_WIDTH = '80px'; +const ASIDE_WIDTH = '250px'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-export-component@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-export-component@errorComponent.tsx index 8fb12f0c6b..5bb0ab5451 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-export-component@errorComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-export-component@errorComponent.tsx @@ -1,3 +1,3 @@ -import * as React from 'react' -const SIDEBAR_MINI_WIDTH = '80px' -const ASIDE_WIDTH = '250px' +import * as React from 'react'; +const SIDEBAR_MINI_WIDTH = '80px'; +const ASIDE_WIDTH = '250px'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-export-component@notFoundComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-export-component@notFoundComponent.tsx index 8fb12f0c6b..5bb0ab5451 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-export-component@notFoundComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-export-component@notFoundComponent.tsx @@ -1,3 +1,3 @@ -import * as React from 'react' -const SIDEBAR_MINI_WIDTH = '80px' -const ASIDE_WIDTH = '250px' +import * as React from 'react'; +const SIDEBAR_MINI_WIDTH = '80px'; +const ASIDE_WIDTH = '250px'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-const.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-const.tsx index d674dbb799..f256b01a83 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-const.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-const.tsx @@ -4,9 +4,11 @@ import { importedComponent as ImportedComponent, importedLoader, } from '../../shared/imported' + export const loaderFn = () => { return importedLoader() } + const Layout = () => { return ( <main> @@ -24,12 +26,15 @@ const Layout = () => { </main> ) } + export const Route = createFileRoute('/_layout')({ component: Layout, loader: loaderFn, }) + const HEADER_HEIGHT = '63px' export const SIDEBAR_WIDTH = '150px' export const SIDEBAR_MINI_WIDTH = '80px' const ASIDE_WIDTH = '250px' + export default Layout diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-const@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-const@component.tsx index 0e0123f1ab..168ba78680 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-const@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-const@component.tsx @@ -1,2 +1,2 @@ -import * as React from 'react' -const ASIDE_WIDTH = '250px' +import * as React from 'react'; +const ASIDE_WIDTH = '250px'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-const@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-const@errorComponent.tsx index 0e0123f1ab..168ba78680 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-const@errorComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-const@errorComponent.tsx @@ -1,2 +1,2 @@ -import * as React from 'react' -const ASIDE_WIDTH = '250px' +import * as React from 'react'; +const ASIDE_WIDTH = '250px'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-const@notFoundComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-const@notFoundComponent.tsx index 0e0123f1ab..168ba78680 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-const@notFoundComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-const@notFoundComponent.tsx @@ -1,2 +1,2 @@ -import * as React from 'react' -const ASIDE_WIDTH = '250px' +import * as React from 'react'; +const ASIDE_WIDTH = '250px'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-destructured.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-destructured.tsx index 89c23305a0..0e3175116f 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-destructured.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-destructured.tsx @@ -1,12 +1,18 @@ import { createFileRoute } from '@tanstack/react-router' + const createBits = () => ({ component: AboutComponentImpl, - loader: () => ({ message: 'hello' }), + loader: () => ({ + message: 'hello', + }), }) + export const { component: AboutComponent, loader } = createBits() + function AboutComponentImpl() { return <div>About</div> } + export const Route = createFileRoute('/about')({ component: AboutComponent, loader, diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-destructured@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-destructured@component.tsx index d64b42fdcc..a6d57afe77 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-destructured@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-destructured@component.tsx @@ -1,2 +1,2 @@ -import { AboutComponent } from 'retain-exports-destructured.tsx?tsr-shared=1' -export { AboutComponent as component } +import { AboutComponent } from "retain-exports-destructured.tsx?tsr-shared=1"; +export { AboutComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-destructured@shared.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-destructured@shared.tsx index 6eff1ff083..b03a4eb83a 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-destructured@shared.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-destructured@shared.tsx @@ -1,9 +1,14 @@ const createBits = () => ({ component: AboutComponentImpl, - loader: () => ({ message: 'hello' }), -}) -const { component: AboutComponent, loader } = createBits() + loader: () => ({ + message: 'hello' + }) +}); +const { + component: AboutComponent, + loader +} = createBits(); function AboutComponentImpl() { - return <div>About</div> + return <div>About</div>; } -export { AboutComponent, AboutComponentImpl, createBits, loader } +export { AboutComponent, AboutComponentImpl, createBits, loader }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-function.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-function.tsx index 83b3dd4eb5..298c388e65 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-function.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-function.tsx @@ -4,9 +4,11 @@ import { importedComponent as ImportedComponent, importedLoader, } from '../../shared/imported' + export function loaderFn() { return importedLoader() } + function Layout() { return ( <main> @@ -24,12 +26,15 @@ function Layout() { </main> ) } + export const Route = createFileRoute('/_layout')({ component: Layout, loader: loaderFn, }) + const HEADER_HEIGHT = '63px' export const SIDEBAR_WIDTH = '150px' export const SIDEBAR_MINI_WIDTH = '80px' const ASIDE_WIDTH = '250px' + export default Layout diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-function@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-function@component.tsx index 0e0123f1ab..168ba78680 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-function@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-function@component.tsx @@ -1,2 +1,2 @@ -import * as React from 'react' -const ASIDE_WIDTH = '250px' +import * as React from 'react'; +const ASIDE_WIDTH = '250px'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-function@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-function@errorComponent.tsx index 0e0123f1ab..168ba78680 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-function@errorComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-function@errorComponent.tsx @@ -1,2 +1,2 @@ -import * as React from 'react' -const ASIDE_WIDTH = '250px' +import * as React from 'react'; +const ASIDE_WIDTH = '250px'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-function@notFoundComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-function@notFoundComponent.tsx index 0e0123f1ab..168ba78680 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-function@notFoundComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-function@notFoundComponent.tsx @@ -1,2 +1,2 @@ -import * as React from 'react' -const ASIDE_WIDTH = '250px' +import * as React from 'react'; +const ASIDE_WIDTH = '250px'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-loader.tsx index 16357edc27..88cd35f704 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-loader.tsx @@ -1,15 +1,16 @@ -const $$splitComponentImporter = () => - import('retain-exports-loader.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import * as React from 'react' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('retain-exports-loader.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import * as React from 'react'; +import { createFileRoute } from '@tanstack/react-router'; export function loaderFn() { - return { foo: 'bar' } + return { + foo: 'bar' + }; } export const Route = createFileRoute('/_layout')({ component: lazyRouteComponent($$splitComponentImporter, 'component'), - loader: loaderFn, -}) -export const SIDEBAR_WIDTH = '150px' -export const SIDEBAR_MINI_WIDTH = '80px' -const ASIDE_WIDTH = '250px' + loader: loaderFn +}); +export const SIDEBAR_WIDTH = '150px'; +export const SIDEBAR_MINI_WIDTH = '80px'; +const ASIDE_WIDTH = '250px'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-loader@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-loader@component.tsx index 604be4dc69..9f54ae0dc5 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-loader@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-loader@component.tsx @@ -1,10 +1,11 @@ -import * as React from 'react' -import { Outlet } from '@tanstack/react-router' -import { importedComponent as ImportedComponent } from '../../shared/imported' +import * as React from 'react'; +import { Outlet } from '@tanstack/react-router'; +import { importedComponent as ImportedComponent } from '../../shared/imported'; function Layout() { - return ( - <main> - <header style={{ height: HEADER_HEIGHT }}> + return <main> + <header style={{ + height: HEADER_HEIGHT + }}> <nav> <ul> <li> @@ -15,9 +16,8 @@ function Layout() { </header> <ImportedComponent /> <Outlet /> - </main> - ) + </main>; } -const HEADER_HEIGHT = '63px' -const ASIDE_WIDTH = '250px' -export { Layout as component } +const HEADER_HEIGHT = '63px'; +const ASIDE_WIDTH = '250px'; +export { Layout as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-loader@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-loader@errorComponent.tsx index 0e0123f1ab..168ba78680 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-loader@errorComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-loader@errorComponent.tsx @@ -1,2 +1,2 @@ -import * as React from 'react' -const ASIDE_WIDTH = '250px' +import * as React from 'react'; +const ASIDE_WIDTH = '250px'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-loader@notFoundComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-loader@notFoundComponent.tsx index 0e0123f1ab..168ba78680 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-loader@notFoundComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/retain-exports-loader@notFoundComponent.tsx @@ -1,2 +1,2 @@ -import * as React from 'react' -const ASIDE_WIDTH = '250px' +import * as React from 'react'; +const ASIDE_WIDTH = '250px'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-class.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-class.tsx index 19509e3bdd..6e2f0229e4 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-class.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-class.tsx @@ -1,11 +1,10 @@ -import { store } from 'shared-class.tsx?tsr-shared=1' -const $$splitComponentImporter = () => - import('shared-class.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +import { store } from "shared-class.tsx?tsr-shared=1"; +const $$splitComponentImporter = () => import('shared-class.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/store')({ loader: async () => { - store.set('items', await fetch('/api')) + store.set('items', await fetch('/api')); }, - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-class@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-class@component.tsx index e0e187fb1d..6a38b10ff8 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-class@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-class@component.tsx @@ -1,3 +1,3 @@ -import { store } from 'shared-class.tsx?tsr-shared=1' -const SplitComponent = () => <div>{store.get('items')}</div> -export { SplitComponent as component } +import { store } from "shared-class.tsx?tsr-shared=1"; +const SplitComponent = () => <div>{store.get('items')}</div>; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-class@shared.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-class@shared.tsx index 0abc282ecc..18c40bafb6 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-class@shared.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-class@shared.tsx @@ -1,11 +1,11 @@ class DataStore { - data = new Map() + data = new Map(); get(k: string) { - return this.data.get(k) + return this.data.get(k); } set(k: string, v: unknown) { - this.data.set(k, v) + this.data.set(k, v); } } -const store = new DataStore() -export { DataStore, store } +const store = new DataStore(); +export { DataStore, store }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-destructured-export.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-destructured-export.tsx index dc4d2d383f..9453dbfbda 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-destructured-export.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-destructured-export.tsx @@ -1,10 +1,9 @@ -import { apiUrl } from 'shared-destructured-export.tsx?tsr-shared=1' -const $$splitComponentImporter = () => - import('shared-destructured-export.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +import { apiUrl } from "shared-destructured-export.tsx?tsr-shared=1"; +const $$splitComponentImporter = () => import('shared-destructured-export.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/config')({ loader: async () => fetch(apiUrl), - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) -export { apiUrl, timeout } from 'shared-destructured-export.tsx?tsr-shared=1' + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); +export { apiUrl, timeout } from "shared-destructured-export.tsx?tsr-shared=1"; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-destructured-export@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-destructured-export@component.tsx index 8cd0f14a27..16b288ac5f 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-destructured-export@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-destructured-export@component.tsx @@ -1,3 +1,3 @@ -import { timeout } from 'shared-destructured-export.tsx?tsr-shared=1' -const SplitComponent = () => <div>Timeout: {timeout}</div> -export { SplitComponent as component } +import { timeout } from "shared-destructured-export.tsx?tsr-shared=1"; +const SplitComponent = () => <div>Timeout: {timeout}</div>; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-destructured-export@shared.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-destructured-export@shared.tsx index ae9324acc9..f0bfd70add 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-destructured-export@shared.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-destructured-export@shared.tsx @@ -1,5 +1,11 @@ -const { apiUrl, timeout } = getConfig() +const { + apiUrl, + timeout +} = getConfig(); function getConfig() { - return { apiUrl: '/api', timeout: 5000 } + return { + apiUrl: '/api', + timeout: 5000 + }; } -export { apiUrl, getConfig, timeout } +export { apiUrl, getConfig, timeout }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-destructured.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-destructured.tsx index b1d4f96065..3019454516 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-destructured.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-destructured.tsx @@ -1,9 +1,8 @@ -import { apiUrl } from 'shared-destructured.tsx?tsr-shared=1' -const $$splitComponentImporter = () => - import('shared-destructured.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +import { apiUrl } from "shared-destructured.tsx?tsr-shared=1"; +const $$splitComponentImporter = () => import('shared-destructured.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/config')({ loader: async () => fetch(apiUrl), - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-destructured@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-destructured@component.tsx index 3d7933a573..5c0182e61a 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-destructured@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-destructured@component.tsx @@ -1,3 +1,3 @@ -import { timeout } from 'shared-destructured.tsx?tsr-shared=1' -const SplitComponent = () => <div>Timeout: {timeout}</div> -export { SplitComponent as component } +import { timeout } from "shared-destructured.tsx?tsr-shared=1"; +const SplitComponent = () => <div>Timeout: {timeout}</div>; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-destructured@shared.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-destructured@shared.tsx index ae9324acc9..f0bfd70add 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-destructured@shared.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-destructured@shared.tsx @@ -1,5 +1,11 @@ -const { apiUrl, timeout } = getConfig() +const { + apiUrl, + timeout +} = getConfig(); function getConfig() { - return { apiUrl: '/api', timeout: 5000 } + return { + apiUrl: '/api', + timeout: 5000 + }; } -export { apiUrl, getConfig, timeout } +export { apiUrl, getConfig, timeout }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-exported.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-exported.tsx index aa9730bec7..c2eb8b1012 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-exported.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-exported.tsx @@ -1,12 +1,13 @@ -import { queryOptions } from 'shared-exported.tsx?tsr-shared=1' -const $$splitComponentImporter = () => - import('shared-exported.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +import { queryOptions } from "shared-exported.tsx?tsr-shared=1"; +const $$splitComponentImporter = () => import('shared-exported.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/query')({ loader: async () => { - return { staleTime: queryOptions.staleTime } + return { + staleTime: queryOptions.staleTime + }; }, - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) -export { queryOptions } from 'shared-exported.tsx?tsr-shared=1' + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); +export { queryOptions } from "shared-exported.tsx?tsr-shared=1"; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-exported@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-exported@component.tsx index 9fe61942dd..b020b5cadf 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-exported@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-exported@component.tsx @@ -1,3 +1,3 @@ -import { queryOptions } from 'shared-exported.tsx?tsr-shared=1' -const SplitComponent = () => <div>GC: {queryOptions.gcTime}</div> -export { SplitComponent as component } +import { queryOptions } from "shared-exported.tsx?tsr-shared=1"; +const SplitComponent = () => <div>GC: {queryOptions.gcTime}</div>; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-exported@shared.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-exported@shared.tsx index 3a1ff108bb..a3f91b85bb 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-exported@shared.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-exported@shared.tsx @@ -1,2 +1,5 @@ -const queryOptions = { staleTime: 5000, gcTime: 10000 } -export { queryOptions } +const queryOptions = { + staleTime: 5000, + gcTime: 10000 +}; +export { queryOptions }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-function.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-function.tsx index d4f3d89f2d..7372ff4b07 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-function.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-function.tsx @@ -1,15 +1,14 @@ -import { getCached, cache } from 'shared-function.tsx?tsr-shared=1' -const $$splitComponentImporter = () => - import('shared-function.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +import { getCached, cache } from "shared-function.tsx?tsr-shared=1"; +const $$splitComponentImporter = () => import('shared-function.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; function setCached(key: string, val: unknown) { - cache.set(key, val) + cache.set(key, val); } export const Route = createFileRoute('/cached')({ loader: async () => { - setCached('data', await fetch('/api').then((r) => r.json())) - return getCached('data') + setCached('data', await fetch('/api').then(r => r.json())); + return getCached('data'); }, - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-function@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-function@component.tsx index 1c327523af..571bd9356a 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-function@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-function@component.tsx @@ -1,3 +1,3 @@ -import { getCached } from 'shared-function.tsx?tsr-shared=1' -const SplitComponent = () => <div>{JSON.stringify(getCached('data'))}</div> -export { SplitComponent as component } +import { getCached } from "shared-function.tsx?tsr-shared=1"; +const SplitComponent = () => <div>{JSON.stringify(getCached('data'))}</div>; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-function@shared.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-function@shared.tsx index 243ac23a66..27d2cf03f1 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-function@shared.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-function@shared.tsx @@ -1,5 +1,5 @@ -const cache = new Map() +const cache = new Map(); function getCached(key: string) { - return cache.get(key) + return cache.get(key); } -export { cache, getCached } +export { cache, getCached }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-imported-binding.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-imported-binding.tsx index da3387c5fd..c3e284c081 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-imported-binding.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-imported-binding.tsx @@ -1,9 +1,8 @@ -const $$splitComponentImporter = () => - import('shared-imported-binding.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' -import { sharedUtil } from '../utils' +const $$splitComponentImporter = () => import('shared-imported-binding.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; +import { sharedUtil } from '../utils'; export const Route = createFileRoute('/imported')({ loader: async () => sharedUtil('load'), - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-imported-binding@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-imported-binding@component.tsx index e3c8a0f5d8..0a835ae063 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-imported-binding@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-imported-binding@component.tsx @@ -1,3 +1,3 @@ -import { sharedUtil } from '../utils' -const SplitComponent = () => <div>{sharedUtil('render')}</div> -export { SplitComponent as component } +import { sharedUtil } from '../utils'; +const SplitComponent = () => <div>{sharedUtil('render')}</div>; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-indirect-ref.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-indirect-ref.tsx index 244f566066..889dd57cf0 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-indirect-ref.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-indirect-ref.tsx @@ -1,12 +1,13 @@ -import { state, getCount } from 'shared-indirect-ref.tsx?tsr-shared=1' -const $$splitComponentImporter = () => - import('shared-indirect-ref.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +import { state, getCount } from "shared-indirect-ref.tsx?tsr-shared=1"; +const $$splitComponentImporter = () => import('shared-indirect-ref.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/shared-indirect')({ loader: () => { - state.count++ - return { count: getCount() } + state.count++; + return { + count: getCount() + }; }, - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-indirect-ref@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-indirect-ref@component.tsx index 64bb6ab567..62995e7fd8 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-indirect-ref@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-indirect-ref@component.tsx @@ -1,9 +1,7 @@ -import { state, getCount } from 'shared-indirect-ref.tsx?tsr-shared=1' +import { state, getCount } from "shared-indirect-ref.tsx?tsr-shared=1"; function SharedComponent() { - return ( - <div> + return <div> {getCount()} - {state.count} - </div> - ) + </div>; } -export { SharedComponent as component } +export { SharedComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-indirect-ref@shared.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-indirect-ref@shared.tsx index b4910d2fd1..7e7e811ba8 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-indirect-ref@shared.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-indirect-ref@shared.tsx @@ -1,5 +1,7 @@ -const state = { count: 0 } +const state = { + count: 0 +}; function getCount() { - return state.count + return state.count; } -export { getCount, state } +export { getCount, state }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-jsx-component-ref.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-jsx-component-ref.tsx index 6b29c09f33..728caca361 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-jsx-component-ref.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-jsx-component-ref.tsx @@ -1,10 +1,9 @@ -import { shared } from 'shared-jsx-component-ref.tsx?tsr-shared=1' -const $$splitComponentImporter = () => - import('shared-jsx-component-ref.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' +import { shared } from "shared-jsx-component-ref.tsx?tsr-shared=1"; +const $$splitComponentImporter = () => import('shared-jsx-component-ref.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; // @ts-nocheck -import { createFileRoute } from '@tanstack/react-router' +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/jsx')({ loader: () => shared, - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-jsx-component-ref@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-jsx-component-ref@component.tsx index 845e1db45c..52ecb6d474 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-jsx-component-ref@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-jsx-component-ref@component.tsx @@ -1,5 +1,5 @@ -import { shared } from 'shared-jsx-component-ref.tsx?tsr-shared=1' // @ts-nocheck +import { shared } from "shared-jsx-component-ref.tsx?tsr-shared=1"; // @ts-nocheck function SharedComponent() { - return <div>{shared}</div> + return <div>{shared}</div>; } -export { SharedComponent as component } +export { SharedComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-jsx-component-ref@shared.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-jsx-component-ref@shared.tsx index 60ae1006a1..d5cc2cf990 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-jsx-component-ref@shared.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-jsx-component-ref@shared.tsx @@ -1,3 +1,4 @@ // @ts-nocheck -const shared = 1 -export { shared } + +const shared = 1; +export { shared }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-none.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-none.tsx index 6d0ece44ba..dd352bfc41 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-none.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-none.tsx @@ -1,9 +1,8 @@ -const $$splitComponentImporter = () => - import('shared-none.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' -const loaderHelper = () => fetch('/api') +const $$splitComponentImporter = () => import('shared-none.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; +const loaderHelper = () => fetch('/api'); export const Route = createFileRoute('/clean')({ loader: async () => loaderHelper(), - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-none@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-none@component.tsx index 1bfd4eb63f..701deeedeb 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-none@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-none@component.tsx @@ -1,7 +1,5 @@ -const ComponentHelper = () => <span>helper</span> -const SplitComponent = () => ( - <div> - <ComponentHelper /> - </div> -) -export { SplitComponent as component } +const ComponentHelper = () => <span>helper</span>; +const SplitComponent = () => <div> + <ComponentHelper /> + </div>; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-referencing-route.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-referencing-route.tsx index 1ac3428ebc..f82ac5b900 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-referencing-route.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-referencing-route.tsx @@ -1,15 +1,16 @@ -import { HEADER } from 'shared-referencing-route.tsx?tsr-shared=1' -const $$splitComponentImporter = () => - import('shared-referencing-route.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +import { HEADER } from "shared-referencing-route.tsx?tsr-shared=1"; +const $$splitComponentImporter = () => import('shared-referencing-route.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; function usePageTitle() { - return `${HEADER} - ${Route.fullPath}` + return `${HEADER} - ${Route.fullPath}`; } export const Route = createFileRoute('/about')({ loader: async () => { - const title = usePageTitle() - return { title } + const title = usePageTitle(); + return { + title + }; }, - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-referencing-route@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-referencing-route@component.tsx index b2c4630c90..2cb2cdb68c 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-referencing-route@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-referencing-route@component.tsx @@ -1,10 +1,10 @@ -import { HEADER } from 'shared-referencing-route.tsx?tsr-shared=1' +import { HEADER } from "shared-referencing-route.tsx?tsr-shared=1"; function usePageTitle() { - return `${HEADER} - ${Route.fullPath}` + return `${HEADER} - ${Route.fullPath}`; } -import { Route } from 'shared-referencing-route.tsx' +import { Route } from "shared-referencing-route.tsx"; const SplitComponent = () => { - const title = usePageTitle() - return <div>{title}</div> -} -export { SplitComponent as component } + const title = usePageTitle(); + return <div>{title}</div>; +}; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-referencing-route@shared.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-referencing-route@shared.tsx index 34b9c4ca41..cc2d01424c 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-referencing-route@shared.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-referencing-route@shared.tsx @@ -1,2 +1,2 @@ -const HEADER = 'Page' -export { HEADER } +const HEADER = 'Page'; +export { HEADER }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-runtime.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-runtime.tsx deleted file mode 100644 index 17d70ca9bd..0000000000 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-runtime.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { - state, - createState, - createSeed, - increment, -} from 'shared-runtime.tsx?tsr-shared=1' -const $$splitComponentImporter = () => - import('shared-runtime.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' -console.log('shared-runtime:reference') -export const Route = createFileRoute('/shared-runtime')({ - beforeLoad: () => state, - loader: () => { - increment() - return state - }, - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) -function createState(initialState: { count: number }): { - state: { count: number } - increment: () => number -} -export { state as firstState, state as secondState, state as 'odd-name' } -export default createSeed diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-runtime@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-runtime@component.tsx deleted file mode 100644 index 5245f6d9eb..0000000000 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-runtime@component.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import { - state, - createState, - createSeed, - Labels, -} from 'shared-runtime.tsx?tsr-shared=1' -const label = createComponentLabel() -function createState(initialState: { count: number }): { - state: { count: number } - increment: () => number -} -function createComponentLabel() { - console.log('shared-runtime:component') - return Labels.component -} -export { state as firstState, state as secondState, state as 'odd-name' } -export default createSeed -const SplitComponent = () => { - if (state.count === 3) { - throw new Error('route source-map contract') - } - return `${label}:${state.count}` -} -export { SplitComponent as component } diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-runtime@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-runtime@errorComponent.tsx deleted file mode 100644 index 03cacac5b3..0000000000 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-runtime@errorComponent.tsx +++ /dev/null @@ -1,7 +0,0 @@ -import { state, createState, createSeed } from 'shared-runtime.tsx?tsr-shared=1' -function createState(initialState: { count: number }): { - state: { count: number } - increment: () => number -} -export { state as firstState, state as secondState, state as 'odd-name' } -export default createSeed diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-runtime@notFoundComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-runtime@notFoundComponent.tsx deleted file mode 100644 index 03cacac5b3..0000000000 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-runtime@notFoundComponent.tsx +++ /dev/null @@ -1,7 +0,0 @@ -import { state, createState, createSeed } from 'shared-runtime.tsx?tsr-shared=1' -function createState(initialState: { count: number }): { - state: { count: number } - increment: () => number -} -export { state as firstState, state as secondState, state as 'odd-name' } -export default createSeed diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-runtime@shared.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-runtime@shared.tsx deleted file mode 100644 index c53a7e1568..0000000000 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-runtime@shared.tsx +++ /dev/null @@ -1,13 +0,0 @@ -const Count = { Initial: 0 } -const Labels = { component: 'count' } -const seed = createSeed() -const { state, increment } = createState(seed) -function createSeed() { - console.log('shared-runtime:seed') - return { count: Count.Initial, label: Labels.component } -} -function createState(initialState: { count: number }) { - console.log('shared-runtime:state') - return { state: initialState, increment: () => initialState.count++ } -} -export { Count, createSeed, createState, increment, Labels, seed, state } diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-transitive.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-transitive.tsx index 3860bd4688..ce5a10c47c 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-transitive.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-transitive.tsx @@ -1,12 +1,11 @@ -import { config } from 'shared-transitive.tsx?tsr-shared=1' -const $$splitComponentImporter = () => - import('shared-transitive.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' -const fetcher = (path: string) => fetch(`${config.url}${path}`) +import { config } from "shared-transitive.tsx?tsr-shared=1"; +const $$splitComponentImporter = () => import('shared-transitive.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; +const fetcher = (path: string) => fetch(`${config.url}${path}`); export const Route = createFileRoute('/api')({ loader: async () => { - return fetcher('/data') + return fetcher('/data'); }, - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-transitive@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-transitive@component.tsx index c237a03583..7a3a74048e 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-transitive@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-transitive@component.tsx @@ -1,3 +1,3 @@ -import { config } from 'shared-transitive.tsx?tsr-shared=1' -const SplitComponent = () => <div>Timeout: {config.timeout}</div> -export { SplitComponent as component } +import { config } from "shared-transitive.tsx?tsr-shared=1"; +const SplitComponent = () => <div>Timeout: {config.timeout}</div>; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-transitive@shared.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-transitive@shared.tsx index ac44498714..8bec4a1d55 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-transitive@shared.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-transitive@shared.tsx @@ -1,3 +1,6 @@ -const BASE_URL = 'https://api.example.com' -const config = { url: BASE_URL, timeout: 5000 } -export { BASE_URL, config } +const BASE_URL = 'https://api.example.com'; +const config = { + url: BASE_URL, + timeout: 5000 +}; +export { BASE_URL, config }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-variable.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-variable.tsx index f7b7b51f4d..c0c02cec46 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-variable.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-variable.tsx @@ -1,12 +1,13 @@ -import { collection } from 'shared-variable.tsx?tsr-shared=1' -const $$splitComponentImporter = () => - import('shared-variable.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +import { collection } from "shared-variable.tsx?tsr-shared=1"; +const $$splitComponentImporter = () => import('shared-variable.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/todos')({ loader: async () => { - await collection.preload() - return { data: 'loaded' } + await collection.preload(); + return { + data: 'loaded' + }; }, - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-variable@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-variable@component.tsx index 10325aa95e..d149922fbc 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-variable@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-variable@component.tsx @@ -1,3 +1,3 @@ -import { collection } from 'shared-variable.tsx?tsr-shared=1' -const SplitComponent = () => <div>{collection.name}</div> -export { SplitComponent as component } +import { collection } from "shared-variable.tsx?tsr-shared=1"; +const SplitComponent = () => <div>{collection.name}</div>; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-variable@shared.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-variable@shared.tsx index 10421dac09..8a0560d5b9 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-variable@shared.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-variable@shared.tsx @@ -1,2 +1,5 @@ -const collection = { name: 'todos', preload: async () => {} } -export { collection } +const collection = { + name: 'todos', + preload: async () => {} +}; +export { collection }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-with-side-effect.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-with-side-effect.tsx index 39bbc717d9..cba0c7770b 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-with-side-effect.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-with-side-effect.tsx @@ -1,12 +1,11 @@ -import { registry } from 'shared-with-side-effect.tsx?tsr-shared=1' -const $$splitComponentImporter = () => - import('shared-with-side-effect.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' -console.log('registry created') +import { registry } from "shared-with-side-effect.tsx?tsr-shared=1"; +const $$splitComponentImporter = () => import('shared-with-side-effect.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; +console.log('registry created'); export const Route = createFileRoute('/fx')({ loader: async () => { - registry.set('loaded', true) + registry.set('loaded', true); }, - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-with-side-effect@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-with-side-effect@component.tsx index 3ede22c8be..d953af00fa 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-with-side-effect@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-with-side-effect@component.tsx @@ -1,3 +1,3 @@ -import { registry } from 'shared-with-side-effect.tsx?tsr-shared=1' -const SplitComponent = () => <div>{registry.size}</div> -export { SplitComponent as component } +import { registry } from "shared-with-side-effect.tsx?tsr-shared=1"; +const SplitComponent = () => <div>{registry.size}</div>; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-with-side-effect@shared.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-with-side-effect@shared.tsx index a59298f9e0..f26c656fdd 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-with-side-effect@shared.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/shared-with-side-effect@shared.tsx @@ -1,2 +1,2 @@ -const registry = new Map() -export { registry } +const registry = new Map(); +export { registry }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/undefined-literals.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/undefined-literals.tsx index 88b0bf1ba8..0c6e4f01aa 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/undefined-literals.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/undefined-literals.tsx @@ -1,4 +1,5 @@ import { createFileRoute } from '@tanstack/react-router' + export const Route = createFileRoute('/undefined-test')({ component: undefined, errorComponent: undefined, diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/useStateDestructure.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/useStateDestructure.tsx index b5b3ecade6..d0de09bf8b 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/useStateDestructure.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/useStateDestructure.tsx @@ -1,4 +1,5 @@ import * as React from 'react' + import { CgCornerUpLeft, CgSpinner } from 'react-icons/cg' import { FaBolt, @@ -20,6 +21,7 @@ import { startProject } from '~/projects/start' import { createFileRoute } from '@tanstack/react-router' import { Framework, getBranch } from '~/projects' import { seo } from '~/utils/seo' + const menu = [ { label: ( @@ -70,22 +72,31 @@ const menu = [ to: `https://cottonbureau.com/people/tanstack`, }, ] + export const Route = createFileRoute('/_libraries/start/$version/')({ component: VersionIndex, meta: () => - seo({ title: startProject.name, description: startProject.description }), + seo({ + title: startProject.name, + description: startProject.description, + }), }) + const librariesRouteApi = getRouteApi('/_libraries') + export default function VersionIndex() { const { sponsorsPromise } = librariesRouteApi.useLoaderData() const { version } = Route.useParams() const branch = getBranch(startProject, version) const [framework, setFramework] = React.useState<Framework>('react') const [isDark, setIsDark] = React.useState(true) + React.useEffect(() => { setIsDark(window.matchMedia?.(`(prefers-color-scheme: dark)`).matches) }, []) + const gradientText = `inline-block text-transparent bg-clip-text bg-gradient-to-r ${startProject.colorFrom} ${startProject.colorTo}` + return ( <div className="flex flex-col gap-20 md:gap-32 max-w-full"> <div @@ -96,6 +107,7 @@ export default function VersionIndex() { const label = ( <div className="p-2 opacity-90 hover:opacity-100">{item.label}</div> ) + return ( <div key={i} className="hover:underline"> {item.to.startsWith('http') ? ( @@ -257,6 +269,7 @@ Check it out at https://tanstack.com/start/`, </div> </div> </div> */} + {/* <div className="px-4 sm:px-6 lg:px-8 mx-auto"> <div className=" sm:text-center pb-16"> <h3 className="text-3xl text-center mx-auto leading-tight font-extrabold tracking-tight sm:text-4xl lg:leading-none mt-2"> @@ -302,6 +315,7 @@ Check it out at https://tanstack.com/start/`, })} </div> </div> */} + {/* <div> <div className="uppercase tracking-wider text-sm font-semibold text-center text-gray-400 mb-3"> Trusted in Production by @@ -344,6 +358,7 @@ Check it out at https://tanstack.com/start/`, </div> </marquee> </div> */} + <div className="px-4 w-[500px] max-w-full mx-auto"> <h3 className="text-center text-3xl leading-8 font-extrabold tracking-tight sm:text-4xl sm:leading-10 lg:leading-none mt-8"> Partners @@ -373,13 +388,16 @@ Check it out at https://tanstack.com/start/`, </div> </div> </div> + <div className="relative text-lg overflow-hidden"> <h3 className="text-center text-3xl leading-8 font-extrabold tracking-tight sm:text-4xl sm:leading-10 lg:leading-none mt-8"> Sponsors </h3> <div className="my-4 flex flex-wrap mx-auto max-w-screen-lg" - style={{ aspectRatio: '1/1' }} + style={{ + aspectRatio: '1/1', + }} > <Await promise={sponsorsPromise} @@ -398,6 +416,7 @@ Check it out at https://tanstack.com/start/`, </a> </div> </div> + <div className="mx-auto max-w-[400px] flex flex-col gap-2 items-center"> <div className="shadow-lg rounded-lg overflow-hidden bg-white dark:bg-gray-800 dark:text-white"> <Carbon /> @@ -410,6 +429,7 @@ Check it out at https://tanstack.com/start/`, rage-quit OSS. Yay money! 😉 </span> </div> + {/* <div className="flex flex-col gap-4"> <div className="px-4 sm:px-6 lg:px-8 mx-auto max-w-3xl sm:text-center"> <h3 className="text-3xl text-center leading-8 font-extrabold tracking-tight sm:text-4xl sm:leading-10 lg:leading-none mt-2"> @@ -448,6 +468,7 @@ Check it out at https://tanstack.com/start/`, </div> </div> </div> */} + {/* {[''].includes(framework) ? ( <div className="px-2"> <div className="p-8 text-center text-lg w-full max-w-screen-lg mx-auto bg-black text-white rounded-xl"> @@ -482,6 +503,7 @@ Check it out at https://tanstack.com/start/`, ></iframe> </div> )} */} + {/* <div className="flex flex-col gap-4 items-center"> <div className="font-extrabold text-xl lg:text-2xl"> Wow, you've come a long way! diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/useStateDestructure@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/useStateDestructure@component.tsx index 5cc3099643..97b5481cf5 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/useStateDestructure@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/useStateDestructure@component.tsx @@ -1,2 +1,2 @@ -import { FaBolt, FaBook, FaCheckCircle, FaCogs } from 'react-icons/fa' -import { VscPreview, VscWand } from 'react-icons/vsc' +import { FaBolt, FaBook, FaCheckCircle, FaCogs } from 'react-icons/fa'; +import { VscPreview, VscWand } from 'react-icons/vsc'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/useStateDestructure@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/useStateDestructure@errorComponent.tsx index 5cc3099643..97b5481cf5 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/useStateDestructure@errorComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/useStateDestructure@errorComponent.tsx @@ -1,2 +1,2 @@ -import { FaBolt, FaBook, FaCheckCircle, FaCogs } from 'react-icons/fa' -import { VscPreview, VscWand } from 'react-icons/vsc' +import { FaBolt, FaBook, FaCheckCircle, FaCogs } from 'react-icons/fa'; +import { VscPreview, VscWand } from 'react-icons/vsc'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/useStateDestructure@notFoundComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/useStateDestructure@notFoundComponent.tsx index 5cc3099643..97b5481cf5 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/useStateDestructure@notFoundComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/useStateDestructure@notFoundComponent.tsx @@ -1,2 +1,2 @@ -import { FaBolt, FaBook, FaCheckCircle, FaCogs } from 'react-icons/fa' -import { VscPreview, VscWand } from 'react-icons/vsc' +import { FaBolt, FaBook, FaCheckCircle, FaCogs } from 'react-icons/fa'; +import { VscPreview, VscWand } from 'react-icons/vsc'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/arrow-function.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/arrow-function.tsx index 29a53d433e..ad71347222 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/arrow-function.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/arrow-function.tsx @@ -1,12 +1,10 @@ -const $$splitComponentImporter = () => - import('arrow-function.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -const $$splitLoaderImporter = () => - import('arrow-function.tsx?tsr-split=loader') -import { lazyFn } from '@tanstack/react-router' -import * as React from 'react' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('arrow-function.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +const $$splitLoaderImporter = () => import('arrow-function.tsx?tsr-split=loader'); +import { lazyFn } from '@tanstack/react-router'; +import * as React from 'react'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/posts')({ loader: lazyFn($$splitLoaderImporter, 'loader'), - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/arrow-function@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/arrow-function@component---errorComponent---notFoundComponent---pendingComponent.tsx index e36e48f495..7fe3edee11 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/arrow-function@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/arrow-function@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,31 +1,27 @@ -import * as React from 'react' -import { Link, Outlet } from '@tanstack/react-router' -import { Route } from 'arrow-function.tsx' +import * as React from 'react'; +import { Link, Outlet } from '@tanstack/react-router'; +import { Route } from "arrow-function.tsx"; const PostsComponent = () => { - const posts = Route.useLoaderData() - return ( - <div className="p-2 flex gap-2"> + const posts = Route.useLoaderData(); + return <div className="p-2 flex gap-2"> <ul className="list-disc pl-4"> - {[...posts, { id: 'i-do-not-exist', title: 'Non-existent Post' }]?.map( - (post) => { - return ( - <li key={post.id} className="whitespace-nowrap"> - <Link - to="/posts/$postId" - params={{ postId: post.id }} - className="block py-1 text-blue-800 hover:text-blue-600" - activeProps={{ className: 'text-black font-bold' }} - > + {[...posts, { + id: 'i-do-not-exist', + title: 'Non-existent Post' + }]?.map(post => { + return <li key={post.id} className="whitespace-nowrap"> + <Link to="/posts/$postId" params={{ + postId: post.id + }} className="block py-1 text-blue-800 hover:text-blue-600" activeProps={{ + className: 'text-black font-bold' + }}> <div>{post.title.substring(0, 20)}</div> </Link> - </li> - ) - }, - )} + </li>; + })} </ul> <hr /> <Outlet /> - </div> - ) -} -export { PostsComponent as component } + </div>; +}; +export { PostsComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/arrow-function@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/arrow-function@loader.tsx index 1c4fc213ed..cb195afdd8 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/arrow-function@loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/arrow-function@loader.tsx @@ -1,4 +1,4 @@ -import * as React from 'react' -import { fetchPosts } from '../posts' -const SplitLoader = fetchPosts -export { SplitLoader as loader } +import * as React from 'react'; +import { fetchPosts } from '../posts'; +const SplitLoader = fetchPosts; +export { SplitLoader as loader }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/boolean-null-literals.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/boolean-null-literals.tsx index 05711582b7..c31ee0e095 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/boolean-null-literals.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/boolean-null-literals.tsx @@ -1,14 +1,13 @@ -const $$splitLoaderImporter = () => - import('boolean-null-literals.tsx?tsr-split=loader') -import { lazyFn } from '@tanstack/react-router' -const $$splitComponentImporter = () => - import('boolean-null-literals.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/router' +const $$splitLoaderImporter = () => import('boolean-null-literals.tsx?tsr-split=loader'); +import { lazyFn } from '@tanstack/react-router'; +const $$splitComponentImporter = () => import('boolean-null-literals.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/router'; + // Test errorComponent with false literal export const Route = createFileRoute('/test')({ component: lazyRouteComponent($$splitComponentImporter, 'component'), errorComponent: false, pendingComponent: null, - loader: lazyFn($$splitLoaderImporter, 'loader'), -}) + loader: lazyFn($$splitLoaderImporter, 'loader') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/boolean-null-literals@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/boolean-null-literals@component---errorComponent---notFoundComponent---pendingComponent.tsx index 557105b6a3..c49c9e93a3 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/boolean-null-literals@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/boolean-null-literals@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,3 +1,3 @@ // Test errorComponent with false literal -const SplitComponent = () => <div>Test Component</div> -export { SplitComponent as component } +const SplitComponent = () => <div>Test Component</div>; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/boolean-null-literals@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/boolean-null-literals@loader.tsx index 0e19f8cafe..666ed1e7ec 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/boolean-null-literals@loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/boolean-null-literals@loader.tsx @@ -1,3 +1,5 @@ // Test errorComponent with false literal -const SplitLoader = async () => ({ data: 'test' }) -export { SplitLoader as loader } +const SplitLoader = async () => ({ + data: 'test' +}); +export { SplitLoader as loader }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/chinese.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/chinese.tsx index 41db95b98c..327e227da4 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/chinese.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/chinese.tsx @@ -1,11 +1,10 @@ -const $$splitComponentImporter = () => - import('chinese.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import * as React from 'react' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('chinese.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import * as React from 'react'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/')({ - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); interface DemoProps { - title: string -} + title: string; +} \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/chinese@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/chinese@component---errorComponent---notFoundComponent---pendingComponent.tsx index 2ac1fa54ff..003ca944a1 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/chinese@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/chinese@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,27 +1,23 @@ -import * as React from 'react' +import * as React from 'react'; function HomeComponent() { - return ( - <div className="p-2"> + return <div className="p-2"> <Demo title="标题很好看,谁说不是呢?" /> <Demo title="The title looks great, who can deny that?" /> - </div> - ) + </div>; } interface DemoProps { - title: string + title: string; } -function Demo({ title }: DemoProps) { - return ( - <h1 - style={{ - color: '#2969ff', - fontSize: '2rem', - fontWeight: 'bold', - letterSpacing: '3px', - }} - > +function Demo({ + title +}: DemoProps) { + return <h1 style={{ + color: '#2969ff', + fontSize: '2rem', + fontWeight: 'bold', + letterSpacing: '3px' + }}> {title} - </h1> - ) + </h1>; } -export { HomeComponent as component } +export { HomeComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/chinese@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/chinese@loader.tsx index cbcea8cc40..b4de370f4e 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/chinese@loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/chinese@loader.tsx @@ -1,4 +1,4 @@ -import * as React from 'react' +import * as React from 'react'; interface DemoProps { - title: string -} + title: string; +} \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/circular-reference-arrow-function.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/circular-reference-arrow-function.tsx index 38e3239ffd..ec4cff827d 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/circular-reference-arrow-function.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/circular-reference-arrow-function.tsx @@ -1,7 +1,6 @@ -const $$splitComponentImporter = () => - import('circular-reference-arrow-function.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('circular-reference-arrow-function.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/')({ - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/circular-reference-arrow-function@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/circular-reference-arrow-function@component---errorComponent---notFoundComponent---pendingComponent.tsx index 59c5b5eec2..39ace71ebe 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/circular-reference-arrow-function@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/circular-reference-arrow-function@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,17 +1,19 @@ function getComponentName(obj: Record<string, unknown>): string { - return Object.keys(obj)[0] + return Object.keys(obj)[0]; } const App = () => { - const componentName = getComponentName({ App }) - return ( - <div> + const componentName = getComponentName({ + App + }); + return <div> Component Name is {componentName} <OtherComponent /> - </div> - ) -} + </div>; +}; function OtherComponent() { - const componentName = getComponentName({ App }) - return <div>App component name is {componentName}</div> + const componentName = getComponentName({ + App + }); + return <div>App component name is {componentName}</div>; } -export { App as component } +export { App as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/circular-reference-function.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/circular-reference-function.tsx index b3bdc6b113..e4a82d1022 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/circular-reference-function.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/circular-reference-function.tsx @@ -1,7 +1,6 @@ -const $$splitComponentImporter = () => - import('circular-reference-function.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('circular-reference-function.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/')({ - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/circular-reference-function@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/circular-reference-function@component---errorComponent---notFoundComponent---pendingComponent.tsx index 22fbb8669f..96a753ad8a 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/circular-reference-function@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/circular-reference-function@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,17 +1,19 @@ function getComponentName(obj: Record<string, unknown>): string { - return Object.keys(obj)[0] + return Object.keys(obj)[0]; } function App() { - const componentName = getComponentName({ App }) - return ( - <div> + const componentName = getComponentName({ + App + }); + return <div> Component Name is {componentName} <OtherComponent /> - </div> - ) + </div>; } function OtherComponent() { - const componentName = getComponentName({ App }) - return <div>App component name is {componentName}</div> + const componentName = getComponentName({ + App + }); + return <div>App component name is {componentName}</div>; } -export { App as component } +export { App as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/conditional-properties.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/conditional-properties.tsx index e8296b890b..c20dcdc135 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/conditional-properties.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/conditional-properties.tsx @@ -1,11 +1,9 @@ -const $$splitLoaderImporter = () => - import('conditional-properties.tsx?tsr-split=loader') -import { lazyFn } from '@tanstack/react-router' -const $$splitComponentImporter = () => - import('conditional-properties.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitLoaderImporter = () => import('conditional-properties.tsx?tsr-split=loader'); +import { lazyFn } from '@tanstack/react-router'; +const $$splitComponentImporter = () => import('conditional-properties.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/posts')({ component: lazyRouteComponent($$splitComponentImporter, 'component'), - loader: lazyFn($$splitLoaderImporter, 'loader'), -}) + loader: lazyFn($$splitLoaderImporter, 'loader') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/conditional-properties@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/conditional-properties@component---errorComponent---notFoundComponent---pendingComponent.tsx index e460c54467..aaf3410c69 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/conditional-properties@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/conditional-properties@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,5 +1,5 @@ -import { isEnabled } from '@features/feature-flags' -import TrueImport from '@modules/true-component' -import { FalseComponent } from '@modules/false-component' -const SplitComponent = isEnabled ? TrueImport.Component : FalseComponent -export { SplitComponent as component } +import { isEnabled } from '@features/feature-flags'; +import TrueImport from '@modules/true-component'; +import { FalseComponent } from '@modules/false-component'; +const SplitComponent = isEnabled ? TrueImport.Component : FalseComponent; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/conditional-properties@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/conditional-properties@loader.tsx index e5872a344c..e10f305ddc 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/conditional-properties@loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/conditional-properties@loader.tsx @@ -1,5 +1,5 @@ -import { isEnabled } from '@features/feature-flags' -import TrueImport from '@modules/true-component' -import { falseLoader } from '@modules/false-component' -const SplitLoader = isEnabled ? TrueImport.loader : falseLoader -export { SplitLoader as loader } +import { isEnabled } from '@features/feature-flags'; +import TrueImport from '@modules/true-component'; +import { falseLoader } from '@modules/false-component'; +const SplitLoader = isEnabled ? TrueImport.loader : falseLoader; +export { SplitLoader as loader }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-export-multiple.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-export-multiple.tsx index f9e740d637..e411fd54d8 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-export-multiple.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-export-multiple.tsx @@ -1,13 +1,15 @@ -const $$splitComponentImporter = () => - import('destructured-export-multiple.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('destructured-export-multiple.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const getConfig = () => ({ baseUrl: 'https://api.example.com', - timeout: 5000, -}) -export const { baseUrl, timeout } = getConfig() -export const [first, second] = [1, 2] + timeout: 5000 +}); +export const { + baseUrl, + timeout +} = getConfig(); +export const [first, second] = [1, 2]; export const Route = createFileRoute('/about')({ - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-export-multiple@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-export-multiple@component---errorComponent---notFoundComponent---pendingComponent.tsx index 6a15a59c0a..9441b5a689 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-export-multiple@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-export-multiple@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,10 +1,8 @@ -import { baseUrl, timeout } from 'destructured-export-multiple.tsx' +import { baseUrl, timeout } from "destructured-export-multiple.tsx"; function AboutComponent() { - return ( - <div> + return <div> <p>Base URL: {baseUrl}</p> <p>Timeout: {timeout}</p> - </div> - ) + </div>; } -export { AboutComponent as component } +export { AboutComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-export-nested.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-export-nested.tsx index f4fafce158..076c24b06f 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-export-nested.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-export-nested.tsx @@ -1,16 +1,19 @@ -const $$splitComponentImporter = () => - import('destructured-export-nested.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('destructured-export-nested.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; const getConfig = () => ({ - api: { baseUrl: 'https://api.example.com' }, + api: { + baseUrl: 'https://api.example.com' + }, timeout: 5000, - extra: 'data', -}) + extra: 'data' +}); export const { - api: { baseUrl }, + api: { + baseUrl + }, ...rest -} = getConfig() +} = getConfig(); export const Route = createFileRoute('/about')({ - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-export-nested@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-export-nested@component---errorComponent---notFoundComponent---pendingComponent.tsx index 9bc538525f..8ba46e33e1 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-export-nested@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-export-nested@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,9 +1,7 @@ -import { baseUrl } from 'destructured-export-nested.tsx' +import { baseUrl } from "destructured-export-nested.tsx"; function AboutComponent() { - return ( - <div> + return <div> <p>Base URL: {baseUrl}</p> - </div> - ) + </div>; } -export { AboutComponent as component } +export { AboutComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-export.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-export.tsx index b56d070279..3f79ca544b 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-export.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-export.tsx @@ -1,11 +1,17 @@ -const $$splitComponentImporter = () => - import('destructured-export.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('destructured-export.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export function getObjectCallback() { - return { getObject: () => ({ constA: 10, constB: 5 }) } + return { + getObject: () => ({ + constA: 10, + constB: 5 + }) + }; } -export const { getObject } = getObjectCallback() +export const { + getObject +} = getObjectCallback(); export const Route = createFileRoute('/about')({ - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-export@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-export@component---errorComponent---notFoundComponent---pendingComponent.tsx index b0abbd2e6e..f58942d5af 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-export@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-export@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,11 +1,14 @@ export function getObjectCallback() { - return { getObject: () => ({ constA: 10, constB: 5 }) } + return { + getObject: () => ({ + constA: 10, + constB: 5 + }) + }; } function AboutComponent() { - return ( - <div className="p-2"> + return <div className="p-2"> <h3>About</h3> - </div> - ) + </div>; } -export { AboutComponent as component } +export { AboutComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-export@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-export@loader.tsx index 024e0e620e..45fb19eecd 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-export@loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-export@loader.tsx @@ -1,3 +1,8 @@ export function getObjectCallback() { - return { getObject: () => ({ constA: 10, constB: 5 }) } -} + return { + getObject: () => ({ + constA: 10, + constB: 5 + }) + }; +} \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-react-memo-imported-component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-react-memo-imported-component.tsx index e914a58628..c27220acce 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-react-memo-imported-component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-react-memo-imported-component.tsx @@ -1,11 +1,9 @@ -const $$splitLoaderImporter = () => - import('destructured-react-memo-imported-component.tsx?tsr-split=loader') -import { lazyFn } from '@tanstack/react-router' -const $$splitComponentImporter = () => - import('destructured-react-memo-imported-component.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitLoaderImporter = () => import('destructured-react-memo-imported-component.tsx?tsr-split=loader'); +import { lazyFn } from '@tanstack/react-router'; +const $$splitComponentImporter = () => import('destructured-react-memo-imported-component.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/')({ component: lazyRouteComponent($$splitComponentImporter, 'component'), - loader: lazyFn($$splitLoaderImporter, 'loader'), -}) + loader: lazyFn($$splitLoaderImporter, 'loader') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-react-memo-imported-component@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-react-memo-imported-component@component---errorComponent---notFoundComponent---pendingComponent.tsx index 88dcdf6e48..446d55e26b 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-react-memo-imported-component@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-react-memo-imported-component@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,6 +1,6 @@ -import { memo } from 'react' +import { memo } from 'react'; function Component() { - return <div>Component</div> + return <div>Component</div>; } -const SplitComponent = memo(Component) -export { SplitComponent as component } +const SplitComponent = memo(Component); +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-react-memo-imported-component@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-react-memo-imported-component@loader.tsx index 8691aec6ff..52e811be53 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-react-memo-imported-component@loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-react-memo-imported-component@loader.tsx @@ -1,3 +1,3 @@ -import { importedLoader } from '../../shared/imported' -const SplitLoader = importedLoader -export { SplitLoader as loader } +import { importedLoader } from '../../shared/imported'; +const SplitLoader = importedLoader; +export { SplitLoader as loader }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-route-options-defaults.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-route-options-defaults.tsx index bf26704b82..1759b05846 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-route-options-defaults.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-route-options-defaults.tsx @@ -1,11 +1,9 @@ -const $$splitLoaderImporter = () => - import('destructured-route-options-defaults.tsx?tsr-split=loader') -import { lazyFn } from '@tanstack/react-router' -const $$splitComponentImporter = () => - import('destructured-route-options-defaults.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitLoaderImporter = () => import('destructured-route-options-defaults.tsx?tsr-split=loader'); +import { lazyFn } from '@tanstack/react-router'; +const $$splitComponentImporter = () => import('destructured-route-options-defaults.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/about')({ component: lazyRouteComponent($$splitComponentImporter, 'component'), - loader: lazyFn($$splitLoaderImporter, 'loader'), -}) + loader: lazyFn($$splitLoaderImporter, 'loader') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-route-options-defaults@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-route-options-defaults@component---errorComponent---notFoundComponent---pendingComponent.tsx index c26d6be33d..c73696ff32 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-route-options-defaults@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-route-options-defaults@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,2 +1,2 @@ -import { MyComponent } from 'destructured-route-options-defaults.tsx?tsr-shared=1' -export { MyComponent as component } +import { MyComponent } from "destructured-route-options-defaults.tsx?tsr-shared=1"; +export { MyComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-route-options-defaults@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-route-options-defaults@loader.tsx index 3caedc3e55..99d9619b91 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-route-options-defaults@loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-route-options-defaults@loader.tsx @@ -1,2 +1,2 @@ -import { loader } from 'destructured-route-options-defaults.tsx?tsr-shared=1' -export { loader } +import { loader } from "destructured-route-options-defaults.tsx?tsr-shared=1"; +export { loader }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-route-options-defaults@shared.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-route-options-defaults@shared.tsx index a7dee6af52..fdc9acef5b 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-route-options-defaults@shared.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructured-route-options-defaults@shared.tsx @@ -1,23 +1,22 @@ function defaultLoader() { - return { message: 'default' } + return { + message: 'default' + }; } function DefaultComponent() { - return <div>Default</div> + return <div>Default</div>; } const createBits = () => ({ component: ActualComponent, - loader: () => ({ message: 'hello' }), -}) -const { component: MyComponent = DefaultComponent, loader = defaultLoader } = - createBits() + loader: () => ({ + message: 'hello' + }) +}); +const { + component: MyComponent = DefaultComponent, + loader = defaultLoader +} = createBits(); function ActualComponent() { - return <div>About</div> -} -export { - ActualComponent, - createBits, - DefaultComponent, - defaultLoader, - loader, - MyComponent, + return <div>About</div>; } +export { ActualComponent, createBits, DefaultComponent, defaultLoader, loader, MyComponent }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructuring.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructuring.tsx index 112fded569..d80f17484f 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructuring.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructuring.tsx @@ -1,9 +1,11 @@ import thing from 'thing' + export function test() { const { foo: { bar: { destructured }, }, } = thing + return destructured } diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructuring@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructuring@component---errorComponent---notFoundComponent---pendingComponent.tsx index 112fded569..858c5c0e05 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructuring@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructuring@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,9 +1,11 @@ -import thing from 'thing' +import thing from 'thing'; export function test() { const { foo: { - bar: { destructured }, - }, - } = thing - return destructured -} + bar: { + destructured + } + } + } = thing; + return destructured; +} \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructuring@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructuring@loader.tsx index 112fded569..858c5c0e05 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructuring@loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/destructuring@loader.tsx @@ -1,9 +1,11 @@ -import thing from 'thing' +import thing from 'thing'; export function test() { const { foo: { - bar: { destructured }, - }, - } = thing - return destructured -} + bar: { + destructured + } + } + } = thing; + return destructured; +} \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/directive-prologue.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/directive-prologue.tsx index a5bca5a02c..12d3529331 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/directive-prologue.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/directive-prologue.tsx @@ -1,8 +1,8 @@ -'use client' -const $$splitComponentImporter = () => - import('directive-prologue.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +'use client'; + +const $$splitComponentImporter = () => import('directive-prologue.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/directive')({ - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/directive-prologue@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/directive-prologue@component---errorComponent---notFoundComponent---pendingComponent.tsx index 9ee4bd8f4c..ce7cd5e5ee 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/directive-prologue@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/directive-prologue@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,5 +1,6 @@ -'use client' +'use client'; + const SplitComponent = () => { - return <div>directive preserved</div> -} -export { SplitComponent as component } + return <div>directive preserved</div>; +}; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/explicit-undefined-component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/explicit-undefined-component.tsx index 8109a89624..4fdd9d1c68 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/explicit-undefined-component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/explicit-undefined-component.tsx @@ -1,3 +1,6 @@ import React from 'react' import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/')({ component: undefined }) + +export const Route = createFileRoute('/')({ + component: undefined, +}) diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/explicit-undefined-component@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/explicit-undefined-component@component---errorComponent---notFoundComponent---pendingComponent.tsx index b45dfaa8f0..b01f5e7863 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/explicit-undefined-component@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/explicit-undefined-component@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1 +1 @@ -import React from 'react' +import React from 'react'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/explicit-undefined-component@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/explicit-undefined-component@loader.tsx index b45dfaa8f0..b01f5e7863 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/explicit-undefined-component@loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/explicit-undefined-component@loader.tsx @@ -1 +1 @@ -import React from 'react' +import React from 'react'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/export-default-component-and-normal-notFound.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/export-default-component-and-normal-notFound.tsx index fc6cef74a4..0ca25a7017 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/export-default-component-and-normal-notFound.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/export-default-component-and-normal-notFound.tsx @@ -1,23 +1,15 @@ -console.warn( - '[tanstack-router] These exports from "export-default-component-and-normal-notFound.tsx" will not be code-split and will increase your bundle size:\n- Home\nFor the best optimization, these items should either have their export statements removed, or be imported from another location that is not a route file.', -) -const $$splitNotFoundComponentImporter = () => - import('export-default-component-and-normal-notFound.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import React, { useState } from 'react' -import { createFileRoute } from '@tanstack/react-router' +console.warn("[tanstack-router] These exports from \"export-default-component-and-normal-notFound.tsx\" will not be code-split and will increase your bundle size:\n- Home\nFor the best optimization, these items should either have their export statements removed, or be imported from another location that is not a route file."); +const $$splitNotFoundComponentImporter = () => import('export-default-component-and-normal-notFound.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import React, { useState } from 'react'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/home')({ component: Home, - notFoundComponent: lazyRouteComponent( - $$splitNotFoundComponentImporter, - 'notFoundComponent', - ), -}) + notFoundComponent: lazyRouteComponent($$splitNotFoundComponentImporter, 'notFoundComponent') +}); export default function Home() { - const [one, setOne] = useState('this is from a state') - return ( - <div> + const [one, setOne] = useState('this is from a state'); + return <div> <h1>{one}</h1> - </div> - ) -} + </div>; +} \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/export-default-component-and-normal-notFound@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/export-default-component-and-normal-notFound@component---errorComponent---notFoundComponent---pendingComponent.tsx index 3da924c04c..62cd0a1036 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/export-default-component-and-normal-notFound@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/export-default-component-and-normal-notFound@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,5 +1,5 @@ -import React from 'react' +import React from 'react'; function NotFoundComponent() { - return <div>Not Found</div> + return <div>Not Found</div>; } -export { NotFoundComponent as notFoundComponent } +export { NotFoundComponent as notFoundComponent }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/export-default-component-and-normal-notFound@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/export-default-component-and-normal-notFound@loader.tsx index b45dfaa8f0..b01f5e7863 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/export-default-component-and-normal-notFound@loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/export-default-component-and-normal-notFound@loader.tsx @@ -1 +1 @@ -import React from 'react' +import React from 'react'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/export-default-component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/export-default-component.tsx index de2d748c91..c5198b9e00 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/export-default-component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/export-default-component.tsx @@ -1,8 +1,13 @@ import React, { useState } from 'react' import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/home')({ component: Home }) + +export const Route = createFileRoute('/home')({ + component: Home, +}) + export default function Home() { const [one, setOne] = useState('this is from a state') + return ( <div> <h1>{one}</h1> diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/export-default-component@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/export-default-component@component---errorComponent---notFoundComponent---pendingComponent.tsx index b45dfaa8f0..b01f5e7863 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/export-default-component@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/export-default-component@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1 +1 @@ -import React from 'react' +import React from 'react'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/export-default-component@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/export-default-component@loader.tsx index b45dfaa8f0..b01f5e7863 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/export-default-component@loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/export-default-component@loader.tsx @@ -1 +1 @@ -import React from 'react' +import React from 'react'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/function-as-parameter.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/function-as-parameter.tsx index 817b89d69a..3ae9710cd5 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/function-as-parameter.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/function-as-parameter.tsx @@ -1,20 +1,29 @@ import * as React from 'react' // @ts-expect-error import { useMemo } from 'tan-react' + const useUsedVar = 'i-am-unused' + const ReactUseMemoCall1 = React.useMemo(function performAction() { return 'true' }, []) + console.info(ReactUseMemoCall1) + const ReactUseMemoCall2 = React.useMemo(() => { return 'true' }, []) + console.info(ReactUseMemoCall2) + const UseMemoCall1 = useMemo(function performAction() { return 'true' }, []) + console.info(UseMemoCall1) + const UseMemoCall2 = useMemo(() => { return 'true' }, []) + console.info(UseMemoCall2) diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/function-as-parameter@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/function-as-parameter@component---errorComponent---notFoundComponent---pendingComponent.tsx index 817b89d69a..23e2cd0f03 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/function-as-parameter@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/function-as-parameter@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,20 +1,20 @@ -import * as React from 'react' +import * as React from 'react'; // @ts-expect-error -import { useMemo } from 'tan-react' -const useUsedVar = 'i-am-unused' +import { useMemo } from 'tan-react'; +const useUsedVar = 'i-am-unused'; const ReactUseMemoCall1 = React.useMemo(function performAction() { - return 'true' -}, []) -console.info(ReactUseMemoCall1) + return 'true'; +}, []); +console.info(ReactUseMemoCall1); const ReactUseMemoCall2 = React.useMemo(() => { - return 'true' -}, []) -console.info(ReactUseMemoCall2) + return 'true'; +}, []); +console.info(ReactUseMemoCall2); const UseMemoCall1 = useMemo(function performAction() { - return 'true' -}, []) -console.info(UseMemoCall1) + return 'true'; +}, []); +console.info(UseMemoCall1); const UseMemoCall2 = useMemo(() => { - return 'true' -}, []) -console.info(UseMemoCall2) + return 'true'; +}, []); +console.info(UseMemoCall2); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/function-as-parameter@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/function-as-parameter@loader.tsx index 817b89d69a..23e2cd0f03 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/function-as-parameter@loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/function-as-parameter@loader.tsx @@ -1,20 +1,20 @@ -import * as React from 'react' +import * as React from 'react'; // @ts-expect-error -import { useMemo } from 'tan-react' -const useUsedVar = 'i-am-unused' +import { useMemo } from 'tan-react'; +const useUsedVar = 'i-am-unused'; const ReactUseMemoCall1 = React.useMemo(function performAction() { - return 'true' -}, []) -console.info(ReactUseMemoCall1) + return 'true'; +}, []); +console.info(ReactUseMemoCall1); const ReactUseMemoCall2 = React.useMemo(() => { - return 'true' -}, []) -console.info(ReactUseMemoCall2) + return 'true'; +}, []); +console.info(ReactUseMemoCall2); const UseMemoCall1 = useMemo(function performAction() { - return 'true' -}, []) -console.info(UseMemoCall1) + return 'true'; +}, []); +console.info(UseMemoCall1); const UseMemoCall2 = useMemo(() => { - return 'true' -}, []) -console.info(UseMemoCall2) + return 'true'; +}, []); +console.info(UseMemoCall2); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/function-declaration.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/function-declaration.tsx index b12490e0a5..c191f9fddd 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/function-declaration.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/function-declaration.tsx @@ -1,12 +1,10 @@ -const $$splitComponentImporter = () => - import('function-declaration.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -const $$splitLoaderImporter = () => - import('function-declaration.tsx?tsr-split=loader') -import { lazyFn } from '@tanstack/react-router' -import * as React from 'react' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('function-declaration.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +const $$splitLoaderImporter = () => import('function-declaration.tsx?tsr-split=loader'); +import { lazyFn } from '@tanstack/react-router'; +import * as React from 'react'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/posts')({ loader: lazyFn($$splitLoaderImporter, 'loader'), - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/function-declaration@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/function-declaration@component---errorComponent---notFoundComponent---pendingComponent.tsx index a0ebf07dee..3476c52d54 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/function-declaration@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/function-declaration@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,31 +1,27 @@ -import * as React from 'react' -import { Link, Outlet } from '@tanstack/react-router' -import { Route } from 'function-declaration.tsx' +import * as React from 'react'; +import { Link, Outlet } from '@tanstack/react-router'; +import { Route } from "function-declaration.tsx"; function PostsComponent() { - const posts = Route.useLoaderData() - return ( - <div className="p-2 flex gap-2"> + const posts = Route.useLoaderData(); + return <div className="p-2 flex gap-2"> <ul className="list-disc pl-4"> - {[...posts, { id: 'i-do-not-exist', title: 'Non-existent Post' }]?.map( - (post) => { - return ( - <li key={post.id} className="whitespace-nowrap"> - <Link - to="/posts/$postId" - params={{ postId: post.id }} - className="block py-1 text-blue-800 hover:text-blue-600" - activeProps={{ className: 'text-black font-bold' }} - > + {[...posts, { + id: 'i-do-not-exist', + title: 'Non-existent Post' + }]?.map(post => { + return <li key={post.id} className="whitespace-nowrap"> + <Link to="/posts/$postId" params={{ + postId: post.id + }} className="block py-1 text-blue-800 hover:text-blue-600" activeProps={{ + className: 'text-black font-bold' + }}> <div>{post.title.substring(0, 20)}</div> </Link> - </li> - ) - }, - )} + </li>; + })} </ul> <hr /> <Outlet /> - </div> - ) + </div>; } -export { PostsComponent as component } +export { PostsComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/function-declaration@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/function-declaration@loader.tsx index 1c4fc213ed..cb195afdd8 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/function-declaration@loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/function-declaration@loader.tsx @@ -1,4 +1,4 @@ -import * as React from 'react' -import { fetchPosts } from '../posts' -const SplitLoader = fetchPosts -export { SplitLoader as loader } +import * as React from 'react'; +import { fetchPosts } from '../posts'; +const SplitLoader = fetchPosts; +export { SplitLoader as loader }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/importAttribute.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/importAttribute.tsx index b6b9c182dc..e2aab465f5 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/importAttribute.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/importAttribute.tsx @@ -1,7 +1,6 @@ -const $$splitComponentImporter = () => - import('importAttribute.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('importAttribute.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/')({ - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/importAttribute@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/importAttribute@component---errorComponent---notFoundComponent---pendingComponent.tsx index 88abef0c00..f34d3c6408 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/importAttribute@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/importAttribute@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,3 +1,3 @@ -import { test } from './test' with { type: 'macro' } -const SplitComponent = () => test -export { SplitComponent as component } +import { test } from './test' with { type: 'macro' }; +const SplitComponent = () => test; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-default-component-destructured-loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-default-component-destructured-loader.tsx index 969129bdf2..70d5be8c3f 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-default-component-destructured-loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-default-component-destructured-loader.tsx @@ -1,11 +1,9 @@ -const $$splitLoaderImporter = () => - import('imported-default-component-destructured-loader.tsx?tsr-split=loader') -import { lazyFn } from '@tanstack/react-router' -const $$splitComponentImporter = () => - import('imported-default-component-destructured-loader.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitLoaderImporter = () => import('imported-default-component-destructured-loader.tsx?tsr-split=loader'); +import { lazyFn } from '@tanstack/react-router'; +const $$splitComponentImporter = () => import('imported-default-component-destructured-loader.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/')({ component: lazyRouteComponent($$splitComponentImporter, 'component'), - loader: lazyFn($$splitLoaderImporter, 'loader'), -}) + loader: lazyFn($$splitLoaderImporter, 'loader') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-default-component-destructured-loader@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-default-component-destructured-loader@component---errorComponent---notFoundComponent---pendingComponent.tsx index 9350cda9e8..d21b198c98 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-default-component-destructured-loader@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-default-component-destructured-loader@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,3 +1,3 @@ -import importedComponent from '../../shared/imported' -const SplitComponent = importedComponent -export { SplitComponent as component } +import importedComponent from '../../shared/imported'; +const SplitComponent = importedComponent; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-default-component-destructured-loader@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-default-component-destructured-loader@loader.tsx index 8691aec6ff..52e811be53 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-default-component-destructured-loader@loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-default-component-destructured-loader@loader.tsx @@ -1,3 +1,3 @@ -import { importedLoader } from '../../shared/imported' -const SplitLoader = importedLoader -export { SplitLoader as loader } +import { importedLoader } from '../../shared/imported'; +const SplitLoader = importedLoader; +export { SplitLoader as loader }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-default-component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-default-component.tsx index f793a41de9..601c1f656a 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-default-component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-default-component.tsx @@ -1,7 +1,6 @@ -const $$splitComponentImporter = () => - import('imported-default-component.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('imported-default-component.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/')({ - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-default-component@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-default-component@component---errorComponent---notFoundComponent---pendingComponent.tsx index d356227040..31ccf07c52 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-default-component@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-default-component@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,3 +1,3 @@ -import ImportedDefaultComponent from '../../shared/imported' -const SplitComponent = ImportedDefaultComponent -export { SplitComponent as component } +import ImportedDefaultComponent from '../../shared/imported'; +const SplitComponent = ImportedDefaultComponent; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-errorComponent.tsx index 13e87eb7f1..4df12c02de 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-errorComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-errorComponent.tsx @@ -1,13 +1,8 @@ -const $$splitErrorComponentImporter = () => - import('imported-errorComponent.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -const $$splitComponentImporter = () => - import('imported-errorComponent.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitErrorComponentImporter = () => import('imported-errorComponent.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +const $$splitComponentImporter = () => import('imported-errorComponent.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/')({ component: lazyRouteComponent($$splitComponentImporter, 'component'), - errorComponent: lazyRouteComponent( - $$splitErrorComponentImporter, - 'errorComponent', - ), -}) + errorComponent: lazyRouteComponent($$splitErrorComponentImporter, 'errorComponent') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-errorComponent@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-errorComponent@component---errorComponent---notFoundComponent---pendingComponent.tsx index b5bded20a6..d8a0fcf9ff 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-errorComponent@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-errorComponent@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,7 +1,5 @@ -import ImportedDefaultComponent, { - importedErrorComponent, -} from '../../shared/imported' -const SplitComponent = ImportedDefaultComponent -export { SplitComponent as component } -const SplitErrorComponent = importedErrorComponent -export { SplitErrorComponent as errorComponent } +import ImportedDefaultComponent, { importedErrorComponent } from '../../shared/imported'; +const SplitComponent = ImportedDefaultComponent; +export { SplitComponent as component }; +const SplitErrorComponent = importedErrorComponent; +export { SplitErrorComponent as errorComponent }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-notFoundComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-notFoundComponent.tsx index 48b7f7f6bf..716ec0ca3a 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-notFoundComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-notFoundComponent.tsx @@ -1,13 +1,8 @@ -const $$splitNotFoundComponentImporter = () => - import('imported-notFoundComponent.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -const $$splitComponentImporter = () => - import('imported-notFoundComponent.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitNotFoundComponentImporter = () => import('imported-notFoundComponent.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +const $$splitComponentImporter = () => import('imported-notFoundComponent.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/')({ component: lazyRouteComponent($$splitComponentImporter, 'component'), - notFoundComponent: lazyRouteComponent( - $$splitNotFoundComponentImporter, - 'notFoundComponent', - ), -}) + notFoundComponent: lazyRouteComponent($$splitNotFoundComponentImporter, 'notFoundComponent') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-notFoundComponent@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-notFoundComponent@component---errorComponent---notFoundComponent---pendingComponent.tsx index 9f904a1a19..1273c7c50d 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-notFoundComponent@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-notFoundComponent@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,7 +1,5 @@ -import ImportedDefaultComponent, { - importedNotFoundComponent, -} from '../../shared/imported' -const SplitComponent = ImportedDefaultComponent -export { SplitComponent as component } -const SplitNotFoundComponent = importedNotFoundComponent -export { SplitNotFoundComponent as notFoundComponent } +import ImportedDefaultComponent, { importedNotFoundComponent } from '../../shared/imported'; +const SplitComponent = ImportedDefaultComponent; +export { SplitComponent as component }; +const SplitNotFoundComponent = importedNotFoundComponent; +export { SplitNotFoundComponent as notFoundComponent }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-pendingComponent.tsx index c22e117560..5a5aa789f7 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-pendingComponent.tsx @@ -1,13 +1,8 @@ -const $$splitPendingComponentImporter = () => - import('imported-pendingComponent.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -const $$splitComponentImporter = () => - import('imported-pendingComponent.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitPendingComponentImporter = () => import('imported-pendingComponent.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +const $$splitComponentImporter = () => import('imported-pendingComponent.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/')({ component: lazyRouteComponent($$splitComponentImporter, 'component'), - pendingComponent: lazyRouteComponent( - $$splitPendingComponentImporter, - 'pendingComponent', - ), -}) + pendingComponent: lazyRouteComponent($$splitPendingComponentImporter, 'pendingComponent') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-pendingComponent@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-pendingComponent@component---errorComponent---notFoundComponent---pendingComponent.tsx index d24c7b1505..0368000afa 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-pendingComponent@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported-pendingComponent@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,7 +1,5 @@ -import ImportedDefaultComponent, { - importedPendingComponent, -} from '../../shared/imported' -const SplitComponent = ImportedDefaultComponent -export { SplitComponent as component } -const SplitPendingComponent = importedPendingComponent -export { SplitPendingComponent as pendingComponent } +import ImportedDefaultComponent, { importedPendingComponent } from '../../shared/imported'; +const SplitComponent = ImportedDefaultComponent; +export { SplitComponent as component }; +const SplitPendingComponent = importedPendingComponent; +export { SplitPendingComponent as pendingComponent }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported.tsx index 54a7733167..dd3299b1b1 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported.tsx @@ -1,10 +1,9 @@ -const $$splitLoaderImporter = () => import('imported.tsx?tsr-split=loader') -import { lazyFn } from '@tanstack/react-router' -const $$splitComponentImporter = () => - import('imported.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitLoaderImporter = () => import('imported.tsx?tsr-split=loader'); +import { lazyFn } from '@tanstack/react-router'; +const $$splitComponentImporter = () => import('imported.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/')({ component: lazyRouteComponent($$splitComponentImporter, 'component'), - loader: lazyFn($$splitLoaderImporter, 'loader'), -}) + loader: lazyFn($$splitLoaderImporter, 'loader') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported@component---errorComponent---notFoundComponent---pendingComponent.tsx index e3c06dbe9e..5bc9da8d43 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,3 +1,3 @@ -import { importedComponent } from '../../shared' -const SplitComponent = importedComponent -export { SplitComponent as component } +import { importedComponent } from '../../shared'; +const SplitComponent = importedComponent; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported@loader.tsx index d0418cbce3..9b91fafd91 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported@loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/imported@loader.tsx @@ -1,3 +1,3 @@ -import { importedLoader } from '../../shared' -const SplitLoader = importedLoader -export { SplitLoader as loader } +import { importedLoader } from '../../shared'; +const SplitLoader = importedLoader; +export { SplitLoader as loader }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/inline.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/inline.tsx index 3c27842428..960f639c0a 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/inline.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/inline.tsx @@ -1,10 +1,9 @@ -const $$splitComponentImporter = () => - import('inline.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import * as React from 'react' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('inline.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import * as React from 'react'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/')({ - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) -Route.addChildren([]) -export const test = 'test' + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); +Route.addChildren([]); +export const test = 'test'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/inline@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/inline@component---errorComponent---notFoundComponent---pendingComponent.tsx index d28b872634..58ccfb2903 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/inline@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/inline@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,18 +1,18 @@ -import * as React from 'react' -import * as styles from '../style.css' -import { TEST_DATA } from '../test.const' -const Button = (props: { children: any }) => { - return <button>{props.children}</button> -} -import { Route } from 'inline.tsx' -import { test } from 'inline.tsx' +import * as React from 'react'; +import * as styles from '../style.css'; +import { TEST_DATA } from '../test.const'; +const Button = (props: { + children: any; +}) => { + return <button>{props.children}</button>; +}; +import { Route } from "inline.tsx"; +import { test } from "inline.tsx"; const SplitComponent = () => { - return ( - <div className="p-2"> - {test} - <h3 className={styles.indexPageTitle}>{TEST_DATA.welcome}</h3> - <Button>Click me</Button> - </div> - ) -} -export { SplitComponent as component } + return <div className="p-2"> + {test} + <h3 className={styles.indexPageTitle}>{TEST_DATA.welcome}</h3> + <Button>Click me</Button> + </div>; +}; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/inline@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/inline@loader.tsx index 23fab71edc..9236af6021 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/inline@loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/inline@loader.tsx @@ -1,2 +1,2 @@ -import * as React from 'react' -import { Route } from 'inline.tsx' +import * as React from 'react'; +import { Route } from "inline.tsx"; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/lowercase-function-declaration.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/lowercase-function-declaration.tsx deleted file mode 100644 index 79ef82a7af..0000000000 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/lowercase-function-declaration.tsx +++ /dev/null @@ -1,19 +0,0 @@ -const $$splitErrorComponentImporter = () => - import('lowercase-function-declaration.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -const $$splitPendingComponentImporter = () => - import('lowercase-function-declaration.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -const $$splitComponentImporter = () => - import('lowercase-function-declaration.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/')({ - component: lazyRouteComponent($$splitComponentImporter, 'component'), - pendingComponent: lazyRouteComponent( - $$splitPendingComponentImporter, - 'pendingComponent', - ), - errorComponent: lazyRouteComponent( - $$splitErrorComponentImporter, - 'errorComponent', - ), -}) diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/lowercase-function-declaration@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/lowercase-function-declaration@component---errorComponent---notFoundComponent---pendingComponent.tsx deleted file mode 100644 index ec003091fb..0000000000 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/lowercase-function-declaration@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ /dev/null @@ -1,12 +0,0 @@ -function component() { - return <div>lowercase function declaration</div> -} -function pendingComponent() { - return <div>lowercase pending function declaration</div> -} -function errorComponent() { - return <div>lowercase error function declaration</div> -} -export { component } -export { pendingComponent } -export { errorComponent } diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/lowercase-function-declaration@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/lowercase-function-declaration@loader.tsx deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/lowercase-function-declaration@shared.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/lowercase-function-declaration@shared.tsx deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/random-number.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/random-number.tsx index 440e1f4253..a345d17ae7 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/random-number.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/random-number.tsx @@ -1,41 +1,28 @@ -const $$splitComponentImporter = () => - import('random-number.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -const $$splitLoaderImporter = () => import('random-number.tsx?tsr-split=loader') -import { lazyFn } from '@tanstack/react-router' -import { Await, Link, createFileRoute } from '@tanstack/react-router' -import { Carbon } from '~/components/Carbon' -import { twMerge } from 'tailwind-merge' -import { FaDiscord, FaGithub, FaTshirt } from 'react-icons/fa' -import { CgMusicSpeaker, CgSpinner } from 'react-icons/cg' -import { Footer } from '~/components/Footer' -import SponsorPack from '~/components/SponsorPack' -import { LogoColor } from '~/components/LogoColor' -import agGridImage from '~/images/ag-grid.png' -import nozzleImage from '~/images/nozzle.png' -import bytesImage from '~/images/bytes.svg' -import bytesUidotdevImage from '~/images/bytes-uidotdev.png' -export const textColors = [ - `text-rose-500`, - `text-yellow-500`, - `text-teal-500`, - `text-blue-500`, -] -export const gradients = [ - `from-rose-500 to-yellow-500`, - `from-yellow-500 to-teal-500`, - `from-teal-500 to-violet-500`, - `from-blue-500 to-pink-500`, -] -const courses = [ - { - name: 'The Official TanStack React Query Course', - cardStyles: `border-t-4 border-red-500 hover:(border-green-500)`, - href: 'https://query.gg/?s=tanstack', - description: `Learn how to build enterprise quality apps with TanStack's React Query the easy way with our brand new course.`, - }, -] +const $$splitComponentImporter = () => import('random-number.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +const $$splitLoaderImporter = () => import('random-number.tsx?tsr-split=loader'); +import { lazyFn } from '@tanstack/react-router'; +import { Await, Link, createFileRoute } from '@tanstack/react-router'; +import { Carbon } from '~/components/Carbon'; +import { twMerge } from 'tailwind-merge'; +import { FaDiscord, FaGithub, FaTshirt } from 'react-icons/fa'; +import { CgMusicSpeaker, CgSpinner } from 'react-icons/cg'; +import { Footer } from '~/components/Footer'; +import SponsorPack from '~/components/SponsorPack'; +import { LogoColor } from '~/components/LogoColor'; +import agGridImage from '~/images/ag-grid.png'; +import nozzleImage from '~/images/nozzle.png'; +import bytesImage from '~/images/bytes.svg'; +import bytesUidotdevImage from '~/images/bytes-uidotdev.png'; +export const textColors = [`text-rose-500`, `text-yellow-500`, `text-teal-500`, `text-blue-500`]; +export const gradients = [`from-rose-500 to-yellow-500`, `from-yellow-500 to-teal-500`, `from-teal-500 to-violet-500`, `from-blue-500 to-pink-500`]; +const courses = [{ + name: 'The Official TanStack React Query Course', + cardStyles: `border-t-4 border-red-500 hover:(border-green-500)`, + href: 'https://query.gg/?s=tanstack', + description: `Learn how to build enterprise quality apps with TanStack's React Query the easy way with our brand new course.` +}]; export const Route = createFileRoute('/')({ loader: lazyFn($$splitLoaderImporter, 'loader'), - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/random-number@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/random-number@component---errorComponent---notFoundComponent---pendingComponent.tsx index 26a9f9c142..9ed6d15184 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/random-number@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/random-number@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,48 +1,61 @@ -import { Await, Link } from '@tanstack/react-router' -import { Carbon } from '~/components/Carbon' -import { twMerge } from 'tailwind-merge' -import { FaDiscord, FaGithub, FaTshirt } from 'react-icons/fa' -import { CgMusicSpeaker, CgSpinner } from 'react-icons/cg' -import { Footer } from '~/components/Footer' -import SponsorPack from '~/components/SponsorPack' -import { LogoColor } from '~/components/LogoColor' -import discordImage from '~/images/discord-logo-white.svg' -import agGridImage from '~/images/ag-grid.png' -import nozzleImage from '~/images/nozzle.png' -import bytesImage from '~/images/bytes.svg' -import bytesUidotdevImage from '~/images/bytes-uidotdev.png' -import { useMutation } from '~/hooks/useMutation' -import { sample } from '~/utils/utils' -import { textColors } from 'random-number.tsx' -import { gradients } from 'random-number.tsx' -const courses = [ - { - name: 'The Official TanStack React Query Course', - cardStyles: `border-t-4 border-red-500 hover:(border-green-500)`, - href: 'https://query.gg/?s=tanstack', - description: `Learn how to build enterprise quality apps with TanStack's React Query the easy way with our brand new course.`, - }, -] -import { Route } from 'random-number.tsx' -async function bytesSignupServerFn({ email }: { email: string }) { - 'use server' +import { Await, Link } from '@tanstack/react-router'; +import { Carbon } from '~/components/Carbon'; +import { twMerge } from 'tailwind-merge'; +import { FaDiscord, FaGithub, FaTshirt } from 'react-icons/fa'; +import { CgMusicSpeaker, CgSpinner } from 'react-icons/cg'; +import { Footer } from '~/components/Footer'; +import SponsorPack from '~/components/SponsorPack'; +import { LogoColor } from '~/components/LogoColor'; +import discordImage from '~/images/discord-logo-white.svg'; +import agGridImage from '~/images/ag-grid.png'; +import nozzleImage from '~/images/nozzle.png'; +import bytesImage from '~/images/bytes.svg'; +import bytesUidotdevImage from '~/images/bytes-uidotdev.png'; +import { useMutation } from '~/hooks/useMutation'; +import { sample } from '~/utils/utils'; +import { textColors } from "random-number.tsx"; +import { gradients } from "random-number.tsx"; +const courses = [{ + name: 'The Official TanStack React Query Course', + cardStyles: `border-t-4 border-red-500 hover:(border-green-500)`, + href: 'https://query.gg/?s=tanstack', + description: `Learn how to build enterprise quality apps with TanStack's React Query the easy way with our brand new course.` +}]; +import { Route } from "random-number.tsx"; +async function bytesSignupServerFn({ + email +}: { + email: string; +}) { + 'use server'; + return fetch(`https://bytes.dev/api/bytes-optin-cors`, { method: 'POST', - body: JSON.stringify({ email, influencer: 'tanstack' }), - headers: { Accept: 'application/json', 'Content-Type': 'application/json' }, - }) + body: JSON.stringify({ + email, + influencer: 'tanstack' + }), + headers: { + Accept: 'application/json', + 'Content-Type': 'application/json' + } + }); } function Index() { - const bytesSignupMutation = useMutation({ fn: bytesSignupServerFn }) - const { sponsorsPromise, randomNumber, testing2 } = Route.useLoaderData() - const gradient = sample(gradients, randomNumber) - const textColor = sample(textColors, randomNumber) - return ( - <> + const bytesSignupMutation = useMutation({ + fn: bytesSignupServerFn + }); + const { + sponsorsPromise, + randomNumber, + testing2 + } = Route.useLoaderData(); + const gradient = sample(gradients, randomNumber); + const textColor = sample(textColors, randomNumber); + return <> {discordImage} {gradient} {textColor} - </> - ) + </>; } -export { Index as component } +export { Index as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/random-number@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/random-number@loader.tsx index 0e7d41451e..9f854acfb0 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/random-number@loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/random-number@loader.tsx @@ -1,28 +1,26 @@ -import { Await, Link, defer } from '@tanstack/react-router' -import { Carbon } from '~/components/Carbon' -import { twMerge } from 'tailwind-merge' -import { FaDiscord, FaGithub, FaTshirt } from 'react-icons/fa' -import { CgMusicSpeaker, CgSpinner } from 'react-icons/cg' -import { Footer } from '~/components/Footer' -import SponsorPack from '~/components/SponsorPack' -import { LogoColor } from '~/components/LogoColor' -import { getSponsorsForSponsorPack } from '~/server/sponsors' -import agGridImage from '~/images/ag-grid.png' -import nozzleImage from '~/images/nozzle.png' -import bytesImage from '~/images/bytes.svg' -import bytesUidotdevImage from '~/images/bytes-uidotdev.png' -const courses = [ - { - name: 'The Official TanStack React Query Course', - cardStyles: `border-t-4 border-red-500 hover:(border-green-500)`, - href: 'https://query.gg/?s=tanstack', - description: `Learn how to build enterprise quality apps with TanStack's React Query the easy way with our brand new course.`, - }, -] +import { Await, Link, defer } from '@tanstack/react-router'; +import { Carbon } from '~/components/Carbon'; +import { twMerge } from 'tailwind-merge'; +import { FaDiscord, FaGithub, FaTshirt } from 'react-icons/fa'; +import { CgMusicSpeaker, CgSpinner } from 'react-icons/cg'; +import { Footer } from '~/components/Footer'; +import SponsorPack from '~/components/SponsorPack'; +import { LogoColor } from '~/components/LogoColor'; +import { getSponsorsForSponsorPack } from '~/server/sponsors'; +import agGridImage from '~/images/ag-grid.png'; +import nozzleImage from '~/images/nozzle.png'; +import bytesImage from '~/images/bytes.svg'; +import bytesUidotdevImage from '~/images/bytes-uidotdev.png'; +const courses = [{ + name: 'The Official TanStack React Query Course', + cardStyles: `border-t-4 border-red-500 hover:(border-green-500)`, + href: 'https://query.gg/?s=tanstack', + description: `Learn how to build enterprise quality apps with TanStack's React Query the easy way with our brand new course.` +}]; const SplitLoader = () => { return { randomNumber: Math.random(), - sponsorsPromise: defer(getSponsorsForSponsorPack()), - } -} -export { SplitLoader as loader } + sponsorsPromise: defer(getSponsorsForSponsorPack()) + }; +}; +export { SplitLoader as loader }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/react-memo-component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/react-memo-component.tsx index 9be4f76d08..eea3e62996 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/react-memo-component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/react-memo-component.tsx @@ -1,11 +1,9 @@ -const $$splitLoaderImporter = () => - import('react-memo-component.tsx?tsr-split=loader') -import { lazyFn } from '@tanstack/react-router' -const $$splitComponentImporter = () => - import('react-memo-component.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitLoaderImporter = () => import('react-memo-component.tsx?tsr-split=loader'); +import { lazyFn } from '@tanstack/react-router'; +const $$splitComponentImporter = () => import('react-memo-component.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/')({ component: lazyRouteComponent($$splitComponentImporter, 'component'), - loader: lazyFn($$splitLoaderImporter, 'loader'), -}) + loader: lazyFn($$splitLoaderImporter, 'loader') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/react-memo-component@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/react-memo-component@component---errorComponent---notFoundComponent---pendingComponent.tsx index 6bdb537fe9..dfef29c9e3 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/react-memo-component@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/react-memo-component@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,6 +1,6 @@ -import React from 'react' +import React from 'react'; function Component() { - return <div>Component</div> + return <div>Component</div>; } -const SplitComponent = React.memo(Component) -export { SplitComponent as component } +const SplitComponent = React.memo(Component); +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/react-memo-component@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/react-memo-component@loader.tsx index 8691aec6ff..52e811be53 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/react-memo-component@loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/react-memo-component@loader.tsx @@ -1,3 +1,3 @@ -import { importedLoader } from '../../shared/imported' -const SplitLoader = importedLoader -export { SplitLoader as loader } +import { importedLoader } from '../../shared/imported'; +const SplitLoader = importedLoader; +export { SplitLoader as loader }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/react-memo-imported-component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/react-memo-imported-component.tsx index 2637f8de7a..e445bcbb72 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/react-memo-imported-component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/react-memo-imported-component.tsx @@ -1,11 +1,9 @@ -const $$splitLoaderImporter = () => - import('react-memo-imported-component.tsx?tsr-split=loader') -import { lazyFn } from '@tanstack/react-router' -const $$splitComponentImporter = () => - import('react-memo-imported-component.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitLoaderImporter = () => import('react-memo-imported-component.tsx?tsr-split=loader'); +import { lazyFn } from '@tanstack/react-router'; +const $$splitComponentImporter = () => import('react-memo-imported-component.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/')({ component: lazyRouteComponent($$splitComponentImporter, 'component'), - loader: lazyFn($$splitLoaderImporter, 'loader'), -}) + loader: lazyFn($$splitLoaderImporter, 'loader') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/react-memo-imported-component@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/react-memo-imported-component@component---errorComponent---notFoundComponent---pendingComponent.tsx index d162a1aeaf..540812230e 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/react-memo-imported-component@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/react-memo-imported-component@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,4 +1,4 @@ -import React from 'react' -import { importedComponent } from '../../shared/imported' -const SplitComponent = React.memo(importedComponent) -export { SplitComponent as component } +import React from 'react'; +import { importedComponent } from '../../shared/imported'; +const SplitComponent = React.memo(importedComponent); +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/react-memo-imported-component@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/react-memo-imported-component@loader.tsx index 8691aec6ff..52e811be53 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/react-memo-imported-component@loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/react-memo-imported-component@loader.tsx @@ -1,3 +1,3 @@ -import { importedLoader } from '../../shared/imported' -const SplitLoader = importedLoader -export { SplitLoader as loader } +import { importedLoader } from '../../shared/imported'; +const SplitLoader = importedLoader; +export { SplitLoader as loader }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-export-component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-export-component.tsx index 1b374dd690..f22aa236e1 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-export-component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-export-component.tsx @@ -1,16 +1,14 @@ -console.warn( - '[tanstack-router] These exports from "retain-export-component.tsx" will not be code-split and will increase your bundle size:\n- Layout\nFor the best optimization, these items should either have their export statements removed, or be imported from another location that is not a route file.', -) -const $$splitLoaderImporter = () => - import('retain-export-component.tsx?tsr-split=loader') -import { lazyFn } from '@tanstack/react-router' -import * as React from 'react' -import { createFileRoute, Outlet } from '@tanstack/react-router' -import { importedComponent as ImportedComponent } from '../../shared/imported' +console.warn("[tanstack-router] These exports from \"retain-export-component.tsx\" will not be code-split and will increase your bundle size:\n- Layout\nFor the best optimization, these items should either have their export statements removed, or be imported from another location that is not a route file."); +const $$splitLoaderImporter = () => import('retain-export-component.tsx?tsr-split=loader'); +import { lazyFn } from '@tanstack/react-router'; +import * as React from 'react'; +import { createFileRoute, Outlet } from '@tanstack/react-router'; +import { importedComponent as ImportedComponent } from '../../shared/imported'; export function Layout() { - return ( - <main> - <header style={{ height: HEADER_HEIGHT }}> + return <main> + <header style={{ + height: HEADER_HEIGHT + }}> <nav> <ul> <li> @@ -21,14 +19,13 @@ export function Layout() { </header> <ImportedComponent /> <Outlet /> - </main> - ) + </main>; } export const Route = createFileRoute('/_layout')({ component: Layout, - loader: lazyFn($$splitLoaderImporter, 'loader'), -}) -const HEADER_HEIGHT = '63px' -export const SIDEBAR_WIDTH = '150px' -const SIDEBAR_MINI_WIDTH = '80px' -const ASIDE_WIDTH = '250px' + loader: lazyFn($$splitLoaderImporter, 'loader') +}); +const HEADER_HEIGHT = '63px'; +export const SIDEBAR_WIDTH = '150px'; +const SIDEBAR_MINI_WIDTH = '80px'; +const ASIDE_WIDTH = '250px'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-export-component@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-export-component@component---errorComponent---notFoundComponent---pendingComponent.tsx index 8fb12f0c6b..5bb0ab5451 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-export-component@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-export-component@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,3 +1,3 @@ -import * as React from 'react' -const SIDEBAR_MINI_WIDTH = '80px' -const ASIDE_WIDTH = '250px' +import * as React from 'react'; +const SIDEBAR_MINI_WIDTH = '80px'; +const ASIDE_WIDTH = '250px'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-export-component@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-export-component@loader.tsx index ddeb4d1e6f..9787e27ad7 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-export-component@loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-export-component@loader.tsx @@ -1,6 +1,6 @@ -import * as React from 'react' -import { importedLoader } from '../../shared/imported' -const SIDEBAR_MINI_WIDTH = '80px' -const ASIDE_WIDTH = '250px' -const SplitLoader = importedLoader -export { SplitLoader as loader } +import * as React from 'react'; +import { importedLoader } from '../../shared/imported'; +const SIDEBAR_MINI_WIDTH = '80px'; +const ASIDE_WIDTH = '250px'; +const SplitLoader = importedLoader; +export { SplitLoader as loader }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-const.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-const.tsx index d674dbb799..f256b01a83 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-const.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-const.tsx @@ -4,9 +4,11 @@ import { importedComponent as ImportedComponent, importedLoader, } from '../../shared/imported' + export const loaderFn = () => { return importedLoader() } + const Layout = () => { return ( <main> @@ -24,12 +26,15 @@ const Layout = () => { </main> ) } + export const Route = createFileRoute('/_layout')({ component: Layout, loader: loaderFn, }) + const HEADER_HEIGHT = '63px' export const SIDEBAR_WIDTH = '150px' export const SIDEBAR_MINI_WIDTH = '80px' const ASIDE_WIDTH = '250px' + export default Layout diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-const@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-const@component---errorComponent---notFoundComponent---pendingComponent.tsx index 0e0123f1ab..168ba78680 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-const@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-const@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,2 +1,2 @@ -import * as React from 'react' -const ASIDE_WIDTH = '250px' +import * as React from 'react'; +const ASIDE_WIDTH = '250px'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-const@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-const@loader.tsx index 0e0123f1ab..168ba78680 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-const@loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-const@loader.tsx @@ -1,2 +1,2 @@ -import * as React from 'react' -const ASIDE_WIDTH = '250px' +import * as React from 'react'; +const ASIDE_WIDTH = '250px'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-destructured.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-destructured.tsx index 89c23305a0..0e3175116f 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-destructured.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-destructured.tsx @@ -1,12 +1,18 @@ import { createFileRoute } from '@tanstack/react-router' + const createBits = () => ({ component: AboutComponentImpl, - loader: () => ({ message: 'hello' }), + loader: () => ({ + message: 'hello', + }), }) + export const { component: AboutComponent, loader } = createBits() + function AboutComponentImpl() { return <div>About</div> } + export const Route = createFileRoute('/about')({ component: AboutComponent, loader, diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-destructured@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-destructured@component---errorComponent---notFoundComponent---pendingComponent.tsx index d64b42fdcc..a6d57afe77 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-destructured@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-destructured@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,2 +1,2 @@ -import { AboutComponent } from 'retain-exports-destructured.tsx?tsr-shared=1' -export { AboutComponent as component } +import { AboutComponent } from "retain-exports-destructured.tsx?tsr-shared=1"; +export { AboutComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-destructured@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-destructured@loader.tsx index 0397569b0f..e8d771ea44 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-destructured@loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-destructured@loader.tsx @@ -1,2 +1,2 @@ -import { loader } from 'retain-exports-destructured.tsx?tsr-shared=1' -export { loader } +import { loader } from "retain-exports-destructured.tsx?tsr-shared=1"; +export { loader }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-destructured@shared.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-destructured@shared.tsx index 6eff1ff083..b03a4eb83a 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-destructured@shared.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-destructured@shared.tsx @@ -1,9 +1,14 @@ const createBits = () => ({ component: AboutComponentImpl, - loader: () => ({ message: 'hello' }), -}) -const { component: AboutComponent, loader } = createBits() + loader: () => ({ + message: 'hello' + }) +}); +const { + component: AboutComponent, + loader +} = createBits(); function AboutComponentImpl() { - return <div>About</div> + return <div>About</div>; } -export { AboutComponent, AboutComponentImpl, createBits, loader } +export { AboutComponent, AboutComponentImpl, createBits, loader }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-function.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-function.tsx index 83b3dd4eb5..298c388e65 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-function.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-function.tsx @@ -4,9 +4,11 @@ import { importedComponent as ImportedComponent, importedLoader, } from '../../shared/imported' + export function loaderFn() { return importedLoader() } + function Layout() { return ( <main> @@ -24,12 +26,15 @@ function Layout() { </main> ) } + export const Route = createFileRoute('/_layout')({ component: Layout, loader: loaderFn, }) + const HEADER_HEIGHT = '63px' export const SIDEBAR_WIDTH = '150px' export const SIDEBAR_MINI_WIDTH = '80px' const ASIDE_WIDTH = '250px' + export default Layout diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-function@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-function@component---errorComponent---notFoundComponent---pendingComponent.tsx index 0e0123f1ab..168ba78680 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-function@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-function@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,2 +1,2 @@ -import * as React from 'react' -const ASIDE_WIDTH = '250px' +import * as React from 'react'; +const ASIDE_WIDTH = '250px'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-function@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-function@loader.tsx index 0e0123f1ab..168ba78680 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-function@loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-function@loader.tsx @@ -1,2 +1,2 @@ -import * as React from 'react' -const ASIDE_WIDTH = '250px' +import * as React from 'react'; +const ASIDE_WIDTH = '250px'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-loader.tsx index ef230c47f6..c7d5437729 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-loader.tsx @@ -1,18 +1,17 @@ -console.warn( - '[tanstack-router] These exports from "retain-exports-loader.tsx" will not be code-split and will increase your bundle size:\n- loaderFn\nFor the best optimization, these items should either have their export statements removed, or be imported from another location that is not a route file.', -) -const $$splitComponentImporter = () => - import('retain-exports-loader.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import * as React from 'react' -import { createFileRoute } from '@tanstack/react-router' +console.warn("[tanstack-router] These exports from \"retain-exports-loader.tsx\" will not be code-split and will increase your bundle size:\n- loaderFn\nFor the best optimization, these items should either have their export statements removed, or be imported from another location that is not a route file."); +const $$splitComponentImporter = () => import('retain-exports-loader.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import * as React from 'react'; +import { createFileRoute } from '@tanstack/react-router'; export function loaderFn() { - return { foo: 'bar' } + return { + foo: 'bar' + }; } export const Route = createFileRoute('/_layout')({ component: lazyRouteComponent($$splitComponentImporter, 'component'), - loader: loaderFn, -}) -export const SIDEBAR_WIDTH = '150px' -export const SIDEBAR_MINI_WIDTH = '80px' -const ASIDE_WIDTH = '250px' + loader: loaderFn +}); +export const SIDEBAR_WIDTH = '150px'; +export const SIDEBAR_MINI_WIDTH = '80px'; +const ASIDE_WIDTH = '250px'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-loader@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-loader@component---errorComponent---notFoundComponent---pendingComponent.tsx index 604be4dc69..9f54ae0dc5 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-loader@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-loader@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,10 +1,11 @@ -import * as React from 'react' -import { Outlet } from '@tanstack/react-router' -import { importedComponent as ImportedComponent } from '../../shared/imported' +import * as React from 'react'; +import { Outlet } from '@tanstack/react-router'; +import { importedComponent as ImportedComponent } from '../../shared/imported'; function Layout() { - return ( - <main> - <header style={{ height: HEADER_HEIGHT }}> + return <main> + <header style={{ + height: HEADER_HEIGHT + }}> <nav> <ul> <li> @@ -15,9 +16,8 @@ function Layout() { </header> <ImportedComponent /> <Outlet /> - </main> - ) + </main>; } -const HEADER_HEIGHT = '63px' -const ASIDE_WIDTH = '250px' -export { Layout as component } +const HEADER_HEIGHT = '63px'; +const ASIDE_WIDTH = '250px'; +export { Layout as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-loader@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-loader@loader.tsx index 0e0123f1ab..168ba78680 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-loader@loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/retain-exports-loader@loader.tsx @@ -1,2 +1,2 @@ -import * as React from 'react' -const ASIDE_WIDTH = '250px' +import * as React from 'react'; +const ASIDE_WIDTH = '250px'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-class.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-class.tsx index 96d51c8492..da068daa17 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-class.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-class.tsx @@ -1,10 +1,9 @@ -const $$splitComponentImporter = () => - import('shared-class.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -const $$splitLoaderImporter = () => import('shared-class.tsx?tsr-split=loader') -import { lazyFn } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('shared-class.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +const $$splitLoaderImporter = () => import('shared-class.tsx?tsr-split=loader'); +import { lazyFn } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/store')({ loader: lazyFn($$splitLoaderImporter, 'loader'), - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-class@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-class@component---errorComponent---notFoundComponent---pendingComponent.tsx index e0e187fb1d..6a38b10ff8 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-class@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-class@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,3 +1,3 @@ -import { store } from 'shared-class.tsx?tsr-shared=1' -const SplitComponent = () => <div>{store.get('items')}</div> -export { SplitComponent as component } +import { store } from "shared-class.tsx?tsr-shared=1"; +const SplitComponent = () => <div>{store.get('items')}</div>; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-class@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-class@loader.tsx index 96dcaca4a8..f91799f3c8 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-class@loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-class@loader.tsx @@ -1,5 +1,5 @@ -import { store } from 'shared-class.tsx?tsr-shared=1' +import { store } from "shared-class.tsx?tsr-shared=1"; const SplitLoader = async () => { - store.set('items', await fetch('/api')) -} -export { SplitLoader as loader } + store.set('items', await fetch('/api')); +}; +export { SplitLoader as loader }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-class@shared.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-class@shared.tsx index 0abc282ecc..18c40bafb6 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-class@shared.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-class@shared.tsx @@ -1,11 +1,11 @@ class DataStore { - data = new Map() + data = new Map(); get(k: string) { - return this.data.get(k) + return this.data.get(k); } set(k: string, v: unknown) { - this.data.set(k, v) + this.data.set(k, v); } } -const store = new DataStore() -export { DataStore, store } +const store = new DataStore(); +export { DataStore, store }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-destructured-export.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-destructured-export.tsx index 080a19ff45..7d0f0fcae1 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-destructured-export.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-destructured-export.tsx @@ -1,12 +1,10 @@ -const $$splitComponentImporter = () => - import('shared-destructured-export.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -const $$splitLoaderImporter = () => - import('shared-destructured-export.tsx?tsr-split=loader') -import { lazyFn } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('shared-destructured-export.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +const $$splitLoaderImporter = () => import('shared-destructured-export.tsx?tsr-split=loader'); +import { lazyFn } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/config')({ loader: lazyFn($$splitLoaderImporter, 'loader'), - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) -export { apiUrl, timeout } from 'shared-destructured-export.tsx?tsr-shared=1' + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); +export { apiUrl, timeout } from "shared-destructured-export.tsx?tsr-shared=1"; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-destructured-export@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-destructured-export@component---errorComponent---notFoundComponent---pendingComponent.tsx index 8cd0f14a27..16b288ac5f 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-destructured-export@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-destructured-export@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,3 +1,3 @@ -import { timeout } from 'shared-destructured-export.tsx?tsr-shared=1' -const SplitComponent = () => <div>Timeout: {timeout}</div> -export { SplitComponent as component } +import { timeout } from "shared-destructured-export.tsx?tsr-shared=1"; +const SplitComponent = () => <div>Timeout: {timeout}</div>; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-destructured-export@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-destructured-export@loader.tsx index d099459c6f..33d4b5aa43 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-destructured-export@loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-destructured-export@loader.tsx @@ -1,3 +1,3 @@ -import { apiUrl } from 'shared-destructured-export.tsx?tsr-shared=1' -const SplitLoader = async () => fetch(apiUrl) -export { SplitLoader as loader } +import { apiUrl } from "shared-destructured-export.tsx?tsr-shared=1"; +const SplitLoader = async () => fetch(apiUrl); +export { SplitLoader as loader }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-destructured-export@shared.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-destructured-export@shared.tsx index ae9324acc9..f0bfd70add 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-destructured-export@shared.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-destructured-export@shared.tsx @@ -1,5 +1,11 @@ -const { apiUrl, timeout } = getConfig() +const { + apiUrl, + timeout +} = getConfig(); function getConfig() { - return { apiUrl: '/api', timeout: 5000 } + return { + apiUrl: '/api', + timeout: 5000 + }; } -export { apiUrl, getConfig, timeout } +export { apiUrl, getConfig, timeout }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-destructured.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-destructured.tsx index 7c46a40bb3..8185738e9d 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-destructured.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-destructured.tsx @@ -1,11 +1,9 @@ -const $$splitComponentImporter = () => - import('shared-destructured.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -const $$splitLoaderImporter = () => - import('shared-destructured.tsx?tsr-split=loader') -import { lazyFn } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('shared-destructured.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +const $$splitLoaderImporter = () => import('shared-destructured.tsx?tsr-split=loader'); +import { lazyFn } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/config')({ loader: lazyFn($$splitLoaderImporter, 'loader'), - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-destructured@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-destructured@component---errorComponent---notFoundComponent---pendingComponent.tsx index 3d7933a573..5c0182e61a 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-destructured@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-destructured@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,3 +1,3 @@ -import { timeout } from 'shared-destructured.tsx?tsr-shared=1' -const SplitComponent = () => <div>Timeout: {timeout}</div> -export { SplitComponent as component } +import { timeout } from "shared-destructured.tsx?tsr-shared=1"; +const SplitComponent = () => <div>Timeout: {timeout}</div>; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-destructured@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-destructured@loader.tsx index 53e56d748d..94b0923079 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-destructured@loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-destructured@loader.tsx @@ -1,3 +1,3 @@ -import { apiUrl } from 'shared-destructured.tsx?tsr-shared=1' -const SplitLoader = async () => fetch(apiUrl) -export { SplitLoader as loader } +import { apiUrl } from "shared-destructured.tsx?tsr-shared=1"; +const SplitLoader = async () => fetch(apiUrl); +export { SplitLoader as loader }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-destructured@shared.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-destructured@shared.tsx index ae9324acc9..f0bfd70add 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-destructured@shared.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-destructured@shared.tsx @@ -1,5 +1,11 @@ -const { apiUrl, timeout } = getConfig() +const { + apiUrl, + timeout +} = getConfig(); function getConfig() { - return { apiUrl: '/api', timeout: 5000 } + return { + apiUrl: '/api', + timeout: 5000 + }; } -export { apiUrl, getConfig, timeout } +export { apiUrl, getConfig, timeout }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-exported.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-exported.tsx index bf6574aaed..ce690311b2 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-exported.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-exported.tsx @@ -1,12 +1,10 @@ -const $$splitComponentImporter = () => - import('shared-exported.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -const $$splitLoaderImporter = () => - import('shared-exported.tsx?tsr-split=loader') -import { lazyFn } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('shared-exported.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +const $$splitLoaderImporter = () => import('shared-exported.tsx?tsr-split=loader'); +import { lazyFn } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/query')({ loader: lazyFn($$splitLoaderImporter, 'loader'), - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) -export { queryOptions } from 'shared-exported.tsx?tsr-shared=1' + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); +export { queryOptions } from "shared-exported.tsx?tsr-shared=1"; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-exported@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-exported@component---errorComponent---notFoundComponent---pendingComponent.tsx index 9fe61942dd..b020b5cadf 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-exported@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-exported@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,3 +1,3 @@ -import { queryOptions } from 'shared-exported.tsx?tsr-shared=1' -const SplitComponent = () => <div>GC: {queryOptions.gcTime}</div> -export { SplitComponent as component } +import { queryOptions } from "shared-exported.tsx?tsr-shared=1"; +const SplitComponent = () => <div>GC: {queryOptions.gcTime}</div>; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-exported@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-exported@loader.tsx index 4d4b8fbc5c..332fa35079 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-exported@loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-exported@loader.tsx @@ -1,5 +1,7 @@ -import { queryOptions } from 'shared-exported.tsx?tsr-shared=1' +import { queryOptions } from "shared-exported.tsx?tsr-shared=1"; const SplitLoader = async () => { - return { staleTime: queryOptions.staleTime } -} -export { SplitLoader as loader } + return { + staleTime: queryOptions.staleTime + }; +}; +export { SplitLoader as loader }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-exported@shared.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-exported@shared.tsx index 3a1ff108bb..a3f91b85bb 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-exported@shared.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-exported@shared.tsx @@ -1,2 +1,5 @@ -const queryOptions = { staleTime: 5000, gcTime: 10000 } -export { queryOptions } +const queryOptions = { + staleTime: 5000, + gcTime: 10000 +}; +export { queryOptions }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-function.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-function.tsx index ef2e5e57a3..b5bf41235e 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-function.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-function.tsx @@ -1,11 +1,9 @@ -const $$splitComponentImporter = () => - import('shared-function.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -const $$splitLoaderImporter = () => - import('shared-function.tsx?tsr-split=loader') -import { lazyFn } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('shared-function.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +const $$splitLoaderImporter = () => import('shared-function.tsx?tsr-split=loader'); +import { lazyFn } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/cached')({ loader: lazyFn($$splitLoaderImporter, 'loader'), - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-function@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-function@component---errorComponent---notFoundComponent---pendingComponent.tsx index 1c327523af..571bd9356a 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-function@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-function@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,3 +1,3 @@ -import { getCached } from 'shared-function.tsx?tsr-shared=1' -const SplitComponent = () => <div>{JSON.stringify(getCached('data'))}</div> -export { SplitComponent as component } +import { getCached } from "shared-function.tsx?tsr-shared=1"; +const SplitComponent = () => <div>{JSON.stringify(getCached('data'))}</div>; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-function@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-function@loader.tsx index d8ae45caed..f5f72ab014 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-function@loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-function@loader.tsx @@ -1,9 +1,9 @@ -import { getCached, cache } from 'shared-function.tsx?tsr-shared=1' +import { getCached, cache } from "shared-function.tsx?tsr-shared=1"; function setCached(key: string, val: unknown) { - cache.set(key, val) + cache.set(key, val); } const SplitLoader = async () => { - setCached('data', await fetch('/api').then((r) => r.json())) - return getCached('data') -} -export { SplitLoader as loader } + setCached('data', await fetch('/api').then(r => r.json())); + return getCached('data'); +}; +export { SplitLoader as loader }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-function@shared.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-function@shared.tsx index 243ac23a66..27d2cf03f1 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-function@shared.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-function@shared.tsx @@ -1,5 +1,5 @@ -const cache = new Map() +const cache = new Map(); function getCached(key: string) { - return cache.get(key) + return cache.get(key); } -export { cache, getCached } +export { cache, getCached }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-imported-binding.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-imported-binding.tsx index 30823e2684..d9ce6828fa 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-imported-binding.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-imported-binding.tsx @@ -1,11 +1,9 @@ -const $$splitComponentImporter = () => - import('shared-imported-binding.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -const $$splitLoaderImporter = () => - import('shared-imported-binding.tsx?tsr-split=loader') -import { lazyFn } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('shared-imported-binding.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +const $$splitLoaderImporter = () => import('shared-imported-binding.tsx?tsr-split=loader'); +import { lazyFn } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/imported')({ loader: lazyFn($$splitLoaderImporter, 'loader'), - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-imported-binding@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-imported-binding@component---errorComponent---notFoundComponent---pendingComponent.tsx index e3c8a0f5d8..0a835ae063 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-imported-binding@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-imported-binding@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,3 +1,3 @@ -import { sharedUtil } from '../utils' -const SplitComponent = () => <div>{sharedUtil('render')}</div> -export { SplitComponent as component } +import { sharedUtil } from '../utils'; +const SplitComponent = () => <div>{sharedUtil('render')}</div>; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-imported-binding@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-imported-binding@loader.tsx index 8b8c645837..1b27de9093 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-imported-binding@loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-imported-binding@loader.tsx @@ -1,3 +1,3 @@ -import { sharedUtil } from '../utils' -const SplitLoader = async () => sharedUtil('load') -export { SplitLoader as loader } +import { sharedUtil } from '../utils'; +const SplitLoader = async () => sharedUtil('load'); +export { SplitLoader as loader }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-indirect-ref.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-indirect-ref.tsx index 17ae801b02..f4dfce52ba 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-indirect-ref.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-indirect-ref.tsx @@ -1,11 +1,9 @@ -const $$splitComponentImporter = () => - import('shared-indirect-ref.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -const $$splitLoaderImporter = () => - import('shared-indirect-ref.tsx?tsr-split=loader') -import { lazyFn } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('shared-indirect-ref.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +const $$splitLoaderImporter = () => import('shared-indirect-ref.tsx?tsr-split=loader'); +import { lazyFn } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/shared-indirect')({ loader: lazyFn($$splitLoaderImporter, 'loader'), - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-indirect-ref@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-indirect-ref@component---errorComponent---notFoundComponent---pendingComponent.tsx index 64bb6ab567..62995e7fd8 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-indirect-ref@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-indirect-ref@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,9 +1,7 @@ -import { state, getCount } from 'shared-indirect-ref.tsx?tsr-shared=1' +import { state, getCount } from "shared-indirect-ref.tsx?tsr-shared=1"; function SharedComponent() { - return ( - <div> + return <div> {getCount()} - {state.count} - </div> - ) + </div>; } -export { SharedComponent as component } +export { SharedComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-indirect-ref@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-indirect-ref@loader.tsx index 6b4c2c895b..0625ac53f8 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-indirect-ref@loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-indirect-ref@loader.tsx @@ -1,6 +1,8 @@ -import { state, getCount } from 'shared-indirect-ref.tsx?tsr-shared=1' +import { state, getCount } from "shared-indirect-ref.tsx?tsr-shared=1"; const SplitLoader = () => { - state.count++ - return { count: getCount() } -} -export { SplitLoader as loader } + state.count++; + return { + count: getCount() + }; +}; +export { SplitLoader as loader }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-indirect-ref@shared.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-indirect-ref@shared.tsx index b4910d2fd1..7e7e811ba8 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-indirect-ref@shared.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-indirect-ref@shared.tsx @@ -1,5 +1,7 @@ -const state = { count: 0 } +const state = { + count: 0 +}; function getCount() { - return state.count + return state.count; } -export { getCount, state } +export { getCount, state }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-jsx-component-ref.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-jsx-component-ref.tsx index fd6b2c69be..8ac24d49cf 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-jsx-component-ref.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-jsx-component-ref.tsx @@ -1,12 +1,10 @@ -const $$splitComponentImporter = () => - import('shared-jsx-component-ref.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -const $$splitLoaderImporter = () => - import('shared-jsx-component-ref.tsx?tsr-split=loader') -import { lazyFn } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('shared-jsx-component-ref.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +const $$splitLoaderImporter = () => import('shared-jsx-component-ref.tsx?tsr-split=loader'); +import { lazyFn } from '@tanstack/react-router'; // @ts-nocheck -import { createFileRoute } from '@tanstack/react-router' +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/jsx')({ loader: lazyFn($$splitLoaderImporter, 'loader'), - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-jsx-component-ref@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-jsx-component-ref@component---errorComponent---notFoundComponent---pendingComponent.tsx index 845e1db45c..52ecb6d474 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-jsx-component-ref@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-jsx-component-ref@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,5 +1,5 @@ -import { shared } from 'shared-jsx-component-ref.tsx?tsr-shared=1' // @ts-nocheck +import { shared } from "shared-jsx-component-ref.tsx?tsr-shared=1"; // @ts-nocheck function SharedComponent() { - return <div>{shared}</div> + return <div>{shared}</div>; } -export { SharedComponent as component } +export { SharedComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-jsx-component-ref@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-jsx-component-ref@loader.tsx index 348aecd923..f861dda436 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-jsx-component-ref@loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-jsx-component-ref@loader.tsx @@ -1,3 +1,3 @@ -import { shared } from 'shared-jsx-component-ref.tsx?tsr-shared=1' // @ts-nocheck -const SplitLoader = () => shared -export { SplitLoader as loader } +import { shared } from "shared-jsx-component-ref.tsx?tsr-shared=1"; // @ts-nocheck +const SplitLoader = () => shared; +export { SplitLoader as loader }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-jsx-component-ref@shared.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-jsx-component-ref@shared.tsx index 60ae1006a1..d5cc2cf990 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-jsx-component-ref@shared.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-jsx-component-ref@shared.tsx @@ -1,3 +1,4 @@ // @ts-nocheck -const shared = 1 -export { shared } + +const shared = 1; +export { shared }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-none.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-none.tsx index 5ecfa3b109..06e81042d6 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-none.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-none.tsx @@ -1,10 +1,9 @@ -const $$splitComponentImporter = () => - import('shared-none.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -const $$splitLoaderImporter = () => import('shared-none.tsx?tsr-split=loader') -import { lazyFn } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('shared-none.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +const $$splitLoaderImporter = () => import('shared-none.tsx?tsr-split=loader'); +import { lazyFn } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/clean')({ loader: lazyFn($$splitLoaderImporter, 'loader'), - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-none@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-none@component---errorComponent---notFoundComponent---pendingComponent.tsx index 1bfd4eb63f..701deeedeb 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-none@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-none@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,7 +1,5 @@ -const ComponentHelper = () => <span>helper</span> -const SplitComponent = () => ( - <div> - <ComponentHelper /> - </div> -) -export { SplitComponent as component } +const ComponentHelper = () => <span>helper</span>; +const SplitComponent = () => <div> + <ComponentHelper /> + </div>; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-none@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-none@loader.tsx index 0dfbec2515..d0cfce36ee 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-none@loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-none@loader.tsx @@ -1,3 +1,3 @@ -const loaderHelper = () => fetch('/api') -const SplitLoader = async () => loaderHelper() -export { SplitLoader as loader } +const loaderHelper = () => fetch('/api'); +const SplitLoader = async () => loaderHelper(); +export { SplitLoader as loader }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-referencing-route.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-referencing-route.tsx index 5a3509f434..b62568c1fb 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-referencing-route.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-referencing-route.tsx @@ -1,11 +1,9 @@ -const $$splitComponentImporter = () => - import('shared-referencing-route.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -const $$splitLoaderImporter = () => - import('shared-referencing-route.tsx?tsr-split=loader') -import { lazyFn } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('shared-referencing-route.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +const $$splitLoaderImporter = () => import('shared-referencing-route.tsx?tsr-split=loader'); +import { lazyFn } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/about')({ loader: lazyFn($$splitLoaderImporter, 'loader'), - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-referencing-route@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-referencing-route@component---errorComponent---notFoundComponent---pendingComponent.tsx index b2c4630c90..2cb2cdb68c 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-referencing-route@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-referencing-route@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,10 +1,10 @@ -import { HEADER } from 'shared-referencing-route.tsx?tsr-shared=1' +import { HEADER } from "shared-referencing-route.tsx?tsr-shared=1"; function usePageTitle() { - return `${HEADER} - ${Route.fullPath}` + return `${HEADER} - ${Route.fullPath}`; } -import { Route } from 'shared-referencing-route.tsx' +import { Route } from "shared-referencing-route.tsx"; const SplitComponent = () => { - const title = usePageTitle() - return <div>{title}</div> -} -export { SplitComponent as component } + const title = usePageTitle(); + return <div>{title}</div>; +}; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-referencing-route@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-referencing-route@loader.tsx index dbf196f1b3..baedd53bd7 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-referencing-route@loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-referencing-route@loader.tsx @@ -1,10 +1,12 @@ -import { HEADER } from 'shared-referencing-route.tsx?tsr-shared=1' +import { HEADER } from "shared-referencing-route.tsx?tsr-shared=1"; function usePageTitle() { - return `${HEADER} - ${Route.fullPath}` + return `${HEADER} - ${Route.fullPath}`; } -import { Route } from 'shared-referencing-route.tsx' +import { Route } from "shared-referencing-route.tsx"; const SplitLoader = async () => { - const title = usePageTitle() - return { title } -} -export { SplitLoader as loader } + const title = usePageTitle(); + return { + title + }; +}; +export { SplitLoader as loader }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-referencing-route@shared.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-referencing-route@shared.tsx index 34b9c4ca41..cc2d01424c 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-referencing-route@shared.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-referencing-route@shared.tsx @@ -1,2 +1,2 @@ -const HEADER = 'Page' -export { HEADER } +const HEADER = 'Page'; +export { HEADER }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-runtime.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-runtime.tsx deleted file mode 100644 index 944c0b8ca8..0000000000 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-runtime.tsx +++ /dev/null @@ -1,20 +0,0 @@ -import { state, createState, createSeed } from 'shared-runtime.tsx?tsr-shared=1' -const $$splitComponentImporter = () => - import('shared-runtime.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -const $$splitLoaderImporter = () => - import('shared-runtime.tsx?tsr-split=loader') -import { lazyFn } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' -console.log('shared-runtime:reference') -export const Route = createFileRoute('/shared-runtime')({ - beforeLoad: () => state, - loader: lazyFn($$splitLoaderImporter, 'loader'), - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) -function createState(initialState: { count: number }): { - state: { count: number } - increment: () => number -} -export { state as firstState, state as secondState, state as 'odd-name' } -export default createSeed diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-runtime@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-runtime@component---errorComponent---notFoundComponent---pendingComponent.tsx deleted file mode 100644 index 5245f6d9eb..0000000000 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-runtime@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import { - state, - createState, - createSeed, - Labels, -} from 'shared-runtime.tsx?tsr-shared=1' -const label = createComponentLabel() -function createState(initialState: { count: number }): { - state: { count: number } - increment: () => number -} -function createComponentLabel() { - console.log('shared-runtime:component') - return Labels.component -} -export { state as firstState, state as secondState, state as 'odd-name' } -export default createSeed -const SplitComponent = () => { - if (state.count === 3) { - throw new Error('route source-map contract') - } - return `${label}:${state.count}` -} -export { SplitComponent as component } diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-runtime@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-runtime@loader.tsx deleted file mode 100644 index 6c0c88cab7..0000000000 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-runtime@loader.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import { - state, - createState, - createSeed, - increment, -} from 'shared-runtime.tsx?tsr-shared=1' -function createState(initialState: { count: number }): { - state: { count: number } - increment: () => number -} -export { state as firstState, state as secondState, state as 'odd-name' } -export default createSeed -const SplitLoader = () => { - increment() - return state -} -export { SplitLoader as loader } diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-runtime@shared.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-runtime@shared.tsx deleted file mode 100644 index c53a7e1568..0000000000 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-runtime@shared.tsx +++ /dev/null @@ -1,13 +0,0 @@ -const Count = { Initial: 0 } -const Labels = { component: 'count' } -const seed = createSeed() -const { state, increment } = createState(seed) -function createSeed() { - console.log('shared-runtime:seed') - return { count: Count.Initial, label: Labels.component } -} -function createState(initialState: { count: number }) { - console.log('shared-runtime:state') - return { state: initialState, increment: () => initialState.count++ } -} -export { Count, createSeed, createState, increment, Labels, seed, state } diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-transitive.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-transitive.tsx index aba85fd14b..869602e15b 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-transitive.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-transitive.tsx @@ -1,11 +1,9 @@ -const $$splitComponentImporter = () => - import('shared-transitive.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -const $$splitLoaderImporter = () => - import('shared-transitive.tsx?tsr-split=loader') -import { lazyFn } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('shared-transitive.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +const $$splitLoaderImporter = () => import('shared-transitive.tsx?tsr-split=loader'); +import { lazyFn } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/api')({ loader: lazyFn($$splitLoaderImporter, 'loader'), - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-transitive@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-transitive@component---errorComponent---notFoundComponent---pendingComponent.tsx index c237a03583..7a3a74048e 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-transitive@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-transitive@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,3 +1,3 @@ -import { config } from 'shared-transitive.tsx?tsr-shared=1' -const SplitComponent = () => <div>Timeout: {config.timeout}</div> -export { SplitComponent as component } +import { config } from "shared-transitive.tsx?tsr-shared=1"; +const SplitComponent = () => <div>Timeout: {config.timeout}</div>; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-transitive@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-transitive@loader.tsx index 70faa4c627..8472eab295 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-transitive@loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-transitive@loader.tsx @@ -1,6 +1,6 @@ -import { config } from 'shared-transitive.tsx?tsr-shared=1' -const fetcher = (path: string) => fetch(`${config.url}${path}`) +import { config } from "shared-transitive.tsx?tsr-shared=1"; +const fetcher = (path: string) => fetch(`${config.url}${path}`); const SplitLoader = async () => { - return fetcher('/data') -} -export { SplitLoader as loader } + return fetcher('/data'); +}; +export { SplitLoader as loader }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-transitive@shared.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-transitive@shared.tsx index ac44498714..8bec4a1d55 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-transitive@shared.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-transitive@shared.tsx @@ -1,3 +1,6 @@ -const BASE_URL = 'https://api.example.com' -const config = { url: BASE_URL, timeout: 5000 } -export { BASE_URL, config } +const BASE_URL = 'https://api.example.com'; +const config = { + url: BASE_URL, + timeout: 5000 +}; +export { BASE_URL, config }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-variable.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-variable.tsx index e06ea2b1d2..42f68cce48 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-variable.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-variable.tsx @@ -1,11 +1,9 @@ -const $$splitComponentImporter = () => - import('shared-variable.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -const $$splitLoaderImporter = () => - import('shared-variable.tsx?tsr-split=loader') -import { lazyFn } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('shared-variable.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +const $$splitLoaderImporter = () => import('shared-variable.tsx?tsr-split=loader'); +import { lazyFn } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/todos')({ loader: lazyFn($$splitLoaderImporter, 'loader'), - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-variable@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-variable@component---errorComponent---notFoundComponent---pendingComponent.tsx index 10325aa95e..d149922fbc 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-variable@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-variable@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,3 +1,3 @@ -import { collection } from 'shared-variable.tsx?tsr-shared=1' -const SplitComponent = () => <div>{collection.name}</div> -export { SplitComponent as component } +import { collection } from "shared-variable.tsx?tsr-shared=1"; +const SplitComponent = () => <div>{collection.name}</div>; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-variable@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-variable@loader.tsx index b76d00b514..196a8e48a4 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-variable@loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-variable@loader.tsx @@ -1,6 +1,8 @@ -import { collection } from 'shared-variable.tsx?tsr-shared=1' +import { collection } from "shared-variable.tsx?tsr-shared=1"; const SplitLoader = async () => { - await collection.preload() - return { data: 'loaded' } -} -export { SplitLoader as loader } + await collection.preload(); + return { + data: 'loaded' + }; +}; +export { SplitLoader as loader }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-variable@shared.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-variable@shared.tsx index 10421dac09..8a0560d5b9 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-variable@shared.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-variable@shared.tsx @@ -1,2 +1,5 @@ -const collection = { name: 'todos', preload: async () => {} } -export { collection } +const collection = { + name: 'todos', + preload: async () => {} +}; +export { collection }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-with-side-effect.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-with-side-effect.tsx index 5965d04430..943cdf189c 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-with-side-effect.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-with-side-effect.tsx @@ -1,12 +1,10 @@ -const $$splitComponentImporter = () => - import('shared-with-side-effect.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -const $$splitLoaderImporter = () => - import('shared-with-side-effect.tsx?tsr-split=loader') -import { lazyFn } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' -console.log('registry created') +const $$splitComponentImporter = () => import('shared-with-side-effect.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +const $$splitLoaderImporter = () => import('shared-with-side-effect.tsx?tsr-split=loader'); +import { lazyFn } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; +console.log('registry created'); export const Route = createFileRoute('/fx')({ loader: lazyFn($$splitLoaderImporter, 'loader'), - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-with-side-effect@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-with-side-effect@component---errorComponent---notFoundComponent---pendingComponent.tsx index 3ede22c8be..d953af00fa 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-with-side-effect@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-with-side-effect@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,3 +1,3 @@ -import { registry } from 'shared-with-side-effect.tsx?tsr-shared=1' -const SplitComponent = () => <div>{registry.size}</div> -export { SplitComponent as component } +import { registry } from "shared-with-side-effect.tsx?tsr-shared=1"; +const SplitComponent = () => <div>{registry.size}</div>; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-with-side-effect@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-with-side-effect@loader.tsx index b3b404a8ab..a5f06a0a05 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-with-side-effect@loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-with-side-effect@loader.tsx @@ -1,5 +1,5 @@ -import { registry } from 'shared-with-side-effect.tsx?tsr-shared=1' +import { registry } from "shared-with-side-effect.tsx?tsr-shared=1"; const SplitLoader = async () => { - registry.set('loaded', true) -} -export { SplitLoader as loader } + registry.set('loaded', true); +}; +export { SplitLoader as loader }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-with-side-effect@shared.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-with-side-effect@shared.tsx index a59298f9e0..f26c656fdd 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-with-side-effect@shared.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/shared-with-side-effect@shared.tsx @@ -1,2 +1,2 @@ -const registry = new Map() -export { registry } +const registry = new Map(); +export { registry }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/undefined-literals.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/undefined-literals.tsx index 88b0bf1ba8..0c6e4f01aa 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/undefined-literals.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/undefined-literals.tsx @@ -1,4 +1,5 @@ import { createFileRoute } from '@tanstack/react-router' + export const Route = createFileRoute('/undefined-test')({ component: undefined, errorComponent: undefined, diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/useStateDestructure.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/useStateDestructure.tsx index b5b3ecade6..d0de09bf8b 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/useStateDestructure.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/useStateDestructure.tsx @@ -1,4 +1,5 @@ import * as React from 'react' + import { CgCornerUpLeft, CgSpinner } from 'react-icons/cg' import { FaBolt, @@ -20,6 +21,7 @@ import { startProject } from '~/projects/start' import { createFileRoute } from '@tanstack/react-router' import { Framework, getBranch } from '~/projects' import { seo } from '~/utils/seo' + const menu = [ { label: ( @@ -70,22 +72,31 @@ const menu = [ to: `https://cottonbureau.com/people/tanstack`, }, ] + export const Route = createFileRoute('/_libraries/start/$version/')({ component: VersionIndex, meta: () => - seo({ title: startProject.name, description: startProject.description }), + seo({ + title: startProject.name, + description: startProject.description, + }), }) + const librariesRouteApi = getRouteApi('/_libraries') + export default function VersionIndex() { const { sponsorsPromise } = librariesRouteApi.useLoaderData() const { version } = Route.useParams() const branch = getBranch(startProject, version) const [framework, setFramework] = React.useState<Framework>('react') const [isDark, setIsDark] = React.useState(true) + React.useEffect(() => { setIsDark(window.matchMedia?.(`(prefers-color-scheme: dark)`).matches) }, []) + const gradientText = `inline-block text-transparent bg-clip-text bg-gradient-to-r ${startProject.colorFrom} ${startProject.colorTo}` + return ( <div className="flex flex-col gap-20 md:gap-32 max-w-full"> <div @@ -96,6 +107,7 @@ export default function VersionIndex() { const label = ( <div className="p-2 opacity-90 hover:opacity-100">{item.label}</div> ) + return ( <div key={i} className="hover:underline"> {item.to.startsWith('http') ? ( @@ -257,6 +269,7 @@ Check it out at https://tanstack.com/start/`, </div> </div> </div> */} + {/* <div className="px-4 sm:px-6 lg:px-8 mx-auto"> <div className=" sm:text-center pb-16"> <h3 className="text-3xl text-center mx-auto leading-tight font-extrabold tracking-tight sm:text-4xl lg:leading-none mt-2"> @@ -302,6 +315,7 @@ Check it out at https://tanstack.com/start/`, })} </div> </div> */} + {/* <div> <div className="uppercase tracking-wider text-sm font-semibold text-center text-gray-400 mb-3"> Trusted in Production by @@ -344,6 +358,7 @@ Check it out at https://tanstack.com/start/`, </div> </marquee> </div> */} + <div className="px-4 w-[500px] max-w-full mx-auto"> <h3 className="text-center text-3xl leading-8 font-extrabold tracking-tight sm:text-4xl sm:leading-10 lg:leading-none mt-8"> Partners @@ -373,13 +388,16 @@ Check it out at https://tanstack.com/start/`, </div> </div> </div> + <div className="relative text-lg overflow-hidden"> <h3 className="text-center text-3xl leading-8 font-extrabold tracking-tight sm:text-4xl sm:leading-10 lg:leading-none mt-8"> Sponsors </h3> <div className="my-4 flex flex-wrap mx-auto max-w-screen-lg" - style={{ aspectRatio: '1/1' }} + style={{ + aspectRatio: '1/1', + }} > <Await promise={sponsorsPromise} @@ -398,6 +416,7 @@ Check it out at https://tanstack.com/start/`, </a> </div> </div> + <div className="mx-auto max-w-[400px] flex flex-col gap-2 items-center"> <div className="shadow-lg rounded-lg overflow-hidden bg-white dark:bg-gray-800 dark:text-white"> <Carbon /> @@ -410,6 +429,7 @@ Check it out at https://tanstack.com/start/`, rage-quit OSS. Yay money! 😉 </span> </div> + {/* <div className="flex flex-col gap-4"> <div className="px-4 sm:px-6 lg:px-8 mx-auto max-w-3xl sm:text-center"> <h3 className="text-3xl text-center leading-8 font-extrabold tracking-tight sm:text-4xl sm:leading-10 lg:leading-none mt-2"> @@ -448,6 +468,7 @@ Check it out at https://tanstack.com/start/`, </div> </div> </div> */} + {/* {[''].includes(framework) ? ( <div className="px-2"> <div className="p-8 text-center text-lg w-full max-w-screen-lg mx-auto bg-black text-white rounded-xl"> @@ -482,6 +503,7 @@ Check it out at https://tanstack.com/start/`, ></iframe> </div> )} */} + {/* <div className="flex flex-col gap-4 items-center"> <div className="font-extrabold text-xl lg:text-2xl"> Wow, you've come a long way! diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/useStateDestructure@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/useStateDestructure@component---errorComponent---notFoundComponent---pendingComponent.tsx index 5cc3099643..97b5481cf5 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/useStateDestructure@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/useStateDestructure@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,2 +1,2 @@ -import { FaBolt, FaBook, FaCheckCircle, FaCogs } from 'react-icons/fa' -import { VscPreview, VscWand } from 'react-icons/vsc' +import { FaBolt, FaBook, FaCheckCircle, FaCogs } from 'react-icons/fa'; +import { VscPreview, VscWand } from 'react-icons/vsc'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/useStateDestructure@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/useStateDestructure@loader.tsx index 5cc3099643..97b5481cf5 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/useStateDestructure@loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/useStateDestructure@loader.tsx @@ -1,2 +1,2 @@ -import { FaBolt, FaBook, FaCheckCircle, FaCogs } from 'react-icons/fa' -import { VscPreview, VscWand } from 'react-icons/vsc' +import { FaBolt, FaBook, FaCheckCircle, FaCogs } from 'react-icons/fa'; +import { VscPreview, VscWand } from 'react-icons/vsc'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/using.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/using.tsx index 811b66a9d3..c58f0f663b 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/using.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/using.tsx @@ -1,5 +1,5 @@ -const $$splitLoaderImporter = () => import('using.tsx?tsr-split=loader') -import { lazyFn } from '@tanstack/react-router' +const $$splitLoaderImporter = () => import('using.tsx?tsr-split=loader'); +import { lazyFn } from '@tanstack/react-router'; export const Route = createFileRoute({ - loader: lazyFn($$splitLoaderImporter, 'loader'), -}) + loader: lazyFn($$splitLoaderImporter, 'loader') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/using@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/using@loader.tsx index 3b60e73b8d..7e4f4fde9b 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/using@loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/using@loader.tsx @@ -1,9 +1,17 @@ const DummyPostResource = (postId: string) => ({ - postData: { id: postId, title: 'dummy', body: 'dummy' }, - [Symbol.dispose]: () => console.log('disposing!'), -}) -const SplitLoader = ({ params: { postId } }) => { - using dummyPost = DummyPostResource(postId) - return dummyPost.postData -} -export { SplitLoader as loader } + postData: { + id: postId, + title: 'dummy', + body: 'dummy' + }, + [Symbol.dispose]: () => console.log('disposing!') +}); +const SplitLoader = ({ + params: { + postId + } +}) => { + using dummyPost = DummyPostResource(postId); + return dummyPost.postData; +}; +export { SplitLoader as loader }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/arrow-function.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/arrow-function.tsx index 19dfb7e3ba..380087d43c 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/arrow-function.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/arrow-function.tsx @@ -1,12 +1,10 @@ -const $$splitComponentImporter = () => - import('arrow-function.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -const $$splitLoaderImporter = () => - import('arrow-function.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyFn } from '@tanstack/react-router' -import * as React from 'react' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('arrow-function.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +const $$splitLoaderImporter = () => import('arrow-function.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyFn } from '@tanstack/react-router'; +import * as React from 'react'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/posts')({ loader: lazyFn($$splitLoaderImporter, 'loader'), - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/arrow-function@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/arrow-function@component---loader---notFoundComponent---pendingComponent.tsx index e2f2a1ccdb..764043a59c 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/arrow-function@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/arrow-function@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,34 +1,30 @@ -import * as React from 'react' -import { Link, Outlet } from '@tanstack/react-router' -import { fetchPosts } from '../posts' -import { Route } from 'arrow-function.tsx' +import * as React from 'react'; +import { Link, Outlet } from '@tanstack/react-router'; +import { fetchPosts } from '../posts'; +import { Route } from "arrow-function.tsx"; const PostsComponent = () => { - const posts = Route.useLoaderData() - return ( - <div className="p-2 flex gap-2"> + const posts = Route.useLoaderData(); + return <div className="p-2 flex gap-2"> <ul className="list-disc pl-4"> - {[...posts, { id: 'i-do-not-exist', title: 'Non-existent Post' }]?.map( - (post) => { - return ( - <li key={post.id} className="whitespace-nowrap"> - <Link - to="/posts/$postId" - params={{ postId: post.id }} - className="block py-1 text-blue-800 hover:text-blue-600" - activeProps={{ className: 'text-black font-bold' }} - > + {[...posts, { + id: 'i-do-not-exist', + title: 'Non-existent Post' + }]?.map(post => { + return <li key={post.id} className="whitespace-nowrap"> + <Link to="/posts/$postId" params={{ + postId: post.id + }} className="block py-1 text-blue-800 hover:text-blue-600" activeProps={{ + className: 'text-black font-bold' + }}> <div>{post.title.substring(0, 20)}</div> </Link> - </li> - ) - }, - )} + </li>; + })} </ul> <hr /> <Outlet /> - </div> - ) -} -const SplitLoader = fetchPosts -export { SplitLoader as loader } -export { PostsComponent as component } + </div>; +}; +const SplitLoader = fetchPosts; +export { SplitLoader as loader }; +export { PostsComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/arrow-function@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/arrow-function@errorComponent.tsx index 371dc65868..5f67a6fff1 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/arrow-function@errorComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/arrow-function@errorComponent.tsx @@ -1 +1 @@ -import * as React from 'react' +import * as React from 'react'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/boolean-null-literals.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/boolean-null-literals.tsx index 68fd7fc203..d3f54dd789 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/boolean-null-literals.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/boolean-null-literals.tsx @@ -1,14 +1,13 @@ -const $$splitLoaderImporter = () => - import('boolean-null-literals.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyFn } from '@tanstack/react-router' -const $$splitComponentImporter = () => - import('boolean-null-literals.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/router' +const $$splitLoaderImporter = () => import('boolean-null-literals.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyFn } from '@tanstack/react-router'; +const $$splitComponentImporter = () => import('boolean-null-literals.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/router'; + // Test errorComponent with false literal export const Route = createFileRoute('/test')({ component: lazyRouteComponent($$splitComponentImporter, 'component'), errorComponent: false, pendingComponent: null, - loader: lazyFn($$splitLoaderImporter, 'loader'), -}) + loader: lazyFn($$splitLoaderImporter, 'loader') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/boolean-null-literals@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/boolean-null-literals@component---loader---notFoundComponent---pendingComponent.tsx index 7133d0d77e..40973b0328 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/boolean-null-literals@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/boolean-null-literals@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,5 +1,7 @@ // Test errorComponent with false literal -const SplitLoader = async () => ({ data: 'test' }) -export { SplitLoader as loader } -const SplitComponent = () => <div>Test Component</div> -export { SplitComponent as component } +const SplitLoader = async () => ({ + data: 'test' +}); +export { SplitLoader as loader }; +const SplitComponent = () => <div>Test Component</div>; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/chinese.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/chinese.tsx index bfe965067d..d08045e238 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/chinese.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/chinese.tsx @@ -1,11 +1,10 @@ -const $$splitComponentImporter = () => - import('chinese.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import * as React from 'react' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('chinese.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import * as React from 'react'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/')({ - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); interface DemoProps { - title: string -} + title: string; +} \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/chinese@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/chinese@component---loader---notFoundComponent---pendingComponent.tsx index 2ac1fa54ff..003ca944a1 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/chinese@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/chinese@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,27 +1,23 @@ -import * as React from 'react' +import * as React from 'react'; function HomeComponent() { - return ( - <div className="p-2"> + return <div className="p-2"> <Demo title="标题很好看,谁说不是呢?" /> <Demo title="The title looks great, who can deny that?" /> - </div> - ) + </div>; } interface DemoProps { - title: string + title: string; } -function Demo({ title }: DemoProps) { - return ( - <h1 - style={{ - color: '#2969ff', - fontSize: '2rem', - fontWeight: 'bold', - letterSpacing: '3px', - }} - > +function Demo({ + title +}: DemoProps) { + return <h1 style={{ + color: '#2969ff', + fontSize: '2rem', + fontWeight: 'bold', + letterSpacing: '3px' + }}> {title} - </h1> - ) + </h1>; } -export { HomeComponent as component } +export { HomeComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/chinese@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/chinese@errorComponent.tsx index cbcea8cc40..b4de370f4e 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/chinese@errorComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/chinese@errorComponent.tsx @@ -1,4 +1,4 @@ -import * as React from 'react' +import * as React from 'react'; interface DemoProps { - title: string -} + title: string; +} \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/circular-reference-arrow-function.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/circular-reference-arrow-function.tsx index 819a4a9bf4..fe221be964 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/circular-reference-arrow-function.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/circular-reference-arrow-function.tsx @@ -1,7 +1,6 @@ -const $$splitComponentImporter = () => - import('circular-reference-arrow-function.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('circular-reference-arrow-function.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/')({ - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/circular-reference-arrow-function@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/circular-reference-arrow-function@component---loader---notFoundComponent---pendingComponent.tsx index 59c5b5eec2..39ace71ebe 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/circular-reference-arrow-function@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/circular-reference-arrow-function@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,17 +1,19 @@ function getComponentName(obj: Record<string, unknown>): string { - return Object.keys(obj)[0] + return Object.keys(obj)[0]; } const App = () => { - const componentName = getComponentName({ App }) - return ( - <div> + const componentName = getComponentName({ + App + }); + return <div> Component Name is {componentName} <OtherComponent /> - </div> - ) -} + </div>; +}; function OtherComponent() { - const componentName = getComponentName({ App }) - return <div>App component name is {componentName}</div> + const componentName = getComponentName({ + App + }); + return <div>App component name is {componentName}</div>; } -export { App as component } +export { App as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/circular-reference-function.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/circular-reference-function.tsx index d4a70c7341..14d74d432d 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/circular-reference-function.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/circular-reference-function.tsx @@ -1,7 +1,6 @@ -const $$splitComponentImporter = () => - import('circular-reference-function.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('circular-reference-function.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/')({ - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/circular-reference-function@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/circular-reference-function@component---loader---notFoundComponent---pendingComponent.tsx index 22fbb8669f..96a753ad8a 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/circular-reference-function@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/circular-reference-function@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,17 +1,19 @@ function getComponentName(obj: Record<string, unknown>): string { - return Object.keys(obj)[0] + return Object.keys(obj)[0]; } function App() { - const componentName = getComponentName({ App }) - return ( - <div> + const componentName = getComponentName({ + App + }); + return <div> Component Name is {componentName} <OtherComponent /> - </div> - ) + </div>; } function OtherComponent() { - const componentName = getComponentName({ App }) - return <div>App component name is {componentName}</div> + const componentName = getComponentName({ + App + }); + return <div>App component name is {componentName}</div>; } -export { App as component } +export { App as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/conditional-properties.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/conditional-properties.tsx index 3b956ec804..dfb3b09c5e 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/conditional-properties.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/conditional-properties.tsx @@ -1,11 +1,9 @@ -const $$splitLoaderImporter = () => - import('conditional-properties.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyFn } from '@tanstack/react-router' -const $$splitComponentImporter = () => - import('conditional-properties.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitLoaderImporter = () => import('conditional-properties.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyFn } from '@tanstack/react-router'; +const $$splitComponentImporter = () => import('conditional-properties.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/posts')({ component: lazyRouteComponent($$splitComponentImporter, 'component'), - loader: lazyFn($$splitLoaderImporter, 'loader'), -}) + loader: lazyFn($$splitLoaderImporter, 'loader') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/conditional-properties@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/conditional-properties@component---loader---notFoundComponent---pendingComponent.tsx index 88dcc8e930..857b130de7 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/conditional-properties@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/conditional-properties@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,7 +1,7 @@ -import { isEnabled } from '@features/feature-flags' -import TrueImport from '@modules/true-component' -import { FalseComponent, falseLoader } from '@modules/false-component' -const SplitLoader = isEnabled ? TrueImport.loader : falseLoader -export { SplitLoader as loader } -const SplitComponent = isEnabled ? TrueImport.Component : FalseComponent -export { SplitComponent as component } +import { isEnabled } from '@features/feature-flags'; +import TrueImport from '@modules/true-component'; +import { FalseComponent, falseLoader } from '@modules/false-component'; +const SplitLoader = isEnabled ? TrueImport.loader : falseLoader; +export { SplitLoader as loader }; +const SplitComponent = isEnabled ? TrueImport.Component : FalseComponent; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-export-multiple.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-export-multiple.tsx index e3c598b0b5..8b823166e4 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-export-multiple.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-export-multiple.tsx @@ -1,13 +1,15 @@ -const $$splitComponentImporter = () => - import('destructured-export-multiple.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('destructured-export-multiple.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const getConfig = () => ({ baseUrl: 'https://api.example.com', - timeout: 5000, -}) -export const { baseUrl, timeout } = getConfig() -export const [first, second] = [1, 2] + timeout: 5000 +}); +export const { + baseUrl, + timeout +} = getConfig(); +export const [first, second] = [1, 2]; export const Route = createFileRoute('/about')({ - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-export-multiple@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-export-multiple@component---loader---notFoundComponent---pendingComponent.tsx index 6a15a59c0a..9441b5a689 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-export-multiple@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-export-multiple@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,10 +1,8 @@ -import { baseUrl, timeout } from 'destructured-export-multiple.tsx' +import { baseUrl, timeout } from "destructured-export-multiple.tsx"; function AboutComponent() { - return ( - <div> + return <div> <p>Base URL: {baseUrl}</p> <p>Timeout: {timeout}</p> - </div> - ) + </div>; } -export { AboutComponent as component } +export { AboutComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-export-nested.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-export-nested.tsx index f1608ec6dd..5920a891c0 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-export-nested.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-export-nested.tsx @@ -1,16 +1,19 @@ -const $$splitComponentImporter = () => - import('destructured-export-nested.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('destructured-export-nested.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; const getConfig = () => ({ - api: { baseUrl: 'https://api.example.com' }, + api: { + baseUrl: 'https://api.example.com' + }, timeout: 5000, - extra: 'data', -}) + extra: 'data' +}); export const { - api: { baseUrl }, + api: { + baseUrl + }, ...rest -} = getConfig() +} = getConfig(); export const Route = createFileRoute('/about')({ - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-export-nested@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-export-nested@component---loader---notFoundComponent---pendingComponent.tsx index 9bc538525f..8ba46e33e1 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-export-nested@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-export-nested@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,9 +1,7 @@ -import { baseUrl } from 'destructured-export-nested.tsx' +import { baseUrl } from "destructured-export-nested.tsx"; function AboutComponent() { - return ( - <div> + return <div> <p>Base URL: {baseUrl}</p> - </div> - ) + </div>; } -export { AboutComponent as component } +export { AboutComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-export.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-export.tsx index 397c6400f5..f573764824 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-export.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-export.tsx @@ -1,11 +1,17 @@ -const $$splitComponentImporter = () => - import('destructured-export.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('destructured-export.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export function getObjectCallback() { - return { getObject: () => ({ constA: 10, constB: 5 }) } + return { + getObject: () => ({ + constA: 10, + constB: 5 + }) + }; } -export const { getObject } = getObjectCallback() +export const { + getObject +} = getObjectCallback(); export const Route = createFileRoute('/about')({ - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-export@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-export@component---loader---notFoundComponent---pendingComponent.tsx index b0abbd2e6e..f58942d5af 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-export@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-export@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,11 +1,14 @@ export function getObjectCallback() { - return { getObject: () => ({ constA: 10, constB: 5 }) } + return { + getObject: () => ({ + constA: 10, + constB: 5 + }) + }; } function AboutComponent() { - return ( - <div className="p-2"> + return <div className="p-2"> <h3>About</h3> - </div> - ) + </div>; } -export { AboutComponent as component } +export { AboutComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-export@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-export@errorComponent.tsx index 024e0e620e..45fb19eecd 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-export@errorComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-export@errorComponent.tsx @@ -1,3 +1,8 @@ export function getObjectCallback() { - return { getObject: () => ({ constA: 10, constB: 5 }) } -} + return { + getObject: () => ({ + constA: 10, + constB: 5 + }) + }; +} \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-react-memo-imported-component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-react-memo-imported-component.tsx index b8053fff9e..1776055cc2 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-react-memo-imported-component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-react-memo-imported-component.tsx @@ -1,11 +1,9 @@ -const $$splitLoaderImporter = () => - import('destructured-react-memo-imported-component.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyFn } from '@tanstack/react-router' -const $$splitComponentImporter = () => - import('destructured-react-memo-imported-component.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitLoaderImporter = () => import('destructured-react-memo-imported-component.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyFn } from '@tanstack/react-router'; +const $$splitComponentImporter = () => import('destructured-react-memo-imported-component.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/')({ component: lazyRouteComponent($$splitComponentImporter, 'component'), - loader: lazyFn($$splitLoaderImporter, 'loader'), -}) + loader: lazyFn($$splitLoaderImporter, 'loader') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-react-memo-imported-component@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-react-memo-imported-component@component---loader---notFoundComponent---pendingComponent.tsx index 66f97a20d0..931bed75b4 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-react-memo-imported-component@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-react-memo-imported-component@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,9 +1,9 @@ -import { memo } from 'react' -import { importedLoader } from '../../shared/imported' +import { memo } from 'react'; +import { importedLoader } from '../../shared/imported'; function Component() { - return <div>Component</div> + return <div>Component</div>; } -const SplitLoader = importedLoader -export { SplitLoader as loader } -const SplitComponent = memo(Component) -export { SplitComponent as component } +const SplitLoader = importedLoader; +export { SplitLoader as loader }; +const SplitComponent = memo(Component); +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-route-options-defaults.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-route-options-defaults.tsx index 636e017a64..6cac408c56 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-route-options-defaults.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-route-options-defaults.tsx @@ -1,11 +1,9 @@ -const $$splitLoaderImporter = () => - import('destructured-route-options-defaults.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyFn } from '@tanstack/react-router' -const $$splitComponentImporter = () => - import('destructured-route-options-defaults.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitLoaderImporter = () => import('destructured-route-options-defaults.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyFn } from '@tanstack/react-router'; +const $$splitComponentImporter = () => import('destructured-route-options-defaults.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/about')({ component: lazyRouteComponent($$splitComponentImporter, 'component'), - loader: lazyFn($$splitLoaderImporter, 'loader'), -}) + loader: lazyFn($$splitLoaderImporter, 'loader') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-route-options-defaults@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-route-options-defaults@component---loader---notFoundComponent---pendingComponent.tsx index ae1cd17853..2f8ef91c49 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-route-options-defaults@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructured-route-options-defaults@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,17 +1,23 @@ function defaultLoader() { - return { message: 'default' } + return { + message: 'default' + }; } function DefaultComponent() { - return <div>Default</div> + return <div>Default</div>; } const createBits = () => ({ component: ActualComponent, - loader: () => ({ message: 'hello' }), -}) -const { component: MyComponent = DefaultComponent, loader = defaultLoader } = - createBits() + loader: () => ({ + message: 'hello' + }) +}); +const { + component: MyComponent = DefaultComponent, + loader = defaultLoader +} = createBits(); function ActualComponent() { - return <div>About</div> + return <div>About</div>; } -export { loader } -export { MyComponent as component } +export { loader }; +export { MyComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructuring.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructuring.tsx index 112fded569..d80f17484f 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructuring.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructuring.tsx @@ -1,9 +1,11 @@ import thing from 'thing' + export function test() { const { foo: { bar: { destructured }, }, } = thing + return destructured } diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructuring@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructuring@component---loader---notFoundComponent---pendingComponent.tsx index 112fded569..858c5c0e05 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructuring@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructuring@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,9 +1,11 @@ -import thing from 'thing' +import thing from 'thing'; export function test() { const { foo: { - bar: { destructured }, - }, - } = thing - return destructured -} + bar: { + destructured + } + } + } = thing; + return destructured; +} \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructuring@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructuring@errorComponent.tsx index 112fded569..858c5c0e05 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructuring@errorComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/destructuring@errorComponent.tsx @@ -1,9 +1,11 @@ -import thing from 'thing' +import thing from 'thing'; export function test() { const { foo: { - bar: { destructured }, - }, - } = thing - return destructured -} + bar: { + destructured + } + } + } = thing; + return destructured; +} \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/directive-prologue.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/directive-prologue.tsx index b807ba9283..178bec9bf7 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/directive-prologue.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/directive-prologue.tsx @@ -1,8 +1,8 @@ -'use client' -const $$splitComponentImporter = () => - import('directive-prologue.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +'use client'; + +const $$splitComponentImporter = () => import('directive-prologue.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/directive')({ - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/directive-prologue@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/directive-prologue@component---loader---notFoundComponent---pendingComponent.tsx index 9ee4bd8f4c..ce7cd5e5ee 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/directive-prologue@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/directive-prologue@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,5 +1,6 @@ -'use client' +'use client'; + const SplitComponent = () => { - return <div>directive preserved</div> -} -export { SplitComponent as component } + return <div>directive preserved</div>; +}; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/explicit-undefined-component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/explicit-undefined-component.tsx index 8109a89624..4fdd9d1c68 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/explicit-undefined-component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/explicit-undefined-component.tsx @@ -1,3 +1,6 @@ import React from 'react' import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/')({ component: undefined }) + +export const Route = createFileRoute('/')({ + component: undefined, +}) diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/explicit-undefined-component@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/explicit-undefined-component@component---loader---notFoundComponent---pendingComponent.tsx index b45dfaa8f0..b01f5e7863 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/explicit-undefined-component@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/explicit-undefined-component@component---loader---notFoundComponent---pendingComponent.tsx @@ -1 +1 @@ -import React from 'react' +import React from 'react'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/explicit-undefined-component@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/explicit-undefined-component@errorComponent.tsx index b45dfaa8f0..b01f5e7863 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/explicit-undefined-component@errorComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/explicit-undefined-component@errorComponent.tsx @@ -1 +1 @@ -import React from 'react' +import React from 'react'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/export-default-component-and-normal-notFound.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/export-default-component-and-normal-notFound.tsx index 534529220a..a3e020c559 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/export-default-component-and-normal-notFound.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/export-default-component-and-normal-notFound.tsx @@ -1,23 +1,15 @@ -console.warn( - '[tanstack-router] These exports from "export-default-component-and-normal-notFound.tsx" will not be code-split and will increase your bundle size:\n- Home\nFor the best optimization, these items should either have their export statements removed, or be imported from another location that is not a route file.', -) -const $$splitNotFoundComponentImporter = () => - import('export-default-component-and-normal-notFound.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import React, { useState } from 'react' -import { createFileRoute } from '@tanstack/react-router' +console.warn("[tanstack-router] These exports from \"export-default-component-and-normal-notFound.tsx\" will not be code-split and will increase your bundle size:\n- Home\nFor the best optimization, these items should either have their export statements removed, or be imported from another location that is not a route file."); +const $$splitNotFoundComponentImporter = () => import('export-default-component-and-normal-notFound.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import React, { useState } from 'react'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/home')({ component: Home, - notFoundComponent: lazyRouteComponent( - $$splitNotFoundComponentImporter, - 'notFoundComponent', - ), -}) + notFoundComponent: lazyRouteComponent($$splitNotFoundComponentImporter, 'notFoundComponent') +}); export default function Home() { - const [one, setOne] = useState('this is from a state') - return ( - <div> + const [one, setOne] = useState('this is from a state'); + return <div> <h1>{one}</h1> - </div> - ) -} + </div>; +} \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/export-default-component-and-normal-notFound@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/export-default-component-and-normal-notFound@component---loader---notFoundComponent---pendingComponent.tsx index 3da924c04c..62cd0a1036 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/export-default-component-and-normal-notFound@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/export-default-component-and-normal-notFound@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,5 +1,5 @@ -import React from 'react' +import React from 'react'; function NotFoundComponent() { - return <div>Not Found</div> + return <div>Not Found</div>; } -export { NotFoundComponent as notFoundComponent } +export { NotFoundComponent as notFoundComponent }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/export-default-component-and-normal-notFound@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/export-default-component-and-normal-notFound@errorComponent.tsx index b45dfaa8f0..b01f5e7863 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/export-default-component-and-normal-notFound@errorComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/export-default-component-and-normal-notFound@errorComponent.tsx @@ -1 +1 @@ -import React from 'react' +import React from 'react'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/export-default-component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/export-default-component.tsx index de2d748c91..c5198b9e00 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/export-default-component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/export-default-component.tsx @@ -1,8 +1,13 @@ import React, { useState } from 'react' import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/home')({ component: Home }) + +export const Route = createFileRoute('/home')({ + component: Home, +}) + export default function Home() { const [one, setOne] = useState('this is from a state') + return ( <div> <h1>{one}</h1> diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/export-default-component@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/export-default-component@component---loader---notFoundComponent---pendingComponent.tsx index b45dfaa8f0..b01f5e7863 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/export-default-component@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/export-default-component@component---loader---notFoundComponent---pendingComponent.tsx @@ -1 +1 @@ -import React from 'react' +import React from 'react'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/export-default-component@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/export-default-component@errorComponent.tsx index b45dfaa8f0..b01f5e7863 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/export-default-component@errorComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/export-default-component@errorComponent.tsx @@ -1 +1 @@ -import React from 'react' +import React from 'react'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/function-as-parameter.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/function-as-parameter.tsx index 817b89d69a..3ae9710cd5 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/function-as-parameter.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/function-as-parameter.tsx @@ -1,20 +1,29 @@ import * as React from 'react' // @ts-expect-error import { useMemo } from 'tan-react' + const useUsedVar = 'i-am-unused' + const ReactUseMemoCall1 = React.useMemo(function performAction() { return 'true' }, []) + console.info(ReactUseMemoCall1) + const ReactUseMemoCall2 = React.useMemo(() => { return 'true' }, []) + console.info(ReactUseMemoCall2) + const UseMemoCall1 = useMemo(function performAction() { return 'true' }, []) + console.info(UseMemoCall1) + const UseMemoCall2 = useMemo(() => { return 'true' }, []) + console.info(UseMemoCall2) diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/function-as-parameter@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/function-as-parameter@component---loader---notFoundComponent---pendingComponent.tsx index 817b89d69a..23e2cd0f03 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/function-as-parameter@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/function-as-parameter@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,20 +1,20 @@ -import * as React from 'react' +import * as React from 'react'; // @ts-expect-error -import { useMemo } from 'tan-react' -const useUsedVar = 'i-am-unused' +import { useMemo } from 'tan-react'; +const useUsedVar = 'i-am-unused'; const ReactUseMemoCall1 = React.useMemo(function performAction() { - return 'true' -}, []) -console.info(ReactUseMemoCall1) + return 'true'; +}, []); +console.info(ReactUseMemoCall1); const ReactUseMemoCall2 = React.useMemo(() => { - return 'true' -}, []) -console.info(ReactUseMemoCall2) + return 'true'; +}, []); +console.info(ReactUseMemoCall2); const UseMemoCall1 = useMemo(function performAction() { - return 'true' -}, []) -console.info(UseMemoCall1) + return 'true'; +}, []); +console.info(UseMemoCall1); const UseMemoCall2 = useMemo(() => { - return 'true' -}, []) -console.info(UseMemoCall2) + return 'true'; +}, []); +console.info(UseMemoCall2); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/function-as-parameter@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/function-as-parameter@errorComponent.tsx index 817b89d69a..23e2cd0f03 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/function-as-parameter@errorComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/function-as-parameter@errorComponent.tsx @@ -1,20 +1,20 @@ -import * as React from 'react' +import * as React from 'react'; // @ts-expect-error -import { useMemo } from 'tan-react' -const useUsedVar = 'i-am-unused' +import { useMemo } from 'tan-react'; +const useUsedVar = 'i-am-unused'; const ReactUseMemoCall1 = React.useMemo(function performAction() { - return 'true' -}, []) -console.info(ReactUseMemoCall1) + return 'true'; +}, []); +console.info(ReactUseMemoCall1); const ReactUseMemoCall2 = React.useMemo(() => { - return 'true' -}, []) -console.info(ReactUseMemoCall2) + return 'true'; +}, []); +console.info(ReactUseMemoCall2); const UseMemoCall1 = useMemo(function performAction() { - return 'true' -}, []) -console.info(UseMemoCall1) + return 'true'; +}, []); +console.info(UseMemoCall1); const UseMemoCall2 = useMemo(() => { - return 'true' -}, []) -console.info(UseMemoCall2) + return 'true'; +}, []); +console.info(UseMemoCall2); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/function-declaration.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/function-declaration.tsx index bdef68ad2d..6076420598 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/function-declaration.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/function-declaration.tsx @@ -1,12 +1,10 @@ -const $$splitComponentImporter = () => - import('function-declaration.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -const $$splitLoaderImporter = () => - import('function-declaration.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyFn } from '@tanstack/react-router' -import * as React from 'react' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('function-declaration.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +const $$splitLoaderImporter = () => import('function-declaration.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyFn } from '@tanstack/react-router'; +import * as React from 'react'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/posts')({ loader: lazyFn($$splitLoaderImporter, 'loader'), - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/function-declaration@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/function-declaration@component---loader---notFoundComponent---pendingComponent.tsx index 5289c0c3c4..d453767c20 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/function-declaration@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/function-declaration@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,34 +1,30 @@ -import * as React from 'react' -import { Link, Outlet } from '@tanstack/react-router' -import { fetchPosts } from '../posts' -import { Route } from 'function-declaration.tsx' +import * as React from 'react'; +import { Link, Outlet } from '@tanstack/react-router'; +import { fetchPosts } from '../posts'; +import { Route } from "function-declaration.tsx"; function PostsComponent() { - const posts = Route.useLoaderData() - return ( - <div className="p-2 flex gap-2"> + const posts = Route.useLoaderData(); + return <div className="p-2 flex gap-2"> <ul className="list-disc pl-4"> - {[...posts, { id: 'i-do-not-exist', title: 'Non-existent Post' }]?.map( - (post) => { - return ( - <li key={post.id} className="whitespace-nowrap"> - <Link - to="/posts/$postId" - params={{ postId: post.id }} - className="block py-1 text-blue-800 hover:text-blue-600" - activeProps={{ className: 'text-black font-bold' }} - > + {[...posts, { + id: 'i-do-not-exist', + title: 'Non-existent Post' + }]?.map(post => { + return <li key={post.id} className="whitespace-nowrap"> + <Link to="/posts/$postId" params={{ + postId: post.id + }} className="block py-1 text-blue-800 hover:text-blue-600" activeProps={{ + className: 'text-black font-bold' + }}> <div>{post.title.substring(0, 20)}</div> </Link> - </li> - ) - }, - )} + </li>; + })} </ul> <hr /> <Outlet /> - </div> - ) + </div>; } -const SplitLoader = fetchPosts -export { SplitLoader as loader } -export { PostsComponent as component } +const SplitLoader = fetchPosts; +export { SplitLoader as loader }; +export { PostsComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/function-declaration@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/function-declaration@errorComponent.tsx index 371dc65868..5f67a6fff1 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/function-declaration@errorComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/function-declaration@errorComponent.tsx @@ -1 +1 @@ -import * as React from 'react' +import * as React from 'react'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/importAttribute.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/importAttribute.tsx index f336e2ff0f..cec0324adf 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/importAttribute.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/importAttribute.tsx @@ -1,7 +1,6 @@ -const $$splitComponentImporter = () => - import('importAttribute.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('importAttribute.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/')({ - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/importAttribute@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/importAttribute@component---loader---notFoundComponent---pendingComponent.tsx index 88abef0c00..f34d3c6408 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/importAttribute@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/importAttribute@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,3 +1,3 @@ -import { test } from './test' with { type: 'macro' } -const SplitComponent = () => test -export { SplitComponent as component } +import { test } from './test' with { type: 'macro' }; +const SplitComponent = () => test; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-default-component-destructured-loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-default-component-destructured-loader.tsx index d7c5699549..d79c8e0f32 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-default-component-destructured-loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-default-component-destructured-loader.tsx @@ -1,11 +1,9 @@ -const $$splitLoaderImporter = () => - import('imported-default-component-destructured-loader.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyFn } from '@tanstack/react-router' -const $$splitComponentImporter = () => - import('imported-default-component-destructured-loader.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitLoaderImporter = () => import('imported-default-component-destructured-loader.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyFn } from '@tanstack/react-router'; +const $$splitComponentImporter = () => import('imported-default-component-destructured-loader.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/')({ component: lazyRouteComponent($$splitComponentImporter, 'component'), - loader: lazyFn($$splitLoaderImporter, 'loader'), -}) + loader: lazyFn($$splitLoaderImporter, 'loader') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-default-component-destructured-loader@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-default-component-destructured-loader@component---loader---notFoundComponent---pendingComponent.tsx index b7ed94da4a..d4fc40141e 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-default-component-destructured-loader@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-default-component-destructured-loader@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,5 +1,5 @@ -import importedComponent, { importedLoader } from '../../shared/imported' -const SplitLoader = importedLoader -export { SplitLoader as loader } -const SplitComponent = importedComponent -export { SplitComponent as component } +import importedComponent, { importedLoader } from '../../shared/imported'; +const SplitLoader = importedLoader; +export { SplitLoader as loader }; +const SplitComponent = importedComponent; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-default-component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-default-component.tsx index 81ec753301..c165f65262 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-default-component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-default-component.tsx @@ -1,7 +1,6 @@ -const $$splitComponentImporter = () => - import('imported-default-component.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('imported-default-component.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/')({ - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-default-component@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-default-component@component---loader---notFoundComponent---pendingComponent.tsx index d356227040..31ccf07c52 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-default-component@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-default-component@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,3 +1,3 @@ -import ImportedDefaultComponent from '../../shared/imported' -const SplitComponent = ImportedDefaultComponent -export { SplitComponent as component } +import ImportedDefaultComponent from '../../shared/imported'; +const SplitComponent = ImportedDefaultComponent; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-errorComponent.tsx index e2179478b3..4152c9af17 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-errorComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-errorComponent.tsx @@ -1,13 +1,8 @@ -const $$splitErrorComponentImporter = () => - import('imported-errorComponent.tsx?tsr-split=errorComponent') -const $$splitComponentImporter = () => - import('imported-errorComponent.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitErrorComponentImporter = () => import('imported-errorComponent.tsx?tsr-split=errorComponent'); +const $$splitComponentImporter = () => import('imported-errorComponent.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/')({ component: lazyRouteComponent($$splitComponentImporter, 'component'), - errorComponent: lazyRouteComponent( - $$splitErrorComponentImporter, - 'errorComponent', - ), -}) + errorComponent: lazyRouteComponent($$splitErrorComponentImporter, 'errorComponent') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-errorComponent@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-errorComponent@component---loader---notFoundComponent---pendingComponent.tsx index d356227040..31ccf07c52 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-errorComponent@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-errorComponent@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,3 +1,3 @@ -import ImportedDefaultComponent from '../../shared/imported' -const SplitComponent = ImportedDefaultComponent -export { SplitComponent as component } +import ImportedDefaultComponent from '../../shared/imported'; +const SplitComponent = ImportedDefaultComponent; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-errorComponent@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-errorComponent@errorComponent.tsx index 3f20c3e485..7a8654fb94 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-errorComponent@errorComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-errorComponent@errorComponent.tsx @@ -1,3 +1,3 @@ -import { importedErrorComponent } from '../../shared/imported' -const SplitErrorComponent = importedErrorComponent -export { SplitErrorComponent as errorComponent } +import { importedErrorComponent } from '../../shared/imported'; +const SplitErrorComponent = importedErrorComponent; +export { SplitErrorComponent as errorComponent }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-notFoundComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-notFoundComponent.tsx index 31812e1e44..584c829f37 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-notFoundComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-notFoundComponent.tsx @@ -1,13 +1,8 @@ -const $$splitNotFoundComponentImporter = () => - import('imported-notFoundComponent.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -const $$splitComponentImporter = () => - import('imported-notFoundComponent.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitNotFoundComponentImporter = () => import('imported-notFoundComponent.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +const $$splitComponentImporter = () => import('imported-notFoundComponent.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/')({ component: lazyRouteComponent($$splitComponentImporter, 'component'), - notFoundComponent: lazyRouteComponent( - $$splitNotFoundComponentImporter, - 'notFoundComponent', - ), -}) + notFoundComponent: lazyRouteComponent($$splitNotFoundComponentImporter, 'notFoundComponent') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-notFoundComponent@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-notFoundComponent@component---loader---notFoundComponent---pendingComponent.tsx index 9f904a1a19..1273c7c50d 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-notFoundComponent@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-notFoundComponent@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,7 +1,5 @@ -import ImportedDefaultComponent, { - importedNotFoundComponent, -} from '../../shared/imported' -const SplitComponent = ImportedDefaultComponent -export { SplitComponent as component } -const SplitNotFoundComponent = importedNotFoundComponent -export { SplitNotFoundComponent as notFoundComponent } +import ImportedDefaultComponent, { importedNotFoundComponent } from '../../shared/imported'; +const SplitComponent = ImportedDefaultComponent; +export { SplitComponent as component }; +const SplitNotFoundComponent = importedNotFoundComponent; +export { SplitNotFoundComponent as notFoundComponent }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-pendingComponent.tsx index 0996abeb6c..1be3f8071b 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-pendingComponent.tsx @@ -1,13 +1,8 @@ -const $$splitPendingComponentImporter = () => - import('imported-pendingComponent.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -const $$splitComponentImporter = () => - import('imported-pendingComponent.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitPendingComponentImporter = () => import('imported-pendingComponent.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +const $$splitComponentImporter = () => import('imported-pendingComponent.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/')({ component: lazyRouteComponent($$splitComponentImporter, 'component'), - pendingComponent: lazyRouteComponent( - $$splitPendingComponentImporter, - 'pendingComponent', - ), -}) + pendingComponent: lazyRouteComponent($$splitPendingComponentImporter, 'pendingComponent') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-pendingComponent@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-pendingComponent@component---loader---notFoundComponent---pendingComponent.tsx index d24c7b1505..0368000afa 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-pendingComponent@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported-pendingComponent@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,7 +1,5 @@ -import ImportedDefaultComponent, { - importedPendingComponent, -} from '../../shared/imported' -const SplitComponent = ImportedDefaultComponent -export { SplitComponent as component } -const SplitPendingComponent = importedPendingComponent -export { SplitPendingComponent as pendingComponent } +import ImportedDefaultComponent, { importedPendingComponent } from '../../shared/imported'; +const SplitComponent = ImportedDefaultComponent; +export { SplitComponent as component }; +const SplitPendingComponent = importedPendingComponent; +export { SplitPendingComponent as pendingComponent }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported.tsx index 75c54f18ad..14356133d6 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported.tsx @@ -1,11 +1,9 @@ -const $$splitLoaderImporter = () => - import('imported.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyFn } from '@tanstack/react-router' -const $$splitComponentImporter = () => - import('imported.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitLoaderImporter = () => import('imported.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyFn } from '@tanstack/react-router'; +const $$splitComponentImporter = () => import('imported.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/')({ component: lazyRouteComponent($$splitComponentImporter, 'component'), - loader: lazyFn($$splitLoaderImporter, 'loader'), -}) + loader: lazyFn($$splitLoaderImporter, 'loader') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported@component---loader---notFoundComponent---pendingComponent.tsx index 1c4d3e909b..ecc588688b 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/imported@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,5 +1,5 @@ -import { importedComponent, importedLoader } from '../../shared' -const SplitLoader = importedLoader -export { SplitLoader as loader } -const SplitComponent = importedComponent -export { SplitComponent as component } +import { importedComponent, importedLoader } from '../../shared'; +const SplitLoader = importedLoader; +export { SplitLoader as loader }; +const SplitComponent = importedComponent; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/inline.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/inline.tsx index fbc7185a17..3e2ea1f1c2 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/inline.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/inline.tsx @@ -1,10 +1,9 @@ -const $$splitComponentImporter = () => - import('inline.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import * as React from 'react' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('inline.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import * as React from 'react'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/')({ - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) -Route.addChildren([]) -export const test = 'test' + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); +Route.addChildren([]); +export const test = 'test'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/inline@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/inline@component---loader---notFoundComponent---pendingComponent.tsx index d28b872634..58ccfb2903 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/inline@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/inline@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,18 +1,18 @@ -import * as React from 'react' -import * as styles from '../style.css' -import { TEST_DATA } from '../test.const' -const Button = (props: { children: any }) => { - return <button>{props.children}</button> -} -import { Route } from 'inline.tsx' -import { test } from 'inline.tsx' +import * as React from 'react'; +import * as styles from '../style.css'; +import { TEST_DATA } from '../test.const'; +const Button = (props: { + children: any; +}) => { + return <button>{props.children}</button>; +}; +import { Route } from "inline.tsx"; +import { test } from "inline.tsx"; const SplitComponent = () => { - return ( - <div className="p-2"> - {test} - <h3 className={styles.indexPageTitle}>{TEST_DATA.welcome}</h3> - <Button>Click me</Button> - </div> - ) -} -export { SplitComponent as component } + return <div className="p-2"> + {test} + <h3 className={styles.indexPageTitle}>{TEST_DATA.welcome}</h3> + <Button>Click me</Button> + </div>; +}; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/inline@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/inline@errorComponent.tsx index 23fab71edc..9236af6021 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/inline@errorComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/inline@errorComponent.tsx @@ -1,2 +1,2 @@ -import * as React from 'react' -import { Route } from 'inline.tsx' +import * as React from 'react'; +import { Route } from "inline.tsx"; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/lowercase-function-declaration.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/lowercase-function-declaration.tsx deleted file mode 100644 index 55c51e878b..0000000000 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/lowercase-function-declaration.tsx +++ /dev/null @@ -1,19 +0,0 @@ -const $$splitErrorComponentImporter = () => - import('lowercase-function-declaration.tsx?tsr-split=errorComponent') -const $$splitPendingComponentImporter = () => - import('lowercase-function-declaration.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -const $$splitComponentImporter = () => - import('lowercase-function-declaration.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/')({ - component: lazyRouteComponent($$splitComponentImporter, 'component'), - pendingComponent: lazyRouteComponent( - $$splitPendingComponentImporter, - 'pendingComponent', - ), - errorComponent: lazyRouteComponent( - $$splitErrorComponentImporter, - 'errorComponent', - ), -}) diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/lowercase-function-declaration@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/lowercase-function-declaration@component---loader---notFoundComponent---pendingComponent.tsx deleted file mode 100644 index 3b432397b3..0000000000 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/lowercase-function-declaration@component---loader---notFoundComponent---pendingComponent.tsx +++ /dev/null @@ -1,8 +0,0 @@ -function component() { - return <div>lowercase function declaration</div> -} -function pendingComponent() { - return <div>lowercase pending function declaration</div> -} -export { component } -export { pendingComponent } diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/lowercase-function-declaration@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/lowercase-function-declaration@errorComponent.tsx deleted file mode 100644 index 9d411c1f0f..0000000000 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/lowercase-function-declaration@errorComponent.tsx +++ /dev/null @@ -1,4 +0,0 @@ -function errorComponent() { - return <div>lowercase error function declaration</div> -} -export { errorComponent } diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/lowercase-function-declaration@shared.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/lowercase-function-declaration@shared.tsx deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/random-number.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/random-number.tsx index 602ff5c117..5b4cfaaa9b 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/random-number.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/random-number.tsx @@ -1,42 +1,28 @@ -const $$splitComponentImporter = () => - import('random-number.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -const $$splitLoaderImporter = () => - import('random-number.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyFn } from '@tanstack/react-router' -import { Await, Link, createFileRoute } from '@tanstack/react-router' -import { Carbon } from '~/components/Carbon' -import { twMerge } from 'tailwind-merge' -import { FaDiscord, FaGithub, FaTshirt } from 'react-icons/fa' -import { CgMusicSpeaker, CgSpinner } from 'react-icons/cg' -import { Footer } from '~/components/Footer' -import SponsorPack from '~/components/SponsorPack' -import { LogoColor } from '~/components/LogoColor' -import agGridImage from '~/images/ag-grid.png' -import nozzleImage from '~/images/nozzle.png' -import bytesImage from '~/images/bytes.svg' -import bytesUidotdevImage from '~/images/bytes-uidotdev.png' -export const textColors = [ - `text-rose-500`, - `text-yellow-500`, - `text-teal-500`, - `text-blue-500`, -] -export const gradients = [ - `from-rose-500 to-yellow-500`, - `from-yellow-500 to-teal-500`, - `from-teal-500 to-violet-500`, - `from-blue-500 to-pink-500`, -] -const courses = [ - { - name: 'The Official TanStack React Query Course', - cardStyles: `border-t-4 border-red-500 hover:(border-green-500)`, - href: 'https://query.gg/?s=tanstack', - description: `Learn how to build enterprise quality apps with TanStack's React Query the easy way with our brand new course.`, - }, -] +const $$splitComponentImporter = () => import('random-number.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +const $$splitLoaderImporter = () => import('random-number.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyFn } from '@tanstack/react-router'; +import { Await, Link, createFileRoute } from '@tanstack/react-router'; +import { Carbon } from '~/components/Carbon'; +import { twMerge } from 'tailwind-merge'; +import { FaDiscord, FaGithub, FaTshirt } from 'react-icons/fa'; +import { CgMusicSpeaker, CgSpinner } from 'react-icons/cg'; +import { Footer } from '~/components/Footer'; +import SponsorPack from '~/components/SponsorPack'; +import { LogoColor } from '~/components/LogoColor'; +import agGridImage from '~/images/ag-grid.png'; +import nozzleImage from '~/images/nozzle.png'; +import bytesImage from '~/images/bytes.svg'; +import bytesUidotdevImage from '~/images/bytes-uidotdev.png'; +export const textColors = [`text-rose-500`, `text-yellow-500`, `text-teal-500`, `text-blue-500`]; +export const gradients = [`from-rose-500 to-yellow-500`, `from-yellow-500 to-teal-500`, `from-teal-500 to-violet-500`, `from-blue-500 to-pink-500`]; +const courses = [{ + name: 'The Official TanStack React Query Course', + cardStyles: `border-t-4 border-red-500 hover:(border-green-500)`, + href: 'https://query.gg/?s=tanstack', + description: `Learn how to build enterprise quality apps with TanStack's React Query the easy way with our brand new course.` +}]; export const Route = createFileRoute('/')({ loader: lazyFn($$splitLoaderImporter, 'loader'), - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/random-number@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/random-number@component---loader---notFoundComponent---pendingComponent.tsx index 37649d8606..c133e05d9e 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/random-number@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/random-number@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,56 +1,69 @@ -import { Await, Link, defer } from '@tanstack/react-router' -import { Carbon } from '~/components/Carbon' -import { twMerge } from 'tailwind-merge' -import { FaDiscord, FaGithub, FaTshirt } from 'react-icons/fa' -import { CgMusicSpeaker, CgSpinner } from 'react-icons/cg' -import { Footer } from '~/components/Footer' -import SponsorPack from '~/components/SponsorPack' -import { LogoColor } from '~/components/LogoColor' -import { getSponsorsForSponsorPack } from '~/server/sponsors' -import discordImage from '~/images/discord-logo-white.svg' -import agGridImage from '~/images/ag-grid.png' -import nozzleImage from '~/images/nozzle.png' -import bytesImage from '~/images/bytes.svg' -import bytesUidotdevImage from '~/images/bytes-uidotdev.png' -import { useMutation } from '~/hooks/useMutation' -import { sample } from '~/utils/utils' -import { textColors } from 'random-number.tsx' -import { gradients } from 'random-number.tsx' -const courses = [ - { - name: 'The Official TanStack React Query Course', - cardStyles: `border-t-4 border-red-500 hover:(border-green-500)`, - href: 'https://query.gg/?s=tanstack', - description: `Learn how to build enterprise quality apps with TanStack's React Query the easy way with our brand new course.`, - }, -] -import { Route } from 'random-number.tsx' -async function bytesSignupServerFn({ email }: { email: string }) { - 'use server' +import { Await, Link, defer } from '@tanstack/react-router'; +import { Carbon } from '~/components/Carbon'; +import { twMerge } from 'tailwind-merge'; +import { FaDiscord, FaGithub, FaTshirt } from 'react-icons/fa'; +import { CgMusicSpeaker, CgSpinner } from 'react-icons/cg'; +import { Footer } from '~/components/Footer'; +import SponsorPack from '~/components/SponsorPack'; +import { LogoColor } from '~/components/LogoColor'; +import { getSponsorsForSponsorPack } from '~/server/sponsors'; +import discordImage from '~/images/discord-logo-white.svg'; +import agGridImage from '~/images/ag-grid.png'; +import nozzleImage from '~/images/nozzle.png'; +import bytesImage from '~/images/bytes.svg'; +import bytesUidotdevImage from '~/images/bytes-uidotdev.png'; +import { useMutation } from '~/hooks/useMutation'; +import { sample } from '~/utils/utils'; +import { textColors } from "random-number.tsx"; +import { gradients } from "random-number.tsx"; +const courses = [{ + name: 'The Official TanStack React Query Course', + cardStyles: `border-t-4 border-red-500 hover:(border-green-500)`, + href: 'https://query.gg/?s=tanstack', + description: `Learn how to build enterprise quality apps with TanStack's React Query the easy way with our brand new course.` +}]; +import { Route } from "random-number.tsx"; +async function bytesSignupServerFn({ + email +}: { + email: string; +}) { + 'use server'; + return fetch(`https://bytes.dev/api/bytes-optin-cors`, { method: 'POST', - body: JSON.stringify({ email, influencer: 'tanstack' }), - headers: { Accept: 'application/json', 'Content-Type': 'application/json' }, - }) + body: JSON.stringify({ + email, + influencer: 'tanstack' + }), + headers: { + Accept: 'application/json', + 'Content-Type': 'application/json' + } + }); } function Index() { - const bytesSignupMutation = useMutation({ fn: bytesSignupServerFn }) - const { sponsorsPromise, randomNumber, testing2 } = Route.useLoaderData() - const gradient = sample(gradients, randomNumber) - const textColor = sample(textColors, randomNumber) - return ( - <> + const bytesSignupMutation = useMutation({ + fn: bytesSignupServerFn + }); + const { + sponsorsPromise, + randomNumber, + testing2 + } = Route.useLoaderData(); + const gradient = sample(gradients, randomNumber); + const textColor = sample(textColors, randomNumber); + return <> {discordImage} {gradient} {textColor} - </> - ) + </>; } const SplitLoader = () => { return { randomNumber: Math.random(), - sponsorsPromise: defer(getSponsorsForSponsorPack()), - } -} -export { SplitLoader as loader } -export { Index as component } + sponsorsPromise: defer(getSponsorsForSponsorPack()) + }; +}; +export { SplitLoader as loader }; +export { Index as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/random-number@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/random-number@errorComponent.tsx index 8e156eca17..cdf4d37891 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/random-number@errorComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/random-number@errorComponent.tsx @@ -1,20 +1,18 @@ -import { Await, Link } from '@tanstack/react-router' -import { Carbon } from '~/components/Carbon' -import { twMerge } from 'tailwind-merge' -import { FaDiscord, FaGithub, FaTshirt } from 'react-icons/fa' -import { CgMusicSpeaker, CgSpinner } from 'react-icons/cg' -import { Footer } from '~/components/Footer' -import SponsorPack from '~/components/SponsorPack' -import { LogoColor } from '~/components/LogoColor' -import agGridImage from '~/images/ag-grid.png' -import nozzleImage from '~/images/nozzle.png' -import bytesImage from '~/images/bytes.svg' -import bytesUidotdevImage from '~/images/bytes-uidotdev.png' -const courses = [ - { - name: 'The Official TanStack React Query Course', - cardStyles: `border-t-4 border-red-500 hover:(border-green-500)`, - href: 'https://query.gg/?s=tanstack', - description: `Learn how to build enterprise quality apps with TanStack's React Query the easy way with our brand new course.`, - }, -] +import { Await, Link } from '@tanstack/react-router'; +import { Carbon } from '~/components/Carbon'; +import { twMerge } from 'tailwind-merge'; +import { FaDiscord, FaGithub, FaTshirt } from 'react-icons/fa'; +import { CgMusicSpeaker, CgSpinner } from 'react-icons/cg'; +import { Footer } from '~/components/Footer'; +import SponsorPack from '~/components/SponsorPack'; +import { LogoColor } from '~/components/LogoColor'; +import agGridImage from '~/images/ag-grid.png'; +import nozzleImage from '~/images/nozzle.png'; +import bytesImage from '~/images/bytes.svg'; +import bytesUidotdevImage from '~/images/bytes-uidotdev.png'; +const courses = [{ + name: 'The Official TanStack React Query Course', + cardStyles: `border-t-4 border-red-500 hover:(border-green-500)`, + href: 'https://query.gg/?s=tanstack', + description: `Learn how to build enterprise quality apps with TanStack's React Query the easy way with our brand new course.` +}]; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/react-memo-component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/react-memo-component.tsx index 9f605effce..568c8dc323 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/react-memo-component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/react-memo-component.tsx @@ -1,11 +1,9 @@ -const $$splitLoaderImporter = () => - import('react-memo-component.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyFn } from '@tanstack/react-router' -const $$splitComponentImporter = () => - import('react-memo-component.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitLoaderImporter = () => import('react-memo-component.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyFn } from '@tanstack/react-router'; +const $$splitComponentImporter = () => import('react-memo-component.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/')({ component: lazyRouteComponent($$splitComponentImporter, 'component'), - loader: lazyFn($$splitLoaderImporter, 'loader'), -}) + loader: lazyFn($$splitLoaderImporter, 'loader') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/react-memo-component@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/react-memo-component@component---loader---notFoundComponent---pendingComponent.tsx index 7c2c8e17de..70d8b0eb42 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/react-memo-component@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/react-memo-component@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,9 +1,9 @@ -import React from 'react' -import { importedLoader } from '../../shared/imported' +import React from 'react'; +import { importedLoader } from '../../shared/imported'; function Component() { - return <div>Component</div> + return <div>Component</div>; } -const SplitLoader = importedLoader -export { SplitLoader as loader } -const SplitComponent = React.memo(Component) -export { SplitComponent as component } +const SplitLoader = importedLoader; +export { SplitLoader as loader }; +const SplitComponent = React.memo(Component); +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/react-memo-imported-component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/react-memo-imported-component.tsx index 7e9467be1b..233eca72a0 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/react-memo-imported-component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/react-memo-imported-component.tsx @@ -1,11 +1,9 @@ -const $$splitLoaderImporter = () => - import('react-memo-imported-component.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyFn } from '@tanstack/react-router' -const $$splitComponentImporter = () => - import('react-memo-imported-component.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitLoaderImporter = () => import('react-memo-imported-component.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyFn } from '@tanstack/react-router'; +const $$splitComponentImporter = () => import('react-memo-imported-component.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/')({ component: lazyRouteComponent($$splitComponentImporter, 'component'), - loader: lazyFn($$splitLoaderImporter, 'loader'), -}) + loader: lazyFn($$splitLoaderImporter, 'loader') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/react-memo-imported-component@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/react-memo-imported-component@component---loader---notFoundComponent---pendingComponent.tsx index 83e6e4b28c..d2671013ef 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/react-memo-imported-component@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/react-memo-imported-component@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,6 +1,6 @@ -import React from 'react' -import { importedLoader, importedComponent } from '../../shared/imported' -const SplitLoader = importedLoader -export { SplitLoader as loader } -const SplitComponent = React.memo(importedComponent) -export { SplitComponent as component } +import React from 'react'; +import { importedLoader, importedComponent } from '../../shared/imported'; +const SplitLoader = importedLoader; +export { SplitLoader as loader }; +const SplitComponent = React.memo(importedComponent); +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-export-component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-export-component.tsx index 4f14db0832..1b00751ae6 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-export-component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-export-component.tsx @@ -1,16 +1,14 @@ -console.warn( - '[tanstack-router] These exports from "retain-export-component.tsx" will not be code-split and will increase your bundle size:\n- Layout\nFor the best optimization, these items should either have their export statements removed, or be imported from another location that is not a route file.', -) -const $$splitLoaderImporter = () => - import('retain-export-component.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyFn } from '@tanstack/react-router' -import * as React from 'react' -import { createFileRoute, Outlet } from '@tanstack/react-router' -import { importedComponent as ImportedComponent } from '../../shared/imported' +console.warn("[tanstack-router] These exports from \"retain-export-component.tsx\" will not be code-split and will increase your bundle size:\n- Layout\nFor the best optimization, these items should either have their export statements removed, or be imported from another location that is not a route file."); +const $$splitLoaderImporter = () => import('retain-export-component.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyFn } from '@tanstack/react-router'; +import * as React from 'react'; +import { createFileRoute, Outlet } from '@tanstack/react-router'; +import { importedComponent as ImportedComponent } from '../../shared/imported'; export function Layout() { - return ( - <main> - <header style={{ height: HEADER_HEIGHT }}> + return <main> + <header style={{ + height: HEADER_HEIGHT + }}> <nav> <ul> <li> @@ -21,14 +19,13 @@ export function Layout() { </header> <ImportedComponent /> <Outlet /> - </main> - ) + </main>; } export const Route = createFileRoute('/_layout')({ component: Layout, - loader: lazyFn($$splitLoaderImporter, 'loader'), -}) -const HEADER_HEIGHT = '63px' -export const SIDEBAR_WIDTH = '150px' -const SIDEBAR_MINI_WIDTH = '80px' -const ASIDE_WIDTH = '250px' + loader: lazyFn($$splitLoaderImporter, 'loader') +}); +const HEADER_HEIGHT = '63px'; +export const SIDEBAR_WIDTH = '150px'; +const SIDEBAR_MINI_WIDTH = '80px'; +const ASIDE_WIDTH = '250px'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-export-component@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-export-component@component---loader---notFoundComponent---pendingComponent.tsx index ddeb4d1e6f..9787e27ad7 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-export-component@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-export-component@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,6 +1,6 @@ -import * as React from 'react' -import { importedLoader } from '../../shared/imported' -const SIDEBAR_MINI_WIDTH = '80px' -const ASIDE_WIDTH = '250px' -const SplitLoader = importedLoader -export { SplitLoader as loader } +import * as React from 'react'; +import { importedLoader } from '../../shared/imported'; +const SIDEBAR_MINI_WIDTH = '80px'; +const ASIDE_WIDTH = '250px'; +const SplitLoader = importedLoader; +export { SplitLoader as loader }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-export-component@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-export-component@errorComponent.tsx index 8fb12f0c6b..5bb0ab5451 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-export-component@errorComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-export-component@errorComponent.tsx @@ -1,3 +1,3 @@ -import * as React from 'react' -const SIDEBAR_MINI_WIDTH = '80px' -const ASIDE_WIDTH = '250px' +import * as React from 'react'; +const SIDEBAR_MINI_WIDTH = '80px'; +const ASIDE_WIDTH = '250px'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-const.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-const.tsx index d674dbb799..f256b01a83 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-const.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-const.tsx @@ -4,9 +4,11 @@ import { importedComponent as ImportedComponent, importedLoader, } from '../../shared/imported' + export const loaderFn = () => { return importedLoader() } + const Layout = () => { return ( <main> @@ -24,12 +26,15 @@ const Layout = () => { </main> ) } + export const Route = createFileRoute('/_layout')({ component: Layout, loader: loaderFn, }) + const HEADER_HEIGHT = '63px' export const SIDEBAR_WIDTH = '150px' export const SIDEBAR_MINI_WIDTH = '80px' const ASIDE_WIDTH = '250px' + export default Layout diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-const@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-const@component---loader---notFoundComponent---pendingComponent.tsx index 0e0123f1ab..168ba78680 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-const@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-const@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,2 +1,2 @@ -import * as React from 'react' -const ASIDE_WIDTH = '250px' +import * as React from 'react'; +const ASIDE_WIDTH = '250px'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-const@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-const@errorComponent.tsx index 0e0123f1ab..168ba78680 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-const@errorComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-const@errorComponent.tsx @@ -1,2 +1,2 @@ -import * as React from 'react' -const ASIDE_WIDTH = '250px' +import * as React from 'react'; +const ASIDE_WIDTH = '250px'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-destructured.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-destructured.tsx index 89c23305a0..0e3175116f 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-destructured.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-destructured.tsx @@ -1,12 +1,18 @@ import { createFileRoute } from '@tanstack/react-router' + const createBits = () => ({ component: AboutComponentImpl, - loader: () => ({ message: 'hello' }), + loader: () => ({ + message: 'hello', + }), }) + export const { component: AboutComponent, loader } = createBits() + function AboutComponentImpl() { return <div>About</div> } + export const Route = createFileRoute('/about')({ component: AboutComponent, loader, diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-destructured@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-destructured@component---loader---notFoundComponent---pendingComponent.tsx index c3ddde13a8..43108700f5 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-destructured@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-destructured@component---loader---notFoundComponent---pendingComponent.tsx @@ -1 +1 @@ -export { SplitLoader as loader } +export { SplitLoader as loader }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-function.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-function.tsx index 83b3dd4eb5..298c388e65 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-function.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-function.tsx @@ -4,9 +4,11 @@ import { importedComponent as ImportedComponent, importedLoader, } from '../../shared/imported' + export function loaderFn() { return importedLoader() } + function Layout() { return ( <main> @@ -24,12 +26,15 @@ function Layout() { </main> ) } + export const Route = createFileRoute('/_layout')({ component: Layout, loader: loaderFn, }) + const HEADER_HEIGHT = '63px' export const SIDEBAR_WIDTH = '150px' export const SIDEBAR_MINI_WIDTH = '80px' const ASIDE_WIDTH = '250px' + export default Layout diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-function@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-function@component---loader---notFoundComponent---pendingComponent.tsx index 0e0123f1ab..168ba78680 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-function@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-function@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,2 +1,2 @@ -import * as React from 'react' -const ASIDE_WIDTH = '250px' +import * as React from 'react'; +const ASIDE_WIDTH = '250px'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-function@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-function@errorComponent.tsx index 0e0123f1ab..168ba78680 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-function@errorComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-function@errorComponent.tsx @@ -1,2 +1,2 @@ -import * as React from 'react' -const ASIDE_WIDTH = '250px' +import * as React from 'react'; +const ASIDE_WIDTH = '250px'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-loader.tsx index e805842e0c..b36cbc6be2 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-loader.tsx @@ -1,18 +1,17 @@ -console.warn( - '[tanstack-router] These exports from "retain-exports-loader.tsx" will not be code-split and will increase your bundle size:\n- loaderFn\nFor the best optimization, these items should either have their export statements removed, or be imported from another location that is not a route file.', -) -const $$splitComponentImporter = () => - import('retain-exports-loader.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -import * as React from 'react' -import { createFileRoute } from '@tanstack/react-router' +console.warn("[tanstack-router] These exports from \"retain-exports-loader.tsx\" will not be code-split and will increase your bundle size:\n- loaderFn\nFor the best optimization, these items should either have their export statements removed, or be imported from another location that is not a route file."); +const $$splitComponentImporter = () => import('retain-exports-loader.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +import * as React from 'react'; +import { createFileRoute } from '@tanstack/react-router'; export function loaderFn() { - return { foo: 'bar' } + return { + foo: 'bar' + }; } export const Route = createFileRoute('/_layout')({ component: lazyRouteComponent($$splitComponentImporter, 'component'), - loader: loaderFn, -}) -export const SIDEBAR_WIDTH = '150px' -export const SIDEBAR_MINI_WIDTH = '80px' -const ASIDE_WIDTH = '250px' + loader: loaderFn +}); +export const SIDEBAR_WIDTH = '150px'; +export const SIDEBAR_MINI_WIDTH = '80px'; +const ASIDE_WIDTH = '250px'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-loader@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-loader@component---loader---notFoundComponent---pendingComponent.tsx index 604be4dc69..9f54ae0dc5 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-loader@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-loader@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,10 +1,11 @@ -import * as React from 'react' -import { Outlet } from '@tanstack/react-router' -import { importedComponent as ImportedComponent } from '../../shared/imported' +import * as React from 'react'; +import { Outlet } from '@tanstack/react-router'; +import { importedComponent as ImportedComponent } from '../../shared/imported'; function Layout() { - return ( - <main> - <header style={{ height: HEADER_HEIGHT }}> + return <main> + <header style={{ + height: HEADER_HEIGHT + }}> <nav> <ul> <li> @@ -15,9 +16,8 @@ function Layout() { </header> <ImportedComponent /> <Outlet /> - </main> - ) + </main>; } -const HEADER_HEIGHT = '63px' -const ASIDE_WIDTH = '250px' -export { Layout as component } +const HEADER_HEIGHT = '63px'; +const ASIDE_WIDTH = '250px'; +export { Layout as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-loader@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-loader@errorComponent.tsx index 0e0123f1ab..168ba78680 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-loader@errorComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/retain-exports-loader@errorComponent.tsx @@ -1,2 +1,2 @@ -import * as React from 'react' -const ASIDE_WIDTH = '250px' +import * as React from 'react'; +const ASIDE_WIDTH = '250px'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-class.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-class.tsx index c9bffc92ba..48afc3f070 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-class.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-class.tsx @@ -1,20 +1,18 @@ -const $$splitComponentImporter = () => - import('shared-class.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -const $$splitLoaderImporter = () => - import('shared-class.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyFn } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('shared-class.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +const $$splitLoaderImporter = () => import('shared-class.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyFn } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; class DataStore { - data = new Map() + data = new Map(); get(k: string) { - return this.data.get(k) + return this.data.get(k); } set(k: string, v: unknown) { - this.data.set(k, v) + this.data.set(k, v); } } export const Route = createFileRoute('/store')({ loader: lazyFn($$splitLoaderImporter, 'loader'), - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-class@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-class@component---loader---notFoundComponent---pendingComponent.tsx index 39593e61e0..10675b99ed 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-class@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-class@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,16 +1,16 @@ class DataStore { - data = new Map() + data = new Map(); get(k: string) { - return this.data.get(k) + return this.data.get(k); } set(k: string, v: unknown) { - this.data.set(k, v) + this.data.set(k, v); } } -const store = new DataStore() +const store = new DataStore(); const SplitLoader = async () => { - store.set('items', await fetch('/api')) -} -export { SplitLoader as loader } -const SplitComponent = () => <div>{store.get('items')}</div> -export { SplitComponent as component } + store.set('items', await fetch('/api')); +}; +export { SplitLoader as loader }; +const SplitComponent = () => <div>{store.get('items')}</div>; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-class@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-class@errorComponent.tsx index 31a1763b5d..0a50638c6a 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-class@errorComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-class@errorComponent.tsx @@ -1,9 +1,9 @@ class DataStore { - data = new Map() + data = new Map(); get(k: string) { - return this.data.get(k) + return this.data.get(k); } set(k: string, v: unknown) { - this.data.set(k, v) + this.data.set(k, v); } -} +} \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-destructured-export.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-destructured-export.tsx index 6b770a1cf2..73f1b54389 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-destructured-export.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-destructured-export.tsx @@ -1,15 +1,19 @@ -const $$splitComponentImporter = () => - import('shared-destructured-export.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -const $$splitLoaderImporter = () => - import('shared-destructured-export.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyFn } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' -export const { apiUrl, timeout } = getConfig() +const $$splitComponentImporter = () => import('shared-destructured-export.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +const $$splitLoaderImporter = () => import('shared-destructured-export.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyFn } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; +export const { + apiUrl, + timeout +} = getConfig(); export const Route = createFileRoute('/config')({ loader: lazyFn($$splitLoaderImporter, 'loader'), - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); function getConfig() { - return { apiUrl: '/api', timeout: 5000 } -} + return { + apiUrl: '/api', + timeout: 5000 + }; +} \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-destructured-export@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-destructured-export@component---loader---notFoundComponent---pendingComponent.tsx index 68114df748..d48accf910 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-destructured-export@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-destructured-export@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,5 +1,5 @@ -import { apiUrl, timeout } from 'shared-destructured-export.tsx' -const SplitLoader = async () => fetch(apiUrl) -export { SplitLoader as loader } -const SplitComponent = () => <div>Timeout: {timeout}</div> -export { SplitComponent as component } +import { apiUrl, timeout } from "shared-destructured-export.tsx"; +const SplitLoader = async () => fetch(apiUrl); +export { SplitLoader as loader }; +const SplitComponent = () => <div>Timeout: {timeout}</div>; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-destructured.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-destructured.tsx index 78bf0b8ceb..fbc4272c3e 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-destructured.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-destructured.tsx @@ -1,11 +1,9 @@ -const $$splitComponentImporter = () => - import('shared-destructured.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -const $$splitLoaderImporter = () => - import('shared-destructured.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyFn } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('shared-destructured.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +const $$splitLoaderImporter = () => import('shared-destructured.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyFn } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/config')({ loader: lazyFn($$splitLoaderImporter, 'loader'), - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-destructured@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-destructured@component---loader---notFoundComponent---pendingComponent.tsx index a5c9439324..e92f7dd7f8 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-destructured@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-destructured@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,8 +1,14 @@ -const { apiUrl, timeout } = getConfig() +const { + apiUrl, + timeout +} = getConfig(); function getConfig() { - return { apiUrl: '/api', timeout: 5000 } + return { + apiUrl: '/api', + timeout: 5000 + }; } -const SplitLoader = async () => fetch(apiUrl) -export { SplitLoader as loader } -const SplitComponent = () => <div>Timeout: {timeout}</div> -export { SplitComponent as component } +const SplitLoader = async () => fetch(apiUrl); +export { SplitLoader as loader }; +const SplitComponent = () => <div>Timeout: {timeout}</div>; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-exported.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-exported.tsx index 887f52978d..76a5d29dc3 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-exported.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-exported.tsx @@ -1,12 +1,13 @@ -const $$splitComponentImporter = () => - import('shared-exported.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -const $$splitLoaderImporter = () => - import('shared-exported.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyFn } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' -export const queryOptions = { staleTime: 5000, gcTime: 10000 } +const $$splitComponentImporter = () => import('shared-exported.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +const $$splitLoaderImporter = () => import('shared-exported.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyFn } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; +export const queryOptions = { + staleTime: 5000, + gcTime: 10000 +}; export const Route = createFileRoute('/query')({ loader: lazyFn($$splitLoaderImporter, 'loader'), - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-exported@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-exported@component---loader---notFoundComponent---pendingComponent.tsx index f2a32be2bc..f77f81cbdb 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-exported@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-exported@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,7 +1,9 @@ -import { queryOptions } from 'shared-exported.tsx' +import { queryOptions } from "shared-exported.tsx"; const SplitLoader = async () => { - return { staleTime: queryOptions.staleTime } -} -export { SplitLoader as loader } -const SplitComponent = () => <div>GC: {queryOptions.gcTime}</div> -export { SplitComponent as component } + return { + staleTime: queryOptions.staleTime + }; +}; +export { SplitLoader as loader }; +const SplitComponent = () => <div>GC: {queryOptions.gcTime}</div>; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-function.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-function.tsx index b964d09962..8a921d9640 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-function.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-function.tsx @@ -1,11 +1,9 @@ -const $$splitComponentImporter = () => - import('shared-function.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -const $$splitLoaderImporter = () => - import('shared-function.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyFn } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('shared-function.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +const $$splitLoaderImporter = () => import('shared-function.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyFn } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/cached')({ loader: lazyFn($$splitLoaderImporter, 'loader'), - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-function@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-function@component---loader---notFoundComponent---pendingComponent.tsx index 0f4a23b3fe..cfe519f47a 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-function@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-function@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,14 +1,14 @@ -const cache = new Map() +const cache = new Map(); function getCached(key: string) { - return cache.get(key) + return cache.get(key); } function setCached(key: string, val: unknown) { - cache.set(key, val) + cache.set(key, val); } const SplitLoader = async () => { - setCached('data', await fetch('/api').then((r) => r.json())) - return getCached('data') -} -export { SplitLoader as loader } -const SplitComponent = () => <div>{JSON.stringify(getCached('data'))}</div> -export { SplitComponent as component } + setCached('data', await fetch('/api').then(r => r.json())); + return getCached('data'); +}; +export { SplitLoader as loader }; +const SplitComponent = () => <div>{JSON.stringify(getCached('data'))}</div>; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-imported-binding.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-imported-binding.tsx index 71082ac702..feb46cd789 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-imported-binding.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-imported-binding.tsx @@ -1,11 +1,9 @@ -const $$splitComponentImporter = () => - import('shared-imported-binding.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -const $$splitLoaderImporter = () => - import('shared-imported-binding.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyFn } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('shared-imported-binding.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +const $$splitLoaderImporter = () => import('shared-imported-binding.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyFn } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/imported')({ loader: lazyFn($$splitLoaderImporter, 'loader'), - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-imported-binding@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-imported-binding@component---loader---notFoundComponent---pendingComponent.tsx index 7718cec94c..409e8d4023 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-imported-binding@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-imported-binding@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,5 +1,5 @@ -import { sharedUtil } from '../utils' -const SplitLoader = async () => sharedUtil('load') -export { SplitLoader as loader } -const SplitComponent = () => <div>{sharedUtil('render')}</div> -export { SplitComponent as component } +import { sharedUtil } from '../utils'; +const SplitLoader = async () => sharedUtil('load'); +export { SplitLoader as loader }; +const SplitComponent = () => <div>{sharedUtil('render')}</div>; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-indirect-ref.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-indirect-ref.tsx index 913fae8432..4275e17e58 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-indirect-ref.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-indirect-ref.tsx @@ -1,11 +1,9 @@ -const $$splitComponentImporter = () => - import('shared-indirect-ref.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -const $$splitLoaderImporter = () => - import('shared-indirect-ref.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyFn } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('shared-indirect-ref.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +const $$splitLoaderImporter = () => import('shared-indirect-ref.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyFn } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/shared-indirect')({ loader: lazyFn($$splitLoaderImporter, 'loader'), - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-indirect-ref@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-indirect-ref@component---loader---notFoundComponent---pendingComponent.tsx index 90815572f7..090f3b5c73 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-indirect-ref@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-indirect-ref@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,17 +1,19 @@ -const state = { count: 0 } +const state = { + count: 0 +}; function getCount() { - return state.count + return state.count; } function SharedComponent() { - return ( - <div> + return <div> {getCount()} - {state.count} - </div> - ) + </div>; } const SplitLoader = () => { - state.count++ - return { count: getCount() } -} -export { SplitLoader as loader } -export { SharedComponent as component } + state.count++; + return { + count: getCount() + }; +}; +export { SplitLoader as loader }; +export { SharedComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-jsx-component-ref.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-jsx-component-ref.tsx index 7d5cff0d5f..130c7ce120 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-jsx-component-ref.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-jsx-component-ref.tsx @@ -1,12 +1,10 @@ -const $$splitComponentImporter = () => - import('shared-jsx-component-ref.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -const $$splitLoaderImporter = () => - import('shared-jsx-component-ref.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyFn } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('shared-jsx-component-ref.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +const $$splitLoaderImporter = () => import('shared-jsx-component-ref.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyFn } from '@tanstack/react-router'; // @ts-nocheck -import { createFileRoute } from '@tanstack/react-router' +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/jsx')({ loader: lazyFn($$splitLoaderImporter, 'loader'), - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-jsx-component-ref@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-jsx-component-ref@component---loader---notFoundComponent---pendingComponent.tsx index 82b634246f..c5fd18664e 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-jsx-component-ref@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-jsx-component-ref@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,8 +1,9 @@ // @ts-nocheck -const shared = 1 + +const shared = 1; function SharedComponent() { - return <div>{shared}</div> + return <div>{shared}</div>; } -const SplitLoader = () => shared -export { SplitLoader as loader } -export { SharedComponent as component } +const SplitLoader = () => shared; +export { SplitLoader as loader }; +export { SharedComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-none.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-none.tsx index 1dd8f7bb0a..eac0f9ab0a 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-none.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-none.tsx @@ -1,11 +1,9 @@ -const $$splitComponentImporter = () => - import('shared-none.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -const $$splitLoaderImporter = () => - import('shared-none.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyFn } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('shared-none.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +const $$splitLoaderImporter = () => import('shared-none.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyFn } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/clean')({ loader: lazyFn($$splitLoaderImporter, 'loader'), - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-none@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-none@component---loader---notFoundComponent---pendingComponent.tsx index 9f1d1a5ca1..f9f52ba6be 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-none@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-none@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,10 +1,8 @@ -const loaderHelper = () => fetch('/api') -const ComponentHelper = () => <span>helper</span> -const SplitLoader = async () => loaderHelper() -export { SplitLoader as loader } -const SplitComponent = () => ( - <div> - <ComponentHelper /> - </div> -) -export { SplitComponent as component } +const loaderHelper = () => fetch('/api'); +const ComponentHelper = () => <span>helper</span>; +const SplitLoader = async () => loaderHelper(); +export { SplitLoader as loader }; +const SplitComponent = () => <div> + <ComponentHelper /> + </div>; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-referencing-route.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-referencing-route.tsx index f51ed0c13a..9aebb45a95 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-referencing-route.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-referencing-route.tsx @@ -1,11 +1,9 @@ -const $$splitComponentImporter = () => - import('shared-referencing-route.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -const $$splitLoaderImporter = () => - import('shared-referencing-route.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyFn } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('shared-referencing-route.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +const $$splitLoaderImporter = () => import('shared-referencing-route.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyFn } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/about')({ loader: lazyFn($$splitLoaderImporter, 'loader'), - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-referencing-route@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-referencing-route@component---loader---notFoundComponent---pendingComponent.tsx index da98398ae1..9bcd130ea8 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-referencing-route@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-referencing-route@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,15 +1,17 @@ -const HEADER = 'Page' +const HEADER = 'Page'; function usePageTitle() { - return `${HEADER} - ${Route.fullPath}` + return `${HEADER} - ${Route.fullPath}`; } -import { Route } from 'shared-referencing-route.tsx' +import { Route } from "shared-referencing-route.tsx"; const SplitLoader = async () => { - const title = usePageTitle() - return { title } -} -export { SplitLoader as loader } + const title = usePageTitle(); + return { + title + }; +}; +export { SplitLoader as loader }; const SplitComponent = () => { - const title = usePageTitle() - return <div>{title}</div> -} -export { SplitComponent as component } + const title = usePageTitle(); + return <div>{title}</div>; +}; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-runtime.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-runtime.tsx deleted file mode 100644 index fdc18fa37b..0000000000 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-runtime.tsx +++ /dev/null @@ -1,20 +0,0 @@ -import { state, createState, createSeed } from 'shared-runtime.tsx?tsr-shared=1' -const $$splitComponentImporter = () => - import('shared-runtime.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -const $$splitLoaderImporter = () => - import('shared-runtime.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyFn } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' -console.log('shared-runtime:reference') -export const Route = createFileRoute('/shared-runtime')({ - beforeLoad: () => state, - loader: lazyFn($$splitLoaderImporter, 'loader'), - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) -function createState(initialState: { count: number }): { - state: { count: number } - increment: () => number -} -export { state as firstState, state as secondState, state as 'odd-name' } -export default createSeed diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-runtime@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-runtime@component---loader---notFoundComponent---pendingComponent.tsx deleted file mode 100644 index 053cf24d5a..0000000000 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-runtime@component---loader---notFoundComponent---pendingComponent.tsx +++ /dev/null @@ -1,30 +0,0 @@ -import { - state, - createState, - createSeed, - Labels, - increment, -} from 'shared-runtime.tsx?tsr-shared=1' -const label = createComponentLabel() -function createState(initialState: { count: number }): { - state: { count: number } - increment: () => number -} -function createComponentLabel() { - console.log('shared-runtime:component') - return Labels.component -} -export { state as firstState, state as secondState, state as 'odd-name' } -export default createSeed -const SplitLoader = () => { - increment() - return state -} -export { SplitLoader as loader } -const SplitComponent = () => { - if (state.count === 3) { - throw new Error('route source-map contract') - } - return `${label}:${state.count}` -} -export { SplitComponent as component } diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-runtime@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-runtime@errorComponent.tsx deleted file mode 100644 index 03cacac5b3..0000000000 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-runtime@errorComponent.tsx +++ /dev/null @@ -1,7 +0,0 @@ -import { state, createState, createSeed } from 'shared-runtime.tsx?tsr-shared=1' -function createState(initialState: { count: number }): { - state: { count: number } - increment: () => number -} -export { state as firstState, state as secondState, state as 'odd-name' } -export default createSeed diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-runtime@shared.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-runtime@shared.tsx deleted file mode 100644 index c53a7e1568..0000000000 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-runtime@shared.tsx +++ /dev/null @@ -1,13 +0,0 @@ -const Count = { Initial: 0 } -const Labels = { component: 'count' } -const seed = createSeed() -const { state, increment } = createState(seed) -function createSeed() { - console.log('shared-runtime:seed') - return { count: Count.Initial, label: Labels.component } -} -function createState(initialState: { count: number }) { - console.log('shared-runtime:state') - return { state: initialState, increment: () => initialState.count++ } -} -export { Count, createSeed, createState, increment, Labels, seed, state } diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-transitive.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-transitive.tsx index 552cd657e0..67b0631b8e 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-transitive.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-transitive.tsx @@ -1,11 +1,9 @@ -const $$splitComponentImporter = () => - import('shared-transitive.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -const $$splitLoaderImporter = () => - import('shared-transitive.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyFn } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('shared-transitive.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +const $$splitLoaderImporter = () => import('shared-transitive.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyFn } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/api')({ loader: lazyFn($$splitLoaderImporter, 'loader'), - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-transitive@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-transitive@component---loader---notFoundComponent---pendingComponent.tsx index c67ed3c691..662d7fd7aa 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-transitive@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-transitive@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,9 +1,12 @@ -const BASE_URL = 'https://api.example.com' -const config = { url: BASE_URL, timeout: 5000 } -const fetcher = (path: string) => fetch(`${config.url}${path}`) +const BASE_URL = 'https://api.example.com'; +const config = { + url: BASE_URL, + timeout: 5000 +}; +const fetcher = (path: string) => fetch(`${config.url}${path}`); const SplitLoader = async () => { - return fetcher('/data') -} -export { SplitLoader as loader } -const SplitComponent = () => <div>Timeout: {config.timeout}</div> -export { SplitComponent as component } + return fetcher('/data'); +}; +export { SplitLoader as loader }; +const SplitComponent = () => <div>Timeout: {config.timeout}</div>; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-variable.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-variable.tsx index 191b12aa33..48cdad100e 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-variable.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-variable.tsx @@ -1,11 +1,9 @@ -const $$splitComponentImporter = () => - import('shared-variable.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -const $$splitLoaderImporter = () => - import('shared-variable.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyFn } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' +const $$splitComponentImporter = () => import('shared-variable.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +const $$splitLoaderImporter = () => import('shared-variable.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyFn } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/todos')({ loader: lazyFn($$splitLoaderImporter, 'loader'), - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-variable@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-variable@component---loader---notFoundComponent---pendingComponent.tsx index e96ced1955..daca782a6f 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-variable@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-variable@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,8 +1,13 @@ -const collection = { name: 'todos', preload: async () => {} } +const collection = { + name: 'todos', + preload: async () => {} +}; const SplitLoader = async () => { - await collection.preload() - return { data: 'loaded' } -} -export { SplitLoader as loader } -const SplitComponent = () => <div>{collection.name}</div> -export { SplitComponent as component } + await collection.preload(); + return { + data: 'loaded' + }; +}; +export { SplitLoader as loader }; +const SplitComponent = () => <div>{collection.name}</div>; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-with-side-effect.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-with-side-effect.tsx index 5f68cb275d..c322746737 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-with-side-effect.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-with-side-effect.tsx @@ -1,12 +1,10 @@ -const $$splitComponentImporter = () => - import('shared-with-side-effect.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/react-router' -const $$splitLoaderImporter = () => - import('shared-with-side-effect.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyFn } from '@tanstack/react-router' -import { createFileRoute } from '@tanstack/react-router' -console.log('registry created') +const $$splitComponentImporter = () => import('shared-with-side-effect.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/react-router'; +const $$splitLoaderImporter = () => import('shared-with-side-effect.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyFn } from '@tanstack/react-router'; +import { createFileRoute } from '@tanstack/react-router'; +console.log('registry created'); export const Route = createFileRoute('/fx')({ loader: lazyFn($$splitLoaderImporter, 'loader'), - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-with-side-effect@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-with-side-effect@component---loader---notFoundComponent---pendingComponent.tsx index 542779a26b..6c77f8b857 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-with-side-effect@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/shared-with-side-effect@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,7 +1,7 @@ -const registry = new Map() +const registry = new Map(); const SplitLoader = async () => { - registry.set('loaded', true) -} -export { SplitLoader as loader } -const SplitComponent = () => <div>{registry.size}</div> -export { SplitComponent as component } + registry.set('loaded', true); +}; +export { SplitLoader as loader }; +const SplitComponent = () => <div>{registry.size}</div>; +export { SplitComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/undefined-literals.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/undefined-literals.tsx index 88b0bf1ba8..0c6e4f01aa 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/undefined-literals.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/undefined-literals.tsx @@ -1,4 +1,5 @@ import { createFileRoute } from '@tanstack/react-router' + export const Route = createFileRoute('/undefined-test')({ component: undefined, errorComponent: undefined, diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/useStateDestructure.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/useStateDestructure.tsx index b5b3ecade6..d0de09bf8b 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/useStateDestructure.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/useStateDestructure.tsx @@ -1,4 +1,5 @@ import * as React from 'react' + import { CgCornerUpLeft, CgSpinner } from 'react-icons/cg' import { FaBolt, @@ -20,6 +21,7 @@ import { startProject } from '~/projects/start' import { createFileRoute } from '@tanstack/react-router' import { Framework, getBranch } from '~/projects' import { seo } from '~/utils/seo' + const menu = [ { label: ( @@ -70,22 +72,31 @@ const menu = [ to: `https://cottonbureau.com/people/tanstack`, }, ] + export const Route = createFileRoute('/_libraries/start/$version/')({ component: VersionIndex, meta: () => - seo({ title: startProject.name, description: startProject.description }), + seo({ + title: startProject.name, + description: startProject.description, + }), }) + const librariesRouteApi = getRouteApi('/_libraries') + export default function VersionIndex() { const { sponsorsPromise } = librariesRouteApi.useLoaderData() const { version } = Route.useParams() const branch = getBranch(startProject, version) const [framework, setFramework] = React.useState<Framework>('react') const [isDark, setIsDark] = React.useState(true) + React.useEffect(() => { setIsDark(window.matchMedia?.(`(prefers-color-scheme: dark)`).matches) }, []) + const gradientText = `inline-block text-transparent bg-clip-text bg-gradient-to-r ${startProject.colorFrom} ${startProject.colorTo}` + return ( <div className="flex flex-col gap-20 md:gap-32 max-w-full"> <div @@ -96,6 +107,7 @@ export default function VersionIndex() { const label = ( <div className="p-2 opacity-90 hover:opacity-100">{item.label}</div> ) + return ( <div key={i} className="hover:underline"> {item.to.startsWith('http') ? ( @@ -257,6 +269,7 @@ Check it out at https://tanstack.com/start/`, </div> </div> </div> */} + {/* <div className="px-4 sm:px-6 lg:px-8 mx-auto"> <div className=" sm:text-center pb-16"> <h3 className="text-3xl text-center mx-auto leading-tight font-extrabold tracking-tight sm:text-4xl lg:leading-none mt-2"> @@ -302,6 +315,7 @@ Check it out at https://tanstack.com/start/`, })} </div> </div> */} + {/* <div> <div className="uppercase tracking-wider text-sm font-semibold text-center text-gray-400 mb-3"> Trusted in Production by @@ -344,6 +358,7 @@ Check it out at https://tanstack.com/start/`, </div> </marquee> </div> */} + <div className="px-4 w-[500px] max-w-full mx-auto"> <h3 className="text-center text-3xl leading-8 font-extrabold tracking-tight sm:text-4xl sm:leading-10 lg:leading-none mt-8"> Partners @@ -373,13 +388,16 @@ Check it out at https://tanstack.com/start/`, </div> </div> </div> + <div className="relative text-lg overflow-hidden"> <h3 className="text-center text-3xl leading-8 font-extrabold tracking-tight sm:text-4xl sm:leading-10 lg:leading-none mt-8"> Sponsors </h3> <div className="my-4 flex flex-wrap mx-auto max-w-screen-lg" - style={{ aspectRatio: '1/1' }} + style={{ + aspectRatio: '1/1', + }} > <Await promise={sponsorsPromise} @@ -398,6 +416,7 @@ Check it out at https://tanstack.com/start/`, </a> </div> </div> + <div className="mx-auto max-w-[400px] flex flex-col gap-2 items-center"> <div className="shadow-lg rounded-lg overflow-hidden bg-white dark:bg-gray-800 dark:text-white"> <Carbon /> @@ -410,6 +429,7 @@ Check it out at https://tanstack.com/start/`, rage-quit OSS. Yay money! 😉 </span> </div> + {/* <div className="flex flex-col gap-4"> <div className="px-4 sm:px-6 lg:px-8 mx-auto max-w-3xl sm:text-center"> <h3 className="text-3xl text-center leading-8 font-extrabold tracking-tight sm:text-4xl sm:leading-10 lg:leading-none mt-2"> @@ -448,6 +468,7 @@ Check it out at https://tanstack.com/start/`, </div> </div> </div> */} + {/* {[''].includes(framework) ? ( <div className="px-2"> <div className="p-8 text-center text-lg w-full max-w-screen-lg mx-auto bg-black text-white rounded-xl"> @@ -482,6 +503,7 @@ Check it out at https://tanstack.com/start/`, ></iframe> </div> )} */} + {/* <div className="flex flex-col gap-4 items-center"> <div className="font-extrabold text-xl lg:text-2xl"> Wow, you've come a long way! diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/useStateDestructure@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/useStateDestructure@component---loader---notFoundComponent---pendingComponent.tsx index 5cc3099643..97b5481cf5 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/useStateDestructure@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/useStateDestructure@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,2 +1,2 @@ -import { FaBolt, FaBook, FaCheckCircle, FaCogs } from 'react-icons/fa' -import { VscPreview, VscWand } from 'react-icons/vsc' +import { FaBolt, FaBook, FaCheckCircle, FaCogs } from 'react-icons/fa'; +import { VscPreview, VscWand } from 'react-icons/vsc'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/useStateDestructure@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/useStateDestructure@errorComponent.tsx index 5cc3099643..97b5481cf5 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/useStateDestructure@errorComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/useStateDestructure@errorComponent.tsx @@ -1,2 +1,2 @@ -import { FaBolt, FaBook, FaCheckCircle, FaCogs } from 'react-icons/fa' -import { VscPreview, VscWand } from 'react-icons/vsc' +import { FaBolt, FaBook, FaCheckCircle, FaCogs } from 'react-icons/fa'; +import { VscPreview, VscWand } from 'react-icons/vsc'; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/using.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/using.tsx index 22ad515362..140f394f60 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/using.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/using.tsx @@ -1,6 +1,5 @@ -const $$splitLoaderImporter = () => - import('using.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyFn } from '@tanstack/react-router' +const $$splitLoaderImporter = () => import('using.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyFn } from '@tanstack/react-router'; export const Route = createFileRoute({ - loader: lazyFn($$splitLoaderImporter, 'loader'), -}) + loader: lazyFn($$splitLoaderImporter, 'loader') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/using@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/using@component---loader---notFoundComponent---pendingComponent.tsx index 3b60e73b8d..7e4f4fde9b 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/using@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/using@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,9 +1,17 @@ const DummyPostResource = (postId: string) => ({ - postData: { id: postId, title: 'dummy', body: 'dummy' }, - [Symbol.dispose]: () => console.log('disposing!'), -}) -const SplitLoader = ({ params: { postId } }) => { - using dummyPost = DummyPostResource(postId) - return dummyPost.postData -} -export { SplitLoader as loader } + postData: { + id: postId, + title: 'dummy', + body: 'dummy' + }, + [Symbol.dispose]: () => console.log('disposing!') +}); +const SplitLoader = ({ + params: { + postId + } +}) => { + using dummyPost = DummyPostResource(postId); + return dummyPost.postData; +}; +export { SplitLoader as loader }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/solid/1-default/arrow-function.tsx b/packages/router-plugin/tests/code-splitter/snapshots/solid/1-default/arrow-function.tsx index 10bedc87f0..b09548da57 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/solid/1-default/arrow-function.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/solid/1-default/arrow-function.tsx @@ -1,9 +1,8 @@ -const $$splitComponentImporter = () => - import('arrow-function.tsx?tsr-split=component') -import { lazyRouteComponent } from '@tanstack/solid-router' -import { createFileRoute } from '@tanstack/solid-router' -import { fetchPosts } from '../posts' +const $$splitComponentImporter = () => import('arrow-function.tsx?tsr-split=component'); +import { lazyRouteComponent } from '@tanstack/solid-router'; +import { createFileRoute } from '@tanstack/solid-router'; +import { fetchPosts } from '../posts'; export const Route = createFileRoute('/posts')({ loader: fetchPosts, - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/solid/1-default/arrow-function@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/solid/1-default/arrow-function@component.tsx index c84e6f25d4..fe44a34fe1 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/solid/1-default/arrow-function@component.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/solid/1-default/arrow-function@component.tsx @@ -1,31 +1,26 @@ -import * as Solid from 'solid-js' -import { Link, Outlet } from '@tanstack/solid-router' -import { Route } from 'arrow-function.tsx' +import * as Solid from 'solid-js'; +import { Link, Outlet } from '@tanstack/solid-router'; +import { Route } from "arrow-function.tsx"; const PostsComponent = () => { - const posts = Route.useLoaderData() - return ( - <div className="p-2 flex gap-2"> + const posts = Route.useLoaderData(); + return <div className="p-2 flex gap-2"> <ul className="list-disc pl-4"> <Solid.For each={posts()}> - {(post) => { - return ( - <li className="whitespace-nowrap"> - <Link - to="/posts/$postId" - params={{ postId: post.id }} - className="block py-1 text-blue-800 hover:text-blue-600" - activeProps={{ className: 'text-black font-bold' }} - > + {post => { + return <li className="whitespace-nowrap"> + <Link to="/posts/$postId" params={{ + postId: post.id + }} className="block py-1 text-blue-800 hover:text-blue-600" activeProps={{ + className: 'text-black font-bold' + }}> <div>{post.title.substring(0, 20)}</div> </Link> - </li> - ) - }} + </li>; + }} </Solid.For> </ul> <hr /> <Outlet /> - </div> - ) -} -export { PostsComponent as component } + </div>; +}; +export { PostsComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/solid/2-components-combined-loader-separate/arrow-function.tsx b/packages/router-plugin/tests/code-splitter/snapshots/solid/2-components-combined-loader-separate/arrow-function.tsx index 6842e20964..61c77d73bd 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/solid/2-components-combined-loader-separate/arrow-function.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/solid/2-components-combined-loader-separate/arrow-function.tsx @@ -1,11 +1,9 @@ -const $$splitComponentImporter = () => - import('arrow-function.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/solid-router' -const $$splitLoaderImporter = () => - import('arrow-function.tsx?tsr-split=loader') -import { lazyFn } from '@tanstack/solid-router' -import { createFileRoute } from '@tanstack/solid-router' +const $$splitComponentImporter = () => import('arrow-function.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/solid-router'; +const $$splitLoaderImporter = () => import('arrow-function.tsx?tsr-split=loader'); +import { lazyFn } from '@tanstack/solid-router'; +import { createFileRoute } from '@tanstack/solid-router'; export const Route = createFileRoute('/posts')({ loader: lazyFn($$splitLoaderImporter, 'loader'), - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/solid/2-components-combined-loader-separate/arrow-function@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/solid/2-components-combined-loader-separate/arrow-function@component---errorComponent---notFoundComponent---pendingComponent.tsx index c84e6f25d4..fe44a34fe1 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/solid/2-components-combined-loader-separate/arrow-function@component---errorComponent---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/solid/2-components-combined-loader-separate/arrow-function@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -1,31 +1,26 @@ -import * as Solid from 'solid-js' -import { Link, Outlet } from '@tanstack/solid-router' -import { Route } from 'arrow-function.tsx' +import * as Solid from 'solid-js'; +import { Link, Outlet } from '@tanstack/solid-router'; +import { Route } from "arrow-function.tsx"; const PostsComponent = () => { - const posts = Route.useLoaderData() - return ( - <div className="p-2 flex gap-2"> + const posts = Route.useLoaderData(); + return <div className="p-2 flex gap-2"> <ul className="list-disc pl-4"> <Solid.For each={posts()}> - {(post) => { - return ( - <li className="whitespace-nowrap"> - <Link - to="/posts/$postId" - params={{ postId: post.id }} - className="block py-1 text-blue-800 hover:text-blue-600" - activeProps={{ className: 'text-black font-bold' }} - > + {post => { + return <li className="whitespace-nowrap"> + <Link to="/posts/$postId" params={{ + postId: post.id + }} className="block py-1 text-blue-800 hover:text-blue-600" activeProps={{ + className: 'text-black font-bold' + }}> <div>{post.title.substring(0, 20)}</div> </Link> - </li> - ) - }} + </li>; + }} </Solid.For> </ul> <hr /> <Outlet /> - </div> - ) -} -export { PostsComponent as component } + </div>; +}; +export { PostsComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/solid/2-components-combined-loader-separate/arrow-function@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/solid/2-components-combined-loader-separate/arrow-function@loader.tsx index 888abc8593..d9ed4ea7af 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/solid/2-components-combined-loader-separate/arrow-function@loader.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/solid/2-components-combined-loader-separate/arrow-function@loader.tsx @@ -1,3 +1,3 @@ -import { fetchPosts } from '../posts' -const SplitLoader = fetchPosts -export { SplitLoader as loader } +import { fetchPosts } from '../posts'; +const SplitLoader = fetchPosts; +export { SplitLoader as loader }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/solid/3-all-combined-errorComponent-separate/arrow-function.tsx b/packages/router-plugin/tests/code-splitter/snapshots/solid/3-all-combined-errorComponent-separate/arrow-function.tsx index 2b7b2caefc..a872f13d33 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/solid/3-all-combined-errorComponent-separate/arrow-function.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/solid/3-all-combined-errorComponent-separate/arrow-function.tsx @@ -1,11 +1,9 @@ -const $$splitComponentImporter = () => - import('arrow-function.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyRouteComponent } from '@tanstack/solid-router' -const $$splitLoaderImporter = () => - import('arrow-function.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') -import { lazyFn } from '@tanstack/solid-router' -import { createFileRoute } from '@tanstack/solid-router' +const $$splitComponentImporter = () => import('arrow-function.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyRouteComponent } from '@tanstack/solid-router'; +const $$splitLoaderImporter = () => import('arrow-function.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent'); +import { lazyFn } from '@tanstack/solid-router'; +import { createFileRoute } from '@tanstack/solid-router'; export const Route = createFileRoute('/posts')({ loader: lazyFn($$splitLoaderImporter, 'loader'), - component: lazyRouteComponent($$splitComponentImporter, 'component'), -}) + component: lazyRouteComponent($$splitComponentImporter, 'component') +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/snapshots/solid/3-all-combined-errorComponent-separate/arrow-function@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/solid/3-all-combined-errorComponent-separate/arrow-function@component---loader---notFoundComponent---pendingComponent.tsx index 7fdf2dd9d0..2ea36d2e03 100644 --- a/packages/router-plugin/tests/code-splitter/snapshots/solid/3-all-combined-errorComponent-separate/arrow-function@component---loader---notFoundComponent---pendingComponent.tsx +++ b/packages/router-plugin/tests/code-splitter/snapshots/solid/3-all-combined-errorComponent-separate/arrow-function@component---loader---notFoundComponent---pendingComponent.tsx @@ -1,34 +1,29 @@ -import * as Solid from 'solid-js' -import { Link, Outlet } from '@tanstack/solid-router' -import { fetchPosts } from '../posts' -import { Route } from 'arrow-function.tsx' +import * as Solid from 'solid-js'; +import { Link, Outlet } from '@tanstack/solid-router'; +import { fetchPosts } from '../posts'; +import { Route } from "arrow-function.tsx"; const PostsComponent = () => { - const posts = Route.useLoaderData() - return ( - <div className="p-2 flex gap-2"> + const posts = Route.useLoaderData(); + return <div className="p-2 flex gap-2"> <ul className="list-disc pl-4"> <Solid.For each={posts()}> - {(post) => { - return ( - <li className="whitespace-nowrap"> - <Link - to="/posts/$postId" - params={{ postId: post.id }} - className="block py-1 text-blue-800 hover:text-blue-600" - activeProps={{ className: 'text-black font-bold' }} - > + {post => { + return <li className="whitespace-nowrap"> + <Link to="/posts/$postId" params={{ + postId: post.id + }} className="block py-1 text-blue-800 hover:text-blue-600" activeProps={{ + className: 'text-black font-bold' + }}> <div>{post.title.substring(0, 20)}</div> </Link> - </li> - ) - }} + </li>; + }} </Solid.For> </ul> <hr /> <Outlet /> - </div> - ) -} -const SplitLoader = fetchPosts -export { SplitLoader as loader } -export { PostsComponent as component } + </div>; +}; +const SplitLoader = fetchPosts; +export { SplitLoader as loader }; +export { PostsComponent as component }; \ No newline at end of file diff --git a/packages/router-plugin/tests/code-splitter/test-files/react/lowercase-function-declaration.tsx b/packages/router-plugin/tests/code-splitter/test-files/react/lowercase-function-declaration.tsx deleted file mode 100644 index bfc37b1d6a..0000000000 --- a/packages/router-plugin/tests/code-splitter/test-files/react/lowercase-function-declaration.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/')({ - component, - pendingComponent, - errorComponent, -}) - -function component() { - return <div>lowercase function declaration</div> -} - -function pendingComponent() { - return <div>lowercase pending function declaration</div> -} - -function errorComponent() { - return <div>lowercase error function declaration</div> -} diff --git a/packages/router-plugin/tests/code-splitter/test-files/react/shared-runtime.tsx b/packages/router-plugin/tests/code-splitter/test-files/react/shared-runtime.tsx deleted file mode 100644 index f9fd708a0b..0000000000 --- a/packages/router-plugin/tests/code-splitter/test-files/react/shared-runtime.tsx +++ /dev/null @@ -1,50 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -const Count = { Initial: 0 } - -const Labels = { component: 'count' } - -const seed = createSeed() -const { state, increment } = createState(seed) -const label = createComponentLabel() -console.log('shared-runtime:reference') - -export const Route = createFileRoute('/shared-runtime')({ - beforeLoad: () => state, - loader: () => { - increment() - return state - }, - component: () => { - if (state.count === 3) { - throw new Error('route source-map contract') - } - return `${label}:${state.count}` - }, -}) - -function createSeed() { - console.log('shared-runtime:seed') - return { count: Count.Initial, label: Labels.component } -} - -function createState(initialState: { count: number }): { - state: { count: number } - increment: () => number -} -function createState(initialState: { count: number }) { - console.log('shared-runtime:state') - return { - state: initialState, - increment: () => initialState.count++, - } -} - -function createComponentLabel() { - console.log('shared-runtime:component') - return Labels.component -} - -export { state as firstState, state as secondState, state as 'odd-name' } - -export default createSeed diff --git a/packages/router-plugin/tests/config.test.ts b/packages/router-plugin/tests/config.test.ts index 7191f197a9..2f3e8cc7db 100644 --- a/packages/router-plugin/tests/config.test.ts +++ b/packages/router-plugin/tests/config.test.ts @@ -11,6 +11,7 @@ describe('getConfig', () => { inlineConfig: { target: 'solid', autoCodeSplitting: false, + enableRouteGeneration: true, } as Partial<Config>, withJson: false, }, @@ -21,6 +22,7 @@ describe('getConfig', () => { autoCodeSplitting: false, routesDirectory: 'src/paths', generatedRouteTree: 'src/tree/routeTree.gen.ts', + enableRouteGeneration: true, } as Partial<Config>, withJson: false, }, @@ -31,6 +33,7 @@ describe('getConfig', () => { autoCodeSplitting: true, routesDirectory: './src/paths', generatedRouteTree: './src/tree/routeTree.gen.ts', + enableRouteGeneration: true, } as Partial<Config>, withJson: false, }, @@ -41,6 +44,7 @@ describe('getConfig', () => { autoCodeSplitting: false, routesDirectory: '/src/paths', generatedRouteTree: '/src/tree/routeTree.gen.ts', + enableRouteGeneration: true, } as Partial<Config>, withJson: false, }, @@ -56,6 +60,7 @@ describe('getConfig', () => { autoCodeSplitting: true, routesDirectory: './src/paths', generatedRouteTree: './src/tree/routeTree.gen.ts', + enableRouteGeneration: true, } as Partial<Config>, withJson: true, }, diff --git a/packages/router-plugin/tests/delete-nodes.test.ts b/packages/router-plugin/tests/delete-nodes.test.ts index d9b37ce54a..6bb1d3dc6d 100644 --- a/packages/router-plugin/tests/delete-nodes.test.ts +++ b/packages/router-plugin/tests/delete-nodes.test.ts @@ -4,7 +4,6 @@ import { describe, expect, it } from 'vitest' import { compileCodeSplitReferenceRoute } from '../src/core/code-splitter/compilers' import { frameworks } from './constants' -import { formatSnapshot } from './format-snapshot' import type { DeletableNodes } from '../src/core/config' function getFrameworkDir(framework: string) { @@ -58,9 +57,7 @@ describe('code-splitter delete nodes', () => { targetFramework: framework, }) - await expect( - await formatSnapshot(compileResult?.code || code, filename), - ).toMatchFileSnapshot( + await expect(compileResult?.code || code).toMatchFileSnapshot( path.join(dirs.snapshots, groupName, filename), ) }, diff --git a/packages/router-plugin/tests/delete-nodes/snapshots/react/1-delete-nodes-undefined/createRootRoute-ssr-function.tsx b/packages/router-plugin/tests/delete-nodes/snapshots/react/1-delete-nodes-undefined/createRootRoute-ssr-function.tsx index 9ddd962b9c..512e597528 100644 --- a/packages/router-plugin/tests/delete-nodes/snapshots/react/1-delete-nodes-undefined/createRootRoute-ssr-function.tsx +++ b/packages/router-plugin/tests/delete-nodes/snapshots/react/1-delete-nodes-undefined/createRootRoute-ssr-function.tsx @@ -1,5 +1,6 @@ import { createRootRoute } from '@tanstack/react-router' import crypto from 'node:crypto' + export const Route = createRootRoute({ ssr: () => { if (crypto.randomInt(0, 2) === 0) { diff --git a/packages/router-plugin/tests/delete-nodes/snapshots/react/1-delete-nodes-undefined/createRootRouteWithContext-ssr-function.tsx b/packages/router-plugin/tests/delete-nodes/snapshots/react/1-delete-nodes-undefined/createRootRouteWithContext-ssr-function.tsx index 97521cd051..9a2cac49b3 100644 --- a/packages/router-plugin/tests/delete-nodes/snapshots/react/1-delete-nodes-undefined/createRootRouteWithContext-ssr-function.tsx +++ b/packages/router-plugin/tests/delete-nodes/snapshots/react/1-delete-nodes-undefined/createRootRouteWithContext-ssr-function.tsx @@ -1,5 +1,6 @@ import { createRootRouteWithContext } from '@tanstack/react-router' import crypto from 'node:crypto' + export const Route = createRootRouteWithContext<{}>()({ ssr: () => { if (crypto.randomInt(0, 2) === 0) { diff --git a/packages/router-plugin/tests/delete-nodes/snapshots/react/1-delete-nodes-undefined/ssr-data-only.tsx b/packages/router-plugin/tests/delete-nodes/snapshots/react/1-delete-nodes-undefined/ssr-data-only.tsx index 9ab5a1eb7f..c489be3266 100644 --- a/packages/router-plugin/tests/delete-nodes/snapshots/react/1-delete-nodes-undefined/ssr-data-only.tsx +++ b/packages/router-plugin/tests/delete-nodes/snapshots/react/1-delete-nodes-undefined/ssr-data-only.tsx @@ -1,4 +1,5 @@ import { createFileRoute } from '@tanstack/react-router' + export const Route = createFileRoute('/')({ ssr: 'data-only', component: () => { diff --git a/packages/router-plugin/tests/delete-nodes/snapshots/react/1-delete-nodes-undefined/ssr-false.tsx b/packages/router-plugin/tests/delete-nodes/snapshots/react/1-delete-nodes-undefined/ssr-false.tsx index daeb982324..d2409de686 100644 --- a/packages/router-plugin/tests/delete-nodes/snapshots/react/1-delete-nodes-undefined/ssr-false.tsx +++ b/packages/router-plugin/tests/delete-nodes/snapshots/react/1-delete-nodes-undefined/ssr-false.tsx @@ -1,4 +1,5 @@ import { createFileRoute } from '@tanstack/react-router' + export const Route = createFileRoute('/')({ ssr: false, component: () => { diff --git a/packages/router-plugin/tests/delete-nodes/snapshots/react/2-delete-nodes-empty/createRootRoute-ssr-function.tsx b/packages/router-plugin/tests/delete-nodes/snapshots/react/2-delete-nodes-empty/createRootRoute-ssr-function.tsx index 9ddd962b9c..512e597528 100644 --- a/packages/router-plugin/tests/delete-nodes/snapshots/react/2-delete-nodes-empty/createRootRoute-ssr-function.tsx +++ b/packages/router-plugin/tests/delete-nodes/snapshots/react/2-delete-nodes-empty/createRootRoute-ssr-function.tsx @@ -1,5 +1,6 @@ import { createRootRoute } from '@tanstack/react-router' import crypto from 'node:crypto' + export const Route = createRootRoute({ ssr: () => { if (crypto.randomInt(0, 2) === 0) { diff --git a/packages/router-plugin/tests/delete-nodes/snapshots/react/2-delete-nodes-empty/createRootRouteWithContext-ssr-function.tsx b/packages/router-plugin/tests/delete-nodes/snapshots/react/2-delete-nodes-empty/createRootRouteWithContext-ssr-function.tsx index 97521cd051..9a2cac49b3 100644 --- a/packages/router-plugin/tests/delete-nodes/snapshots/react/2-delete-nodes-empty/createRootRouteWithContext-ssr-function.tsx +++ b/packages/router-plugin/tests/delete-nodes/snapshots/react/2-delete-nodes-empty/createRootRouteWithContext-ssr-function.tsx @@ -1,5 +1,6 @@ import { createRootRouteWithContext } from '@tanstack/react-router' import crypto from 'node:crypto' + export const Route = createRootRouteWithContext<{}>()({ ssr: () => { if (crypto.randomInt(0, 2) === 0) { diff --git a/packages/router-plugin/tests/delete-nodes/snapshots/react/2-delete-nodes-empty/ssr-data-only.tsx b/packages/router-plugin/tests/delete-nodes/snapshots/react/2-delete-nodes-empty/ssr-data-only.tsx index 9ab5a1eb7f..c489be3266 100644 --- a/packages/router-plugin/tests/delete-nodes/snapshots/react/2-delete-nodes-empty/ssr-data-only.tsx +++ b/packages/router-plugin/tests/delete-nodes/snapshots/react/2-delete-nodes-empty/ssr-data-only.tsx @@ -1,4 +1,5 @@ import { createFileRoute } from '@tanstack/react-router' + export const Route = createFileRoute('/')({ ssr: 'data-only', component: () => { diff --git a/packages/router-plugin/tests/delete-nodes/snapshots/react/2-delete-nodes-empty/ssr-false.tsx b/packages/router-plugin/tests/delete-nodes/snapshots/react/2-delete-nodes-empty/ssr-false.tsx index daeb982324..d2409de686 100644 --- a/packages/router-plugin/tests/delete-nodes/snapshots/react/2-delete-nodes-empty/ssr-false.tsx +++ b/packages/router-plugin/tests/delete-nodes/snapshots/react/2-delete-nodes-empty/ssr-false.tsx @@ -1,4 +1,5 @@ import { createFileRoute } from '@tanstack/react-router' + export const Route = createFileRoute('/')({ ssr: false, component: () => { diff --git a/packages/router-plugin/tests/delete-nodes/snapshots/react/3-delete-nodes-ssr/createRootRoute-ssr-function.tsx b/packages/router-plugin/tests/delete-nodes/snapshots/react/3-delete-nodes-ssr/createRootRoute-ssr-function.tsx index 74e60e59e1..a442b9ad2f 100644 --- a/packages/router-plugin/tests/delete-nodes/snapshots/react/3-delete-nodes-ssr/createRootRoute-ssr-function.tsx +++ b/packages/router-plugin/tests/delete-nodes/snapshots/react/3-delete-nodes-ssr/createRootRoute-ssr-function.tsx @@ -1,6 +1,6 @@ -import { createRootRoute } from '@tanstack/react-router' +import { createRootRoute } from '@tanstack/react-router'; export const Route = createRootRoute({ component: () => { - return <div className="p-2">hello world</div> - }, -}) + return <div className="p-2">hello world</div>; + } +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/delete-nodes/snapshots/react/3-delete-nodes-ssr/createRootRouteWithContext-ssr-function.tsx b/packages/router-plugin/tests/delete-nodes/snapshots/react/3-delete-nodes-ssr/createRootRouteWithContext-ssr-function.tsx index 9c4e69445c..75c818b072 100644 --- a/packages/router-plugin/tests/delete-nodes/snapshots/react/3-delete-nodes-ssr/createRootRouteWithContext-ssr-function.tsx +++ b/packages/router-plugin/tests/delete-nodes/snapshots/react/3-delete-nodes-ssr/createRootRouteWithContext-ssr-function.tsx @@ -1,6 +1,6 @@ -import { createRootRouteWithContext } from '@tanstack/react-router' +import { createRootRouteWithContext } from '@tanstack/react-router'; export const Route = createRootRouteWithContext<{}>()({ component: () => { - return <div className="p-2">hello world</div> - }, -}) + return <div className="p-2">hello world</div>; + } +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/delete-nodes/snapshots/react/3-delete-nodes-ssr/ssr-data-only.tsx b/packages/router-plugin/tests/delete-nodes/snapshots/react/3-delete-nodes-ssr/ssr-data-only.tsx index fd9a7cd090..cd2371ae2e 100644 --- a/packages/router-plugin/tests/delete-nodes/snapshots/react/3-delete-nodes-ssr/ssr-data-only.tsx +++ b/packages/router-plugin/tests/delete-nodes/snapshots/react/3-delete-nodes-ssr/ssr-data-only.tsx @@ -1,6 +1,6 @@ -import { createFileRoute } from '@tanstack/react-router' +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/')({ component: () => { - return <div className="p-2">hello world</div> - }, -}) + return <div className="p-2">hello world</div>; + } +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/delete-nodes/snapshots/react/3-delete-nodes-ssr/ssr-false.tsx b/packages/router-plugin/tests/delete-nodes/snapshots/react/3-delete-nodes-ssr/ssr-false.tsx index fd9a7cd090..cd2371ae2e 100644 --- a/packages/router-plugin/tests/delete-nodes/snapshots/react/3-delete-nodes-ssr/ssr-false.tsx +++ b/packages/router-plugin/tests/delete-nodes/snapshots/react/3-delete-nodes-ssr/ssr-false.tsx @@ -1,6 +1,6 @@ -import { createFileRoute } from '@tanstack/react-router' +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/')({ component: () => { - return <div className="p-2">hello world</div> - }, -}) + return <div className="p-2">hello world</div>; + } +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/delete-nodes/snapshots/react/3-delete-nodes-ssr/ssr-function.tsx b/packages/router-plugin/tests/delete-nodes/snapshots/react/3-delete-nodes-ssr/ssr-function.tsx index fd9a7cd090..cd2371ae2e 100644 --- a/packages/router-plugin/tests/delete-nodes/snapshots/react/3-delete-nodes-ssr/ssr-function.tsx +++ b/packages/router-plugin/tests/delete-nodes/snapshots/react/3-delete-nodes-ssr/ssr-function.tsx @@ -1,6 +1,6 @@ -import { createFileRoute } from '@tanstack/react-router' +import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/')({ component: () => { - return <div className="p-2">hello world</div> - }, -}) + return <div className="p-2">hello world</div>; + } +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/delete-nodes/snapshots/solid/1-delete-nodes-undefined/ssr-data-only.tsx b/packages/router-plugin/tests/delete-nodes/snapshots/solid/1-delete-nodes-undefined/ssr-data-only.tsx index 50cdfdeb49..e6a51d19ea 100644 --- a/packages/router-plugin/tests/delete-nodes/snapshots/solid/1-delete-nodes-undefined/ssr-data-only.tsx +++ b/packages/router-plugin/tests/delete-nodes/snapshots/solid/1-delete-nodes-undefined/ssr-data-only.tsx @@ -1,4 +1,5 @@ import { createFileRoute } from '@tanstack/solid-router' + export const Route = createFileRoute('/')({ ssr: 'data-only', component: () => { diff --git a/packages/router-plugin/tests/delete-nodes/snapshots/solid/1-delete-nodes-undefined/ssr-false.tsx b/packages/router-plugin/tests/delete-nodes/snapshots/solid/1-delete-nodes-undefined/ssr-false.tsx index 178109f8d7..31eda25da3 100644 --- a/packages/router-plugin/tests/delete-nodes/snapshots/solid/1-delete-nodes-undefined/ssr-false.tsx +++ b/packages/router-plugin/tests/delete-nodes/snapshots/solid/1-delete-nodes-undefined/ssr-false.tsx @@ -1,4 +1,5 @@ import { createFileRoute } from '@tanstack/solid-router' + export const Route = createFileRoute('/')({ ssr: false, component: () => { diff --git a/packages/router-plugin/tests/delete-nodes/snapshots/solid/1-delete-nodes-undefined/ssr-function.tsx b/packages/router-plugin/tests/delete-nodes/snapshots/solid/1-delete-nodes-undefined/ssr-function.tsx index d16a74bb7a..a111e03c8d 100644 --- a/packages/router-plugin/tests/delete-nodes/snapshots/solid/1-delete-nodes-undefined/ssr-function.tsx +++ b/packages/router-plugin/tests/delete-nodes/snapshots/solid/1-delete-nodes-undefined/ssr-function.tsx @@ -1,4 +1,5 @@ import { createFileRoute } from '@tanstack/solid-router' + export const Route = createFileRoute('/')({ ssr: () => { if (typeof window === 'undefined') { diff --git a/packages/router-plugin/tests/delete-nodes/snapshots/solid/2-delete-nodes-empty/ssr-data-only.tsx b/packages/router-plugin/tests/delete-nodes/snapshots/solid/2-delete-nodes-empty/ssr-data-only.tsx index 50cdfdeb49..e6a51d19ea 100644 --- a/packages/router-plugin/tests/delete-nodes/snapshots/solid/2-delete-nodes-empty/ssr-data-only.tsx +++ b/packages/router-plugin/tests/delete-nodes/snapshots/solid/2-delete-nodes-empty/ssr-data-only.tsx @@ -1,4 +1,5 @@ import { createFileRoute } from '@tanstack/solid-router' + export const Route = createFileRoute('/')({ ssr: 'data-only', component: () => { diff --git a/packages/router-plugin/tests/delete-nodes/snapshots/solid/2-delete-nodes-empty/ssr-false.tsx b/packages/router-plugin/tests/delete-nodes/snapshots/solid/2-delete-nodes-empty/ssr-false.tsx index 178109f8d7..31eda25da3 100644 --- a/packages/router-plugin/tests/delete-nodes/snapshots/solid/2-delete-nodes-empty/ssr-false.tsx +++ b/packages/router-plugin/tests/delete-nodes/snapshots/solid/2-delete-nodes-empty/ssr-false.tsx @@ -1,4 +1,5 @@ import { createFileRoute } from '@tanstack/solid-router' + export const Route = createFileRoute('/')({ ssr: false, component: () => { diff --git a/packages/router-plugin/tests/delete-nodes/snapshots/solid/2-delete-nodes-empty/ssr-function.tsx b/packages/router-plugin/tests/delete-nodes/snapshots/solid/2-delete-nodes-empty/ssr-function.tsx index d16a74bb7a..a111e03c8d 100644 --- a/packages/router-plugin/tests/delete-nodes/snapshots/solid/2-delete-nodes-empty/ssr-function.tsx +++ b/packages/router-plugin/tests/delete-nodes/snapshots/solid/2-delete-nodes-empty/ssr-function.tsx @@ -1,4 +1,5 @@ import { createFileRoute } from '@tanstack/solid-router' + export const Route = createFileRoute('/')({ ssr: () => { if (typeof window === 'undefined') { diff --git a/packages/router-plugin/tests/delete-nodes/snapshots/solid/3-delete-nodes-ssr/ssr-data-only.tsx b/packages/router-plugin/tests/delete-nodes/snapshots/solid/3-delete-nodes-ssr/ssr-data-only.tsx index 7ed1de7be5..77e05f3b12 100644 --- a/packages/router-plugin/tests/delete-nodes/snapshots/solid/3-delete-nodes-ssr/ssr-data-only.tsx +++ b/packages/router-plugin/tests/delete-nodes/snapshots/solid/3-delete-nodes-ssr/ssr-data-only.tsx @@ -1,6 +1,6 @@ -import { createFileRoute } from '@tanstack/solid-router' +import { createFileRoute } from '@tanstack/solid-router'; export const Route = createFileRoute('/')({ component: () => { - return <div className="p-2">hello world</div> - }, -}) + return <div className="p-2">hello world</div>; + } +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/delete-nodes/snapshots/solid/3-delete-nodes-ssr/ssr-false.tsx b/packages/router-plugin/tests/delete-nodes/snapshots/solid/3-delete-nodes-ssr/ssr-false.tsx index 7ed1de7be5..77e05f3b12 100644 --- a/packages/router-plugin/tests/delete-nodes/snapshots/solid/3-delete-nodes-ssr/ssr-false.tsx +++ b/packages/router-plugin/tests/delete-nodes/snapshots/solid/3-delete-nodes-ssr/ssr-false.tsx @@ -1,6 +1,6 @@ -import { createFileRoute } from '@tanstack/solid-router' +import { createFileRoute } from '@tanstack/solid-router'; export const Route = createFileRoute('/')({ component: () => { - return <div className="p-2">hello world</div> - }, -}) + return <div className="p-2">hello world</div>; + } +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/delete-nodes/snapshots/solid/3-delete-nodes-ssr/ssr-function.tsx b/packages/router-plugin/tests/delete-nodes/snapshots/solid/3-delete-nodes-ssr/ssr-function.tsx index 7ed1de7be5..77e05f3b12 100644 --- a/packages/router-plugin/tests/delete-nodes/snapshots/solid/3-delete-nodes-ssr/ssr-function.tsx +++ b/packages/router-plugin/tests/delete-nodes/snapshots/solid/3-delete-nodes-ssr/ssr-function.tsx @@ -1,6 +1,6 @@ -import { createFileRoute } from '@tanstack/solid-router' +import { createFileRoute } from '@tanstack/solid-router'; export const Route = createFileRoute('/')({ component: () => { - return <div className="p-2">hello world</div> - }, -}) + return <div className="p-2">hello world</div>; + } +}); \ No newline at end of file diff --git a/packages/router-plugin/tests/esbuild.test.ts b/packages/router-plugin/tests/esbuild.test.ts deleted file mode 100644 index 7a7a57a515..0000000000 --- a/packages/router-plugin/tests/esbuild.test.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { describe, expect, test } from 'vitest' -import { - TanStackRouterCodeSplitterEsbuild, - TanStackRouterGeneratorEsbuild, - tanstackRouter, -} from '../src/esbuild' - -describe('esbuild plugin', () => { - test('refuses autoCodeSplitting', () => { - expect(() => - tanstackRouter({ target: 'react', autoCodeSplitting: true }), - ).toThrow(/autoCodeSplitting/) - }) - - test('refuses the code splitter entry', () => { - expect(() => TanStackRouterCodeSplitterEsbuild()).toThrow( - /autoCodeSplitting/, - ) - }) - - test('accepts route generation without code splitting', () => { - expect(() => tanstackRouter({ target: 'react' })).not.toThrow() - expect(() => - tanstackRouter({ target: 'react', autoCodeSplitting: false }), - ).not.toThrow() - expect(() => TanStackRouterGeneratorEsbuild()).not.toThrow() - }) -}) diff --git a/packages/router-plugin/tests/format-snapshot.ts b/packages/router-plugin/tests/format-snapshot.ts deleted file mode 100644 index d152094bea..0000000000 --- a/packages/router-plugin/tests/format-snapshot.ts +++ /dev/null @@ -1,69 +0,0 @@ -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<string> = [] - 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/router-plugin/tests/handle-route-update.test.ts b/packages/router-plugin/tests/handle-route-update.test.ts deleted file mode 100644 index 9c8e239fe2..0000000000 --- a/packages/router-plugin/tests/handle-route-update.test.ts +++ /dev/null @@ -1,652 +0,0 @@ -// @vitest-environment jsdom - -import { - BaseRootRoute, - BaseRoute, - RouterCore, - createNonReactiveMutableStore, - createNonReactiveReadonlyStore, - trimPathRight, -} from '@tanstack/router-core' -import { describe, expect, it, onTestFinished, vi } from 'vitest' -import { Fragment, act, createElement } from 'react' -import { createPortal } from 'react-dom' -import { createRoot } from 'react-dom/client' -import { createMemoryHistory } from '../../history/src' -import { HeadContent } from '../../react-router/src/HeadContent' -import { RouterContextProvider } from '../../react-router/src/RouterProvider' -import { Scripts } from '../../react-router/src/Scripts' -import { Router as ReactRouter } from '../../react-router/src/router' -import { getHandleRouteUpdateCode } from '../src/core/hmr' -import type { AnyRoute, GetStoreConfig } from '@tanstack/router-core' - -vi.mock('@tanstack/router-core/isServer', async (importOriginal) => ({ - ...(await importOriginal()), - isServer: undefined, -})) - -const getStoreConfig: GetStoreConfig = () => ({ - createMutableStore: createNonReactiveMutableStore, - createReadonlyStore: createNonReactiveReadonlyStore, - batch: (fn) => fn(), -}) - -const getHandleRouteUpdate = () => { - return new Function(`return ${getHandleRouteUpdateCode([])}`)() as ( - routeId: string, - newRoute: AnyRoute, - ) => void -} - -function asAnyRoute<TRoute>(route: TRoute): TRoute & AnyRoute { - return route as unknown as TRoute & AnyRoute -} - -function createTestHistory() { - const location = { - href: '/', - pathname: '/', - search: '', - hash: '', - state: { __TSR_index: 0 }, - } - - return { - location, - length: 1, - subscribers: new Set(), - subscribe: () => () => {}, - push: () => {}, - replace: () => {}, - go: () => {}, - back: () => {}, - forward: () => {}, - canGoBack: () => false, - createHref: (href: string) => href, - block: () => () => {}, - flush: () => {}, - destroy: () => {}, - notify: () => {}, - } -} - -function createTestRouter<TRouteTree>(routeTree: TRouteTree) { - return new RouterCore( - { - routeTree: asAnyRoute(routeTree), - history: createTestHistory() as any, - isServer: true, - }, - getStoreConfig, - ) -} - -function createClientTestRouter<TRouteTree>( - routeTree: TRouteTree, - initialEntry: string, -) { - return new RouterCore( - { - routeTree: asAnyRoute(routeTree), - history: createMemoryHistory({ initialEntries: [initialEntry] }), - isServer: false, - origin: 'http://localhost', - }, - getStoreConfig, - ) -} - -function createReactClientTestRouter<TRouteTree>( - routeTree: TRouteTree, - initialEntry: string, -) { - return new ReactRouter({ - routeTree: asAnyRoute(routeTree), - history: createMemoryHistory({ initialEntries: [initialEntry] }), - isServer: false, - origin: 'http://localhost', - }) -} - -function withWindowRouter(router: RouterCore<any, any, any, any, any>) { - const testWindow = globalThis.window as any - const hadOwnRouter = Object.prototype.hasOwnProperty.call( - testWindow, - '__TSR_ROUTER__', - ) - const previousRouter = testWindow.__TSR_ROUTER__ - testWindow.__TSR_ROUTER__ = router - - return () => { - if (hadOwnRouter) { - testWindow.__TSR_ROUTER__ = previousRouter - } else { - delete testWindow.__TSR_ROUTER__ - } - } -} - -function runHandleRouteUpdate<TRoute>( - router: RouterCore<any, any, any, any, any>, - routeId: string, - newRoute: TRoute, -) { - const restoreWindow = withWindowRouter(router) - try { - getHandleRouteUpdate()(routeId, asAnyRoute(newRoute)) - } finally { - restoreWindow() - } -} - -function getProcessedTreeRouteForPath( - router: RouterCore<any, any, any, any, any>, - path: string, -) { - return router.buildRouteTree().routesByPath[path]?.id -} - -describe('handleRouteUpdate', () => { - it('keeps routesByPath pointed at an index route when a pathless layout updates', () => { - const rootRoute = new BaseRootRoute({}) - const parentRoute = new BaseRoute({ - getParentRoute: () => asAnyRoute(rootRoute), - path: '/livestock/$farmId/medicine', - }) - const pathlessRoute = new BaseRoute({ - getParentRoute: () => asAnyRoute(parentRoute), - id: '_form', - }) - const newRoute = new BaseRoute({ - getParentRoute: () => asAnyRoute(pathlessRoute), - path: 'new', - }) - const indexRoute = new BaseRoute({ - getParentRoute: () => asAnyRoute(parentRoute), - path: '/', - }) - const routeTree = rootRoute.addChildren([ - parentRoute.addChildren([ - pathlessRoute.addChildren([asAnyRoute(newRoute)]), - asAnyRoute(indexRoute), - ]), - ]) - const router = createTestRouter(routeTree) - const key = trimPathRight(indexRoute.fullPath) - - expect(router.routesByPath[key]?.id).toBe(indexRoute.id) - - const restoreWindow = withWindowRouter(router) - try { - getHandleRouteUpdate()( - pathlessRoute.id, - asAnyRoute(new BaseRoute({} as any)), - ) - } finally { - restoreWindow() - } - - expect(router.routesByPath[key]?.id).toBe(indexRoute.id) - expect(router.routesByPath[key]?.id).toBe( - getProcessedTreeRouteForPath(router, key), - ) - }) - - it('keeps an index route winning the trimmed path key when its parent updates', () => { - const rootRoute = new BaseRootRoute({}) - const parentRoute = new BaseRoute({ - getParentRoute: () => asAnyRoute(rootRoute), - path: '/path', - }) - const indexRoute = new BaseRoute({ - getParentRoute: () => asAnyRoute(parentRoute), - path: '/', - }) - const routeTree = rootRoute.addChildren([ - parentRoute.addChildren([asAnyRoute(indexRoute)]), - ]) - const router = createTestRouter(routeTree) - const key = trimPathRight(indexRoute.fullPath) - - expect(router.routesByPath[key]?.id).toBe(indexRoute.id) - - const restoreWindow = withWindowRouter(router) - try { - getHandleRouteUpdate()( - parentRoute.id, - asAnyRoute(new BaseRoute({} as any)), - ) - } finally { - restoreWindow() - } - - expect(router.routesByPath[key]?.id).toBe(indexRoute.id) - expect(router.routesByPath[key]?.id).toBe( - getProcessedTreeRouteForPath(router, key), - ) - }) - - it('refreshes matching data when params.parse changes', () => { - const rootRoute = new BaseRootRoute({}) - const itemRoute = new BaseRoute({ - getParentRoute: () => asAnyRoute(rootRoute), - path: '/items/$itemId', - params: { - parse: ({ itemId }: { itemId: string }) => { - return /^\d+$/.test(itemId) ? { itemId } : false - }, - }, - }) - const routeTree = rootRoute.addChildren([asAnyRoute(itemRoute)]) - const router = createTestRouter(routeTree) - - expect(router.getMatchedRoutes('/items/abc')[2]?.id).toBeUndefined() - - const restoreWindow = withWindowRouter(router) - try { - getHandleRouteUpdate()( - itemRoute.id, - asAnyRoute( - new BaseRoute({ - params: { - parse: ({ itemId }: { itemId: string }) => ({ itemId }), - }, - } as any), - ), - ) - } finally { - restoreWindow() - } - - expect(router.getMatchedRoutes('/items/abc')[2]?.id).toBe(itemRoute.id) - }) - - it('hydrates the hot module route export with generated route tree state', () => { - const rootRoute = new BaseRootRoute({}) - const itemRoute = new BaseRoute({ - getParentRoute: () => asAnyRoute(rootRoute), - path: '/items/$itemId', - }) - const routeTree = rootRoute.addChildren([asAnyRoute(itemRoute)]) - const router = createTestRouter(routeTree) - const newRoute = new BaseRoute({} as any) - - expect((newRoute as any).to).toBeUndefined() - - const restoreWindow = withWindowRouter(router) - try { - getHandleRouteUpdate()(itemRoute.id, asAnyRoute(newRoute)) - } finally { - restoreWindow() - } - - expect(newRoute.id).toBe(itemRoute.id) - expect(newRoute.path).toBe(itemRoute.path) - expect(newRoute.fullPath).toBe(itemRoute.fullPath) - expect(newRoute.to).toBe(itemRoute.to) - expect((newRoute as any).parentRoute).toBe(rootRoute) - expect((newRoute as any).options).toBe((itemRoute as any).options) - }) - - it('clears lazy ownership and delegates rematerialization to the router', () => { - const rootRoute = new BaseRootRoute({}) - const itemRoute = new BaseRoute({ - getParentRoute: () => asAnyRoute(rootRoute), - path: '/items/$itemId', - }) - const router = createTestRouter( - rootRoute.addChildren([asAnyRoute(itemRoute)]), - ) - const lazyOwner = Promise.resolve() - const refreshRoute = vi.fn(async () => {}) - ;(itemRoute as any)._lazy = lazyOwner - ;(router as any)._refreshRoute = refreshRoute - - expect((itemRoute as any)._lazy).toBe(lazyOwner) - - runHandleRouteUpdate(router, itemRoute.id, new BaseRoute({} as any)) - - expect((itemRoute as any)._lazy).toBeUndefined() - expect(refreshRoute).toHaveBeenCalledTimes(1) - expect(refreshRoute).toHaveBeenCalledWith() - }) - - it('uses a fresh source lazy importer without erasing an omitted one', () => { - const oldImporter = vi.fn(async () => ({ options: {} }) as any) - const newImporter = vi.fn(async () => ({ options: {} }) as any) - const rootRoute = new BaseRootRoute({}) - const itemRoute = new BaseRoute({ - getParentRoute: () => asAnyRoute(rootRoute), - path: '/items/$itemId', - }).lazy(oldImporter) - const router = createTestRouter( - rootRoute.addChildren([asAnyRoute(itemRoute)]), - ) - - runHandleRouteUpdate( - router, - itemRoute.id, - new BaseRoute({} as any).lazy(newImporter), - ) - expect(itemRoute.lazyFn).toBe(newImporter) - - runHandleRouteUpdate(router, itemRoute.id, new BaseRoute({} as any)) - expect(itemRoute.lazyFn).toBe(newImporter) - }) - - it('removes stale loader data when a hot route removes its loader', async () => { - const rootRoute = new BaseRootRoute({}) - const hotRoute = new BaseRoute({ - getParentRoute: () => asAnyRoute(rootRoute), - path: '/hot', - loader: () => 'stale loader data', - }) - const router = createClientTestRouter( - rootRoute.addChildren([asAnyRoute(hotRoute)]), - '/hot', - ) - await router.load() - - expect(router.state.matches.map((match) => match.routeId)).toEqual([ - rootRoute.id, - hotRoute.id, - ]) - expect(router.state.matches[1]!.loaderData).toBe('stale loader data') - - const restoreWindow = withWindowRouter(router) - try { - getHandleRouteUpdate()(hotRoute.id, asAnyRoute(new BaseRoute({} as any))) - await vi.waitFor(() => { - expect(router.state.matches.map((match) => match.routeId)).toEqual([ - rootRoute.id, - hotRoute.id, - ]) - expect(router.state.matches[1]!.loaderData).toBeUndefined() - }) - } finally { - restoreWindow() - } - }) - - it('keeps hot loader data when an older refresh settles later', async () => { - let resolveStaleRefresh!: (value: string) => void - const staleRefresh = new Promise<string>((resolve) => { - resolveStaleRefresh = resolve - }) - const oldLoader = vi - .fn<() => string | Promise<string>>() - .mockReturnValueOnce('initial') - .mockReturnValueOnce(staleRefresh) - const newLoader = vi.fn(() => 'hot') - const rootRoute = new BaseRootRoute({ loader: oldLoader }) - const router = createClientTestRouter(rootRoute, '/') - - await router.load() - expect(router.state.matches[0]?.loaderData).toBe('initial') - - const oldRefresh = router.invalidate() - await vi.waitFor(() => expect(oldLoader).toHaveBeenCalledTimes(2)) - - runHandleRouteUpdate( - router, - rootRoute.id, - new BaseRootRoute({ loader: newLoader }), - ) - - await vi.waitFor(() => { - expect(router.state.matches[0]?.loaderData).toBe('hot') - }) - - resolveStaleRefresh('stale') - await oldRefresh - - expect(newLoader).toHaveBeenCalledTimes(1) - expect(router.state.matches[0]!.routeId).toBe(rootRoute.id) - expect(router.state.matches[0]!.loaderData).toBe('hot') - }) - - it('does not cache an obsolete inactive preload that settles after a hot update', async () => { - let resolveOldLoader!: (value: string) => void - const oldLoaderResult = new Promise<string>((resolve) => { - resolveOldLoader = resolve - }) - const oldLoader = vi.fn(() => oldLoaderResult) - const newLoader = vi.fn(() => 'hot') - const rootRoute = new BaseRootRoute({}) - const hotRoute = new BaseRoute({ - getParentRoute: () => asAnyRoute(rootRoute), - path: '/hot', - loader: oldLoader, - preloadStaleTime: Infinity, - }) - const router = createClientTestRouter( - rootRoute.addChildren([asAnyRoute(hotRoute)]), - '/', - ) - - await router.load() - const preload = router.preloadRoute({ to: '/hot' }) - await vi.waitFor(() => expect(oldLoader).toHaveBeenCalledOnce()) - - runHandleRouteUpdate( - router, - hotRoute.id, - new BaseRoute({ loader: newLoader } as any), - ) - - resolveOldLoader('obsolete') - await preload - await router.navigate({ to: '/hot' }) - - expect(newLoader).toHaveBeenCalledOnce() - expect(router.state.matches.at(-1)?.loaderData).toBe('hot') - }) - - it('observes hot parser and route-context changes on the active route', async () => { - const rootRoute = new BaseRootRoute({}) - const itemRoute = new BaseRoute({ - getParentRoute: () => asAnyRoute(rootRoute), - path: '/items/$itemId', - params: { - parse: ({ itemId }: { itemId: string }) => ({ - itemId, - parser: 'old', - }), - }, - context: () => ({ source: 'old' }), - }) - const router = createClientTestRouter( - rootRoute.addChildren([asAnyRoute(itemRoute)]), - '/items/abc', - ) - - await router.load() - expect(router.state.matches[1]!.routeId).toBe(itemRoute.id) - expect(router.state.matches[1]!.params).toEqual({ - itemId: 'abc', - parser: 'old', - }) - expect(router.state.matches[1]!.context).toMatchObject({ source: 'old' }) - - runHandleRouteUpdate( - router, - itemRoute.id, - new BaseRoute({ - params: { - parse: ({ itemId }: { itemId: string }) => ({ - itemId, - parser: 'new', - }), - }, - context: () => ({ source: 'new' }), - } as any), - ) - - await vi.waitFor(() => { - expect(router.state.matches[1]!.routeId).toBe(itemRoute.id) - expect(router.state.matches[1]!.params).toEqual({ - itemId: 'abc', - parser: 'new', - }) - expect(router.state.matches[1]!.context).toMatchObject({ source: 'new' }) - }) - }) - - it('rematerializes descendants when a parent route definition changes', async () => { - const rootRoute = new BaseRootRoute({}) - const parentRoute = new BaseRoute({ - getParentRoute: () => asAnyRoute(rootRoute), - path: '/parent', - context: () => ({ source: 'old' }), - }) - const childRoute = new BaseRoute({ - getParentRoute: () => asAnyRoute(parentRoute), - path: '/child', - context: ({ context }) => ({ inheritedSource: context.source }), - }) - const router = createClientTestRouter( - rootRoute.addChildren([ - parentRoute.addChildren([asAnyRoute(childRoute)]), - ]), - '/parent/child', - ) - - await router.load() - expect(router.state.matches[2]?.context).toMatchObject({ - inheritedSource: 'old', - }) - - runHandleRouteUpdate( - router, - parentRoute.id, - new BaseRoute({ context: () => ({ source: 'new' }) } as any), - ) - - await vi.waitFor(() => { - expect(router.state.matches[2]?.context).toMatchObject({ - inheritedSource: 'new', - }) - }) - }) - - it('does not run removed loader or beforeLoad callbacks on a later visit', async () => { - const beforeLoad = vi.fn(() => ({ hotBeforeLoad: true })) - const loader = vi.fn(() => 'hot loader data') - const rootRoute = new BaseRootRoute({}) - const hotRoute = new BaseRoute({ - getParentRoute: () => asAnyRoute(rootRoute), - path: '/hot', - beforeLoad, - loader, - staleTime: Infinity, - gcTime: Infinity, - }) - const otherRoute = new BaseRoute({ - getParentRoute: () => asAnyRoute(rootRoute), - path: '/other', - }) - const router = createClientTestRouter( - rootRoute.addChildren([asAnyRoute(hotRoute), asAnyRoute(otherRoute)]), - '/hot', - ) - - await router.load() - await router.navigate({ to: '/other' }) - expect(beforeLoad).toHaveBeenCalledTimes(1) - expect(loader).toHaveBeenCalledTimes(1) - - runHandleRouteUpdate(router, hotRoute.id, new BaseRoute({} as any)) - await router.navigate({ to: '/hot' }) - - const match = router.state.matches.find( - (candidate) => candidate.routeId === hotRoute.id, - ) - expect(beforeLoad).toHaveBeenCalledTimes(1) - expect(loader).toHaveBeenCalledTimes(1) - expect(match).toBeDefined() - expect(match!.loaderData).toBeUndefined() - expect(match!.context).not.toHaveProperty('hotBeforeLoad') - }) - - it('removes rendered HeadContent and Scripts output after a hot update', async () => { - const rootRoute = new BaseRootRoute({}) - const hotRoute = new BaseRoute({ - getParentRoute: () => asAnyRoute(rootRoute), - path: '/hot', - head: () => ({ - meta: [{ title: 'hot title' }], - scripts: [{ src: '/hot-head.js' }], - }), - scripts: () => [{ src: '/hot-body.js' }], - }) - const router = createReactClientTestRouter( - rootRoute.addChildren([asAnyRoute(hotRoute)]), - '/hot', - ) - - await router.load() - expect(router.state.matches[1]!).toMatchObject({ - routeId: hotRoute.id, - meta: [{ title: 'hot title' }], - headScripts: [{ src: '/hot-head.js' }], - scripts: [{ src: '/hot-body.js' }], - }) - - const container = document.createElement('div') - document.body.appendChild(container) - const reactRoot = createRoot(container) - const previousActEnvironment = (globalThis as any).IS_REACT_ACT_ENVIRONMENT - ;(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true - onTestFinished(() => { - if (previousActEnvironment === undefined) { - delete (globalThis as any).IS_REACT_ACT_ENVIRONMENT - } else { - ;(globalThis as any).IS_REACT_ACT_ENVIRONMENT = previousActEnvironment - } - }) - onTestFinished(() => { - container.remove() - }) - onTestFinished(async () => { - await act(async () => { - reactRoot.unmount() - }) - }) - - await act(async () => { - reactRoot.render( - createElement(RouterContextProvider, { - router, - children: createElement( - Fragment, - null, - createPortal(createElement(HeadContent), document.head), - createElement(Scripts), - ), - }), - ) - }) - - expect(document.head.querySelector('title')?.textContent).toBe('hot title') - expect( - document.head.querySelector('script[src="/hot-head.js"]'), - ).not.toBeNull() - expect( - document.head.querySelector('script[src="/hot-body.js"]'), - ).not.toBeNull() - - await act(async () => { - runHandleRouteUpdate(router, hotRoute.id, new BaseRoute({} as any)) - await vi.waitFor(() => { - expect(router.state.matches[1]!.routeId).toBe(hotRoute.id) - expect(router.state.matches[1]!.meta).toBeUndefined() - expect(router.state.matches[1]!.headScripts).toBeUndefined() - expect(router.state.matches[1]!.scripts).toBeUndefined() - }) - }) - - expect(document.head.querySelector('title')).toBeNull() - expect(document.head.querySelector('script[src="/hot-head.js"]')).toBeNull() - expect(document.head.querySelector('script[src="/hot-body.js"]')).toBeNull() - }) -}) diff --git a/packages/router-plugin/tests/production-warnings.test.ts b/packages/router-plugin/tests/production-warnings.test.ts deleted file mode 100644 index 1ace6edf50..0000000000 --- a/packages/router-plugin/tests/production-warnings.test.ts +++ /dev/null @@ -1,209 +0,0 @@ -/** - * A production client build ships none of the code splitter's development - * warnings, whatever the build process's `NODE_ENV` (Vitest sets it to - * `test`, which behaves like a shell without it): the bundler's mode - * decides, and webpack and Rspack build in production when `mode` is left - * out. Such a warning would log in every visitor's console, with the - * absolute path of the route file on the build machine. - */ -import { - mkdir, - mkdtemp, - readFile, - readdir, - rm, - writeFile, -} from 'node:fs/promises' -import path from 'node:path' -import { rspack } from '@rsbuild/core' -import webpack from 'webpack' -import { describe, expect, test, vi } from 'vitest' - -const timeout = 60_000 - -/** - * The exported component stays in the route module unless the code splitter - * can split exports; the error component is split either way. - */ -const routeSource = `import { createFileRoute } from '@tanstack/react-router' - -export function ExportedPage() { - return 'MARK_EXPORTED_PAGE' -} - -function ErrorPage() { - return 'MARK_ERROR_PAGE' -} - -export const Route = createFileRoute('/')({ - component: ExportedPage, - errorComponent: ErrorPage, -}) -` - -const rootSource = `import { createRootRoute } from '@tanstack/react-router' -export const Route = createRootRoute({}) -` - -/** Writes `files` into a new app directory inside the package. */ -async function createApp(files: Record<string, string>) { - // Keep the app inside the package so runtime imports resolve. - const root = await mkdtemp(path.join(__dirname, '.production-warnings-')) - await mkdir(path.join(root, 'routes')) - for (const [file, code] of Object.entries(files)) { - await writeFile(path.join(root, file), code) - } - return root -} - -function routerOptions(root: string) { - return { - target: 'react', - routesDirectory: path.join(root, 'routes'), - generatedRouteTree: path.join(root, 'routeTree.gen.ts'), - autoCodeSplitting: true, - } as const -} - -/** A client build of `entry` in `mode` (left out when undefined), unminified. */ -function compilerConfig( - root: string, - entry: string, - mode: 'production' | undefined, -) { - return { - context: root, - ...(mode ? { mode } : {}), - target: 'web', - entry: `./${entry}`, - output: { path: path.join(root, 'dist') }, - optimization: { minimize: false }, - } as const -} - -interface Compiler { - run: ( - callback: ( - error: Error | null, - stats?: { - hasErrors: () => boolean - toString: (options: object) => string - }, - ) => void, - ) => void - close: (callback: (error?: Error | null) => void) => void -} - -/** Runs one build and settles once the compiler has closed. */ -function runCompiler(compiler: Compiler) { - return new Promise<void>((resolve, reject) => { - compiler.run((error, stats) => { - // The test removes the app afterwards: wait for the compiler to finish. - compiler.close((closeError) => { - if (error ?? closeError) { - reject(error ?? closeError) - } else if (stats?.hasErrors()) { - reject(new Error(stats.toString({ all: false, errors: true }))) - } else { - resolve() - } - }) - }) - }) -} - -const bundlers = [ - { - name: 'webpack', - // webpack parses no TypeScript: the router plugin is the only loader. - extension: 'js', - async build(root: string, entry: string, mode: 'production' | undefined) { - const { tanstackRouter } = await import('../src/webpack') - await runCompiler( - webpack({ - ...compilerConfig(root, entry, mode), - // The test app is not part of the package's TypeScript project. - resolve: { tsconfig: false }, - plugins: [tanstackRouter(routerOptions(root))], - }), - ) - }, - }, - { - name: 'rspack', - // As in Rsbuild: SWC compiles the router plugin's output. - extension: 'tsx', - async build(root: string, entry: string, mode: 'production' | undefined) { - const { tanstackRouter } = await import('../src/rspack') - await runCompiler( - rspack({ - ...compilerConfig(root, entry, mode), - module: { - rules: [ - { - test: /\.tsx?$/, - loader: 'builtin:swc-loader', - options: { - jsc: { parser: { syntax: 'typescript', tsx: true } }, - }, - type: 'javascript/auto', - }, - ], - }, - plugins: [tanstackRouter(routerOptions(root))], - }), - ) - }, - }, -] as const - -describe.each(bundlers)('$name build', (bundler) => { - test.each([ - { label: "mode: 'production'", mode: 'production' }, - { label: 'mode left out', mode: undefined }, - ] as const)( - 'with $label, the client JS logs no warning about an exported component', - async ({ mode }) => { - const routeFile = `routes/index.${bundler.extension}` - const entry = `entry.${bundler.extension}` - const root = await createApp({ - [`routes/__root.${bundler.extension}`]: rootSource, - [routeFile]: routeSource, - [entry]: `import { Route } from './${routeFile}'\nglobalThis.route = Route\n`, - }) - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - try { - await bundler.build(root, entry, mode) - const warned = warn.mock.calls.some((args) => - args.some((arg) => String(arg).includes('ExportedPage')), - ) - const dist = path.join(root, 'dist') - const chunks = new Map<string, string>() - for (const file of await readdir(dist)) { - if (file.endsWith('.js')) { - chunks.set(file, await readFile(path.join(dist, file), 'utf8')) - } - } - expect( - chunks.get('main.js'), - 'the error component is split', - ).not.toContain('MARK_ERROR_PAGE') - // An exported component kept in the route module is reported. - const split = !chunks.get('main.js')!.includes('MARK_EXPORTED_PAGE') - expect(split || warned, 'split, or reported by the build').toBe(true) - // The app's directory name appears only in absolute paths. - const linesNamingTheApp = [...chunks].flatMap(([file, code]) => - code - .split('\n') - .filter((line) => line.includes(path.basename(root))) - .map((line) => `${file}: ${line.trim()}`), - ) - expect(linesNamingTheApp).toEqual([]) - } finally { - warn.mockRestore() - await rm(root, { recursive: true, force: true }) - } - }, - timeout, - ) -}) diff --git a/packages/router-plugin/tests/react-refresh-route-components.test.ts b/packages/router-plugin/tests/react-refresh-route-components.test.ts deleted file mode 100644 index b0c14b7d8f..0000000000 --- a/packages/router-plugin/tests/react-refresh-route-components.test.ts +++ /dev/null @@ -1,281 +0,0 @@ -/** - * Route HMR keeps the previous `component` (and the other component options) - * so that React Refresh can patch it in place. That only works when the value - * is bound to a top-level name React Refresh registers. These tests compile - * route files with the HMR transforms, then run Vite's Oxc React Refresh - * transform (the one `@vitejs/plugin-react` uses) on the output to see which - * components are registered and how their hook signatures are computed. - */ -import { describe, expect, it } from 'vitest' -import { - compileRouteModules, - declarationOf, - declaratorName, - evaluateModule, - expectRegisteredRouteOption, - exportedNames, - getRouteOption, - head, - importedNames, - parseModule, - reactRefresh, - topLevelDeclarators, - transformWithRouteHmrPlugin, -} from './regression-helpers' -import type { ESTree } from 'vite' - -/** Compiles every module the code splitter emits, with React HMR. */ -function compileWithCodeSplitting(code: string) { - return compileRouteModules(code, { hmr: true }).modules -} - -describe('React Refresh registers route components', () => { - // Source: React Refresh ReactFreshBabelPlugin-test "registers top-level - // variable declarations with function expressions" and "... with arrow functions" - it.each([ - ['an arrow function', `() => <p>hi</p>`], - ['an anonymous function expression', `function () { return <p>hi</p> }`], - ['a parenthesized arrow function', `(() => <p>hi</p>)`], - ])('written inline as %s', async (_, component) => { - const code = transformWithRouteHmrPlugin( - `${head}export const Route = createFileRoute('/')({ component: ${component} })`, - ) - await expectRegisteredRouteOption(code, 'component') - }) - - it('for every inline component option of a root route, under distinct names', async () => { - const options = { - component: '() => <p>component</p>', - pendingComponent: '() => <p>pending</p>', - errorComponent: '({ error }) => <p>{String(error)}</p>', - notFoundComponent: '() => <p>not found</p>', - shellComponent: '({ children }) => <html><body>{children}</body></html>', - } - const { reference } = compileWithCodeSplitting( - `import { createRootRoute } from '@tanstack/react-router' -export const Route = createRootRoute({ -${Object.entries(options) - .map(([key, value]) => ` ${key}: ${value},`) - .join('\n')} -})`, - ) - const bindings = new Set<string>() - for (const option of Object.keys(options)) { - bindings.add(await expectRegisteredRouteOption(reference!, option)) - } - expect(bindings.size).toBe(Object.keys(options).length) - }) - - // Source: ReactFreshBabelPlugin-test "only registers pascal case functions" - // and "uses original function declaration if it get reassigned" - it.each([ - ['a const arrow function', `const page = () => <p>hi</p>`], - [ - 'a function expression that names itself', - `const page = function page() { return <p>{typeof page}</p> }`, - ], - [ - 'a reassigned function declaration', - `import { connect } from './connect'\nfunction page() { return <p>hi</p> }\npage = connect(page)`, - ], - ])('declared lowercase as %s, by renaming it', async (_, declaration) => { - const code = transformWithRouteHmrPlugin( - `${head}${declaration}\nexport const Route = createFileRoute('/')({ component: page })`, - ) - const binding = await expectRegisteredRouteOption(code, 'component') - expect(binding).toMatch(/^[A-Z]/) - }) - - // Source: ReactFreshBabelPlugin-test "registers top-level exported function - // declarations" and "registers top-level exported named arrow functions" - it.each([ - ['export function page', `export function page() { return <p>hi</p> }`], - ['export { page }', `const page = () => <p>hi</p>\nexport { page }`], - [ - 'export default page', - `function page() { return <p>hi</p> }\nexport default page`, - ], - ])( - 'renamed lowercase and exported (%s), keeping the exports', - async (_, declaration) => { - const source = `${head}${declaration}\nexport const Route = createFileRoute('/')({ component: page })` - const code = transformWithRouteHmrPlugin(source) - await expectRegisteredRouteOption(code, 'component') - expect(exportedNames(code)).toEqual( - expect.arrayContaining(exportedNames(source)), - ) - }, - ) - - // Source: ReactFreshBabelPlugin-test "does not consider require-like methods to be HOCs" - it('but leaves an imported lowercase component to the module that declares it', () => { - const code = transformWithRouteHmrPlugin( - `${head}import { page } from './page' -export const Route = createFileRoute('/')({ component: page })`, - ) - const { value } = getRouteOption(parseModule(code), 'component') - expect((value as ESTree.IdentifierReference).name).toBe('page') - expect(importedNames(code, './page')).toEqual(['page']) - }) - - // Source: ReactFreshBabelPlugin-test "registers top-level function declarations" - it('renames only the component binding, not an inner binding with its name', async () => { - const code = transformWithRouteHmrPlugin( - `${head}function page() { - const page = 'inner-marker' - return <p>{page}</p> -} -export const Route = createFileRoute('/')({ component: page })`, - ) - await expectRegisteredRouteOption(code, 'component') - const { Route } = await evaluateModule(code, { - '@tanstack/react-router': { - createFileRoute: () => (options: unknown) => ({ options }), - }, - }) - expect((Route as any).options.component()).toBe('<p>inner-marker</p>') - }) - - // Source: ReactFreshIntegration-test "preserves state ..." (families are - // matched by registration name) - it('names hoisted components after their option, so adding options keeps the family', async () => { - const before = transformWithRouteHmrPlugin( - `${head}export const Route = createFileRoute('/')({ component: () => <p>v1</p> })`, - ) - const after = transformWithRouteHmrPlugin( - `${head}export const Route = createFileRoute('/')({ - pendingComponent: () => <p>pending</p>, - errorComponent: () => <p>error</p>, - component: () => <p>v2</p>, -})`, - ) - expect(await expectRegisteredRouteOption(after, 'component')).toBe( - await expectRegisteredRouteOption(before, 'component'), - ) - }) - - // Source: ReactFreshBabelPlugin-test "includes custom hooks into the signatures" - it('with the hook signature of the component the user wrote, also in the split chunk', async () => { - const declarations = `import { useState } from 'react' -const format = (n: number) => String(n) -function useCounter() { - const [count] = useState(0) - return format(count) -}` - const component = `() => { - const count = useCounter() - return <p>{count}</p> -}` - const { signatures } = await reactRefresh( - `${declarations}\nconst Page = ${component}\nexport const Route = {}`, - ) - const expected = signatures.get('Page') - expect(expected).toBeDefined() - // The loader shares `format` with the component's hook. - const source = `${head}${declarations} -export const Route = createFileRoute('/')({ - loader: () => format(1), - component: ${component}, -})` - - const hmr = transformWithRouteHmrPlugin(source) - const hoisted = await expectRegisteredRouteOption(hmr, 'component') - expect((await reactRefresh(hmr)).signatures.get(hoisted)).toBe(expected) - - const modules = compileWithCodeSplitting(source) - expect(modules.shared).toMatch(declarationOf('format')) - const chunkSignatures = (await reactRefresh(modules['virtual component']!)) - .signatures - expect([...chunkSignatures.values()]).toContain(expected) - }) -}) - -describe('React Refresh hoisting picks names nothing else uses', () => { - it.each([ - [ - 'a top-level const', - `const TSRComponent = 'taken'`, - `<p>{TSRComponent}</p>`, - ], - ['an import', `import { TSRComponent } from './taken'`, `<TSRComponent />`], - [ - 'a function declared after the route', - ``, - `<p>{TSRComponent()}</p>`, - `\nfunction TSRComponent() { return 'taken' }`, - ], - ])('not a name held by %s', async (_, before, jsx, after = '') => { - const code = transformWithRouteHmrPlugin( - `${head}${before} -export const Route = createFileRoute('/')({ component: () => ${jsx} })${after}`, - ) - // A reused name would redeclare the user's binding (an invalid module). - const binding = await expectRegisteredRouteOption(code, 'component') - expect(binding).not.toBe('TSRComponent') - }) - - it('nor a global the component reads', async () => { - const code = transformWithRouteHmrPlugin( - `${head}export const Route = createFileRoute('/')({ - component: () => <p>{typeof TSRPendingComponent}</p>, - pendingComponent: () => <p>pending</p>, -})`, - ) - const pending = await expectRegisteredRouteOption(code, 'pendingComponent') - expect(pending).not.toBe('TSRPendingComponent') - // `TSRPendingComponent` must stay an unresolved global inside `component`. - expect(code).not.toMatch(declarationOf('TSRPendingComponent')) - }) -}) - -describe('React Refresh hoisting of inline route components', () => { - it('hoists the root route component but not the components of routes a function creates', async () => { - const { reference } = compileWithCodeSplitting(` -import { createRootRoute, createRoute } from '@tanstack/react-router' -export function makeChild(label: string) { - return createRoute({ - getParentRoute: () => Route, - path: label, - component: () => <div>{label}</div>, - }) -} -export const Route = createRootRoute({ component: () => <div /> }) -`) - const program = parseModule(reference!) - // `label` only exists inside `makeChild`; any other top-level statement - // that mentions it reads an undefined global at render time. - const statementsUsingLabel = program.body - .map((statement) => reference!.slice(statement.start, statement.end)) - .filter( - (statement) => - /\blabel\b/.test(statement) && - !statement.includes('function makeChild('), - ) - expect(statementsUsingLabel).toEqual([]) - // React Refresh can only register components bound to top-level names. - await expectRegisteredRouteOption(reference!, 'component') - }) - - it('declares hoisted components before the route that uses them', () => { - // The lowercase `page`, declared in the same statement as `Route`, is - // renamed for React Refresh as well. - const { reference } = compileWithCodeSplitting(` -import { createRootRoute } from '@tanstack/react-router' -export const page = () => <div />, Route = createRootRoute({ - component: page, - pendingComponent: () => <div />, -}) -`) - const program = parseModule(reference!) - const { route, value } = getRouteOption(program, 'pendingComponent') - expect(value.type).toBe('Identifier') - const name = (value as ESTree.IdentifierReference).name - const declaration = topLevelDeclarators(program).find( - (declarator) => declaratorName(declarator) === name, - ) - // A `const` used before its declaration throws a TDZ ReferenceError when - // the route is created. - expect(declaration).toBeDefined() - expect(declaration!.start).toBeLessThan(route.start) - }) -}) diff --git a/packages/router-plugin/tests/regression-helpers.ts b/packages/router-plugin/tests/regression-helpers.ts deleted file mode 100644 index df482ffe78..0000000000 --- a/packages/router-plugin/tests/regression-helpers.ts +++ /dev/null @@ -1,476 +0,0 @@ -/** - * Helpers shared by the code-splitter and route HMR regression suites: compile - * a route file into every module the code splitter emits, drive the bundler - * plugins the way a bundler does, and inspect or evaluate an emitted module. - */ -import { execFile } from 'node:child_process' -import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' -import path from 'node:path' -import { pathToFileURL } from 'node:url' -import { promisify } from 'node:util' -import { build, parseSync, transformWithOxc } from 'vite' -import { expect } from 'vitest' -import { - compileCodeSplitReferenceRoute, - compileCodeSplitSharedRoute, - compileCodeSplitVirtualRoute, - computeSharedBindings, -} from '../src/core/code-splitter/compilers' -import { getFrameworkHmrCompilerPlugins } from '../src/core/code-splitter/plugins/framework-plugins' -import { defaultCodeSplitGroupings } from '../src/core/constants' -import { createRouterCodeSplitterPlugin } from '../src/core/router-code-splitter-plugin' -import { createRouterHmrPlugin } from '../src/core/router-hmr-plugin' -import { createRouterPluginContext } from '../src/core/router-plugin-context' -import { normalizePath } from '../src/core/utils' -import { getModuleErrors } from './validate-module' -import type { Config } from '../src/core/config' -import type { CodeSplitGroupings } from '../src/core/constants' -import type { HmrStyle } from '../src/core/hmr' -import type { TransformResult, UnpluginOptions } from 'unplugin' -import type { ESTree } from 'vite' - -export { declarationOf } from './validate-module' - -export const head = `import { createFileRoute } from '@tanstack/react-router'\n` - -/** - * Compiles a route file with the default groupings into every module the code - * splitter emits for it: `reference`, one `virtual <split>` chunk per grouping - * and, when bindings are shared, `shared`. - */ -export function compileRouteModules( - code: string, - options: { - filename?: string - targetFramework?: 'react' | 'solid' - /** Compile with route HMR and the framework's HMR compiler plugins. */ - hmr?: boolean - } = {}, -) { - const { - filename = 'route.tsx', - targetFramework = 'react', - hmr = false, - } = options - const groupings = defaultCodeSplitGroupings - const compilerPlugins = hmr - ? getFrameworkHmrCompilerPlugins({ targetFramework }) - : undefined - const computed = computeSharedBindings({ - code, - filename, - codeSplitGroupings: groupings, - }) - const sharedBindings = computed.size > 0 ? computed : undefined - const reference = compileCodeSplitReferenceRoute({ - code, - filename, - id: filename, - addHmr: hmr, - codeSplitGroupings: groupings, - targetFramework, - sharedBindings, - compilerPlugins, - }) - const modules: Record<string, string> = { - reference: reference?.code ?? code, - } - for (const targets of groupings) { - const split = targets.join('-') - modules[`virtual ${split}`] = compileCodeSplitVirtualRoute({ - code, - filename: `${filename}?tsr-split=${split}`, - splitTargets: targets, - sharedBindings, - compilerPlugins, - }).code - } - if (sharedBindings) { - modules.shared = compileCodeSplitSharedRoute({ - code, - sharedBindings, - filename: `${filename}?tsr-shared=1`, - }).code - } - return { modules, sharedBindings: [...computed].sort() } -} - -/** Compiles every module of a route file and returns the component chunk. */ -export function componentChunk(code: string) { - return compileRouteModules(code).modules['virtual component']! -} - -/** Asserts that every module is valid, reporting the errors by module name. */ -export async function expectValidModules(modules: Record<string, string>) { - const errors: Record<string, Array<string>> = {} - for (const [name, code] of Object.entries(modules)) { - errors[name] = await getModuleErrors(code) - } - expect(errors).toEqual( - Object.fromEntries(Object.keys(modules).map((name) => [name, []])), - ) -} - -function moduleRecord(code: string) { - return parseSync('module.tsx', code, { sourceType: 'module' }).module -} - -/** Sources a module imports, side-effect imports included, sorted. */ -export function importSources(code: string) { - return [ - ...new Set( - moduleRecord(code).staticImports.map( - (statement) => statement.moduleRequest.value, - ), - ), - ].sort() -} - -/** - * The values a module imports from `source`, sorted: `default`, `*` for a - * namespace import, or the imported name. Type-only specifiers are skipped. - */ -export function importedNames(code: string, source: string) { - return moduleRecord(code) - .staticImports.filter( - (statement) => statement.moduleRequest.value === source, - ) - .flatMap((statement) => - statement.entries - .filter((entry) => !entry.isType) - .map((entry) => - entry.importName.kind === 'Default' - ? 'default' - : entry.importName.kind === 'NamespaceObject' - ? '*' - : entry.importName.name!, - ), - ) - .sort() -} - -/** Value names a module exports (`default` for a default export), sorted. */ -export function exportedNames(code: string) { - return moduleRecord(code) - .staticExports.flatMap((statement) => - statement.entries - .filter((entry) => !entry.isType && entry.exportName.kind !== 'None') - .map((entry) => entry.exportName.name ?? 'default'), - ) - .sort() -} - -/** Absolute, normalized path of a route file in the package's `src/routes`. */ -export function routeFile(name: string) { - return normalizePath(path.join(process.cwd(), `src/routes/${name}.tsx`)) -} - -function runTransform(plugin: UnpluginOptions, code: string, id: string) { - const transform = plugin.transform - if (!transform || typeof transform === 'function') { - throw new Error('Expected object transform') - } - const result = transform.handler.call({} as never, code, id) as - | TransformResult - | null - | undefined - if (!result) { - return null - } - return typeof result === 'string' ? result : result.code -} - -const referencePluginName = - 'tanstack-router:code-splitter:compile-reference-file' -const virtualPluginName = 'tanstack-router:code-splitter:compile-virtual-file' -const sharedPluginName = 'tanstack-router:code-splitter:compile-shared-file' - -/** - * Drives the three code-splitter transforms the way a bundler does, for the - * given route files (absolute path to route id). `configPlugins` are the - * plugins of the resolved Vite config; by default the code splitter itself, - * so its plugin-order check runs. - */ -export async function createCodeSplitterTransforms( - options: Partial<Config>, - routes: Record<string, string>, - configPlugins: Array<{ name: string }> = [{ name: referencePluginName }], -) { - const context = createRouterPluginContext() - for (const [file, routeId] of Object.entries(routes)) { - context.routesByFile.set(file, { routeId }) - } - const plugins = createRouterCodeSplitterPlugin( - { target: 'react', autoCodeSplitting: true, ...options }, - context, - ) - const pluginArray = Array.isArray(plugins) ? plugins : [plugins] - const byName = (name: string) => { - const plugin = pluginArray.find((candidate) => candidate.name === name) - if (!plugin) { - throw new Error(`Code-splitter plugin "${name}" not found`) - } - return plugin - } - const hook = byName(referencePluginName).vite?.configResolved - const config = { - root: process.cwd(), - command: 'build', - plugins: configPlugins, - } as never - if (typeof hook === 'function') { - await hook.call({} as never, config) - } else if (hook) { - await hook.handler.call({} as never, config) - } - return { - reference: (code: string, id: string) => - runTransform(byName(referencePluginName), code, id), - virtual: (code: string, id: string) => - runTransform(byName(virtualPluginName), code, id), - shared: (code: string, id: string) => - runTransform(byName(sharedPluginName), code, id), - } -} - -/** - * Runs the route HMR plugin (used when automatic code splitting is off) on - * the route file `file`, registered under `routeId`. - */ -export function transformWithRouteHmrPlugin( - code: string, - options: Partial<Config> = { target: 'react' }, - route: { file: string; routeId: string } = { - file: routeFile('index'), - routeId: '/', - }, - hmrStyle?: HmrStyle, -) { - const context = createRouterPluginContext() - context.routesByFile.set(route.file, { routeId: route.routeId }) - const plugins = createRouterHmrPlugin(options, context, hmrStyle) - const plugin = Array.isArray(plugins) ? plugins[0]! : plugins - const output = runTransform(plugin, code, route.file) - if (output === null) { - throw new Error('expected the route HMR plugin to transform the route') - } - return output -} - -/** Renders JSX to text: intrinsic elements become tags, components are called. */ -const jsxToText = `const Fragment = Symbol('Fragment') -const h = (type, props, ...children) => { - const text = children.flat(Infinity).filter((c) => c != null && c !== false && c !== true).join('') - if (type === Fragment) { - return text - } - if (typeof type === 'function') { - return type({ ...props, children: text }) - } - if (typeof type !== 'string') { - throw new Error('cannot render ' + String(type)) - } - return '<' + type + '>' + text + '</' + type + '>' -} -` - -const stubsKey = '__regressionModuleStubs' -let evaluations = 0 - -/** - * Evaluates an emitted module like a bundler would: JSX becomes plain calls - * that render to text, and named imports are linked to `stubs`, keyed by - * specifier. Every call evaluates a fresh module instance. - */ -export async function evaluateModule( - code: string, - stubs: Record<string, Record<string, unknown>> = {}, -): Promise<Record<string, (...args: Array<any>) => any>> { - const { code: javascript } = await transformWithOxc(code, 'module.tsx', { - jsx: { runtime: 'classic', pragma: 'h', pragmaFrag: 'Fragment' }, - }) - const key = `${stubsKey}${evaluations++}` - ;(globalThis as Record<string, unknown>)[key] = stubs - // Imports are hoisted: link them before any other statement runs. - const imports: Array<string> = [] - const body = javascript.replace( - /^import\s+\{([^}]*)\}\s+from\s+(["'])(.+?)\2;?$/gm, - (_, named: string, __, source: string) => { - if (!(source in stubs)) { - throw new Error(`no stub for import ${source}`) - } - imports.push( - `const { ${named.replace(/\bas\b/g, ':')} } = globalThis.${key}[${JSON.stringify(source)}];`, - ) - return '' - }, - ) - return import( - /* @vite-ignore */ `data:text/javascript,${encodeURIComponent(`${jsxToText}${imports.join('\n')}\n${body}`)}` - ) -} - -/** - * Applies Vite's Oxc React Refresh transform (the one `@vitejs/plugin-react` - * uses) and returns the registered component names and the hook signature - * arguments of each signed binding. - */ -export async function reactRefresh(code: string) { - const result = await transformWithOxc(code, 'route.tsx', { - jsx: { - runtime: 'automatic', - development: true, - refresh: { emitFullSignatures: true }, - }, - }) - const registered = [ - ...result.code.matchAll(/\$RefreshReg\$\(\w+, "([^"]+)"\)/g), - ].map((match) => match[1]!) - const signatures = new Map( - [...result.code.matchAll(/\b_s\d*\((\w+), ([\s\S]*?)\);\n/g)].map( - (match) => [match[1]!, match[2]!] as const, - ), - ) - return { registered, signatures } -} - -/** Parses a module, asserting that it has no syntax errors. */ -export function parseModule(code: string) { - const { program, errors } = parseSync('route.tsx', code, { - sourceType: 'module', - }) - expect(errors).toEqual([]) - return program -} - -/** Declarators of the top-level variable declarations, exported or not. */ -export function topLevelDeclarators(program: ESTree.Program) { - return program.body.flatMap((statement) => { - const declaration = - statement.type === 'ExportNamedDeclaration' - ? statement.declaration - : statement - return declaration?.type === 'VariableDeclaration' - ? declaration.declarations - : [] - }) -} - -export function declaratorName(declarator: ESTree.VariableDeclarator) { - return declarator.id.type === 'Identifier' ? declarator.id.name : undefined -} - -/** The `Route` declarator and the value of its `option`. */ -export function getRouteOption(program: ESTree.Program, option: string) { - const route = topLevelDeclarators(program).find( - (declarator) => declaratorName(declarator) === 'Route', - ) - const options = - route?.init?.type === 'CallExpression' ? route.init.arguments[0] : null - if (options?.type !== 'ObjectExpression') { - throw new Error('expected `Route` to be created with an options object') - } - const property = options.properties.find( - (candidate) => - candidate.type === 'Property' && - candidate.key.type === 'Identifier' && - candidate.key.name === option, - ) - if (property?.type !== 'Property') { - throw new Error(`expected the \`${option}\` route option`) - } - return { route: route!, value: property.value } -} - -/** Asserts that `option` points to a binding React Refresh registers. */ -export async function expectRegisteredRouteOption( - code: string, - option: string, -) { - expect(await getModuleErrors(code)).toEqual([]) - const { value } = getRouteOption(parseModule(code), option) - expect(value.type).toBe('Identifier') - const binding = (value as ESTree.IdentifierReference).name - expect((await reactRefresh(code)).registered).toContain(binding) - return binding -} - -const runNode = promisify(execFile) - -/** - * Builds a small app with the real Vite plugin (code splitting on, default - * groupings unless `groupings` is given): `routes/index.tsx` holds `route`, - * and `entry.ts` re-exports the route module next to `render(component)`, - * which preloads a component and renders it to a string. `files` adds files - * or replaces `entry.ts`. Then imports the built entry in a separate Node - * process and returns the JSON value returned by `script`, which has the - * entry's exports in scope as `entry`. - */ -export async function buildAndRun( - route: string, - script: string, - options: { - files?: Record<string, string> - groupings?: CodeSplitGroupings - } = {}, -) { - const { tanstackRouter } = await import('../src/vite') - // Keep the temporary app inside the package so real runtime imports resolve. - const root = await mkdtemp(path.join(__dirname, '.regression-build-')) - try { - await mkdir(path.join(root, 'routes')) - const files: Record<string, string> = { - 'routes/__root.tsx': `import { createRootRoute } from '@tanstack/react-router' -export const Route = createRootRoute({})`, - 'routes/index.tsx': route, - 'entry.ts': `import { createElement } from 'react' -import { renderToString } from 'react-dom/server' -export * from './routes/index' -export async function render(component: any) { - await component.preload?.() - return renderToString(createElement(component)) -} -`, - ...options.files, - } - for (const [file, code] of Object.entries(files)) { - await writeFile(path.join(root, file), code) - } - await build({ - root, - configFile: false, - logLevel: 'silent', - plugins: [ - tanstackRouter({ - target: 'react', - routesDirectory: './routes', - generatedRouteTree: './routeTree.gen.ts', - autoCodeSplitting: true, - codeSplittingOptions: { - addHmr: false, - ...(options.groupings && { defaultBehavior: options.groupings }), - }, - }), - ], - build: { - ssr: path.join(root, 'entry.ts'), - outDir: 'dist', - minify: false, - rollupOptions: { - output: { entryFileNames: 'entry.mjs', chunkFileNames: '[name].mjs' }, - }, - }, - }) - const entryUrl = pathToFileURL(path.join(root, 'dist/entry.mjs')).href - const { stdout } = await runNode(process.execPath, [ - '--input-type=module', - '--eval', - `const entry = await import(${JSON.stringify(entryUrl)}) -const result = await (async () => { ${script} })() -process.stdout.write(JSON.stringify(result))`, - ]) - return JSON.parse(stdout) as unknown - } finally { - await rm(root, { recursive: true, force: true }) - } -} diff --git a/packages/router-plugin/tests/router-plugin-context.test.ts b/packages/router-plugin/tests/router-plugin-context.test.ts deleted file mode 100644 index b03e5f6701..0000000000 --- a/packages/router-plugin/tests/router-plugin-context.test.ts +++ /dev/null @@ -1,406 +0,0 @@ -import path from 'node:path' -import * as t from '@babel/types' -import { describe, expect, it, vi } from 'vitest' -import { parseAst } from '@tanstack/router-utils' -import { createRouterCodeSplitterPlugin } from '../src/core/router-code-splitter-plugin' -import { unpluginRouterComposedFactory } from '../src/core/router-composed-plugin' -import { createRouterHmrPlugin } from '../src/core/router-hmr-plugin' -import { createRouterPluginContext } from '../src/core/router-plugin-context' -import { normalizePath } from '../src/core/utils' -import type { Config } from '../src/core/config' -import type { UnpluginOptions, TransformResult } from 'unplugin' - -const referencePluginName = - 'tanstack-router:code-splitter:compile-reference-file' -const virtualPluginName = 'tanstack-router:code-splitter:compile-virtual-file' - -function getCodeSplitterPlugin( - plugins: ReturnType<typeof createRouterCodeSplitterPlugin>, - pluginName: string, -): UnpluginOptions { - const pluginArray = Array.isArray(plugins) ? plugins : [plugins] - const plugin = pluginArray.find((item) => item.name === pluginName) - if (!plugin) { - throw new Error(`Code-splitter plugin "${pluginName}" not found`) - } - return plugin -} - -function getReferencePlugin( - plugins: ReturnType<typeof createRouterCodeSplitterPlugin>, -) { - return getCodeSplitterPlugin(plugins, referencePluginName) -} - -async function configurePlugin( - plugin: UnpluginOptions, - command: 'serve' | 'build' = 'serve', -) { - const hook = plugin.vite?.configResolved - if (!hook) { - return - } - - const config = { - root: process.cwd(), - command, - plugins: [{ name: referencePluginName }], - } as never - - if (typeof hook === 'function') { - await hook.call({} as never, config) - return - } - - await hook.handler.call({} as never, config) -} - -async function transformReferenceRoute( - plugin: UnpluginOptions, - code: string, - id: string, -): Promise<TransformResult | null | undefined> { - const transform = plugin.transform - if (!transform || typeof transform === 'function') { - throw new Error('Expected object transform') - } - return transform.handler.call({} as never, code, id) -} - -function getCode(result: TransformResult | null | undefined) { - if (!result) { - return null - } - if (typeof result === 'string') { - return result - } - return result.code -} - -/** How many times the route module accepts its own hot updates. */ -function countHotAccepts(code: string) { - return code.split('import.meta.hot.accept(').length - 1 -} - -describe('router plugin context', () => { - it('splits parenthesized route factories, option values, and grouping arrays', async () => { - const routeFile = normalizePath( - path.join(process.cwd(), 'src/routes/wrapped.tsx'), - ) - const context = createRouterPluginContext() - context.routesByFile.set(routeFile, { routeId: '/wrapped' }) - const plugins = createRouterCodeSplitterPlugin( - { - target: 'react', - autoCodeSplitting: true, - codeSplittingOptions: { addHmr: false }, - }, - context, - ) - await configurePlugin(getReferencePlugin(plugins), 'build') - const code = `import { createFileRoute } from '@tanstack/react-router' -const Component = () => 'wrapped component' -const loader = () => 'wrapped loader' -export const Route = (createFileRoute('/wrapped'))({ - component: (Component), loader: (loader), - codeSplitGroupings: (([(['component']), (['loader'])])), -})` - const reference = getCode( - await transformReferenceRoute( - getReferencePlugin(plugins), - code, - routeFile, - ), - ) - expect(reference).toContain('lazyRouteComponent') - expect(reference).toContain('lazyFn') - const virtual = getCode( - await transformReferenceRoute( - getCodeSplitterPlugin(plugins, virtualPluginName), - code, - `${routeFile}?tsr-split=component`, - ), - ) - expect(virtual).toContain('wrapped component') - expect(virtual).not.toContain('wrapped loader') - }) - - it('refreshes chunk ownership after source changes and isolates split settings', async () => { - const routeFile = normalizePath( - path.join(process.cwd(), 'src/routes/changing.tsx'), - ) - const source = (name: string, value: string) => ` -import { createFileRoute } from '@tanstack/react-router' -const ${name} = { value: ${JSON.stringify(value)} } -export const Route = createFileRoute('/changing')({ - loader: () => ${name}, - component: () => ${name}.value, -})` - const setup = async (combined: boolean) => { - const context = createRouterPluginContext() - context.routesByFile.set(routeFile, { routeId: '/changing' }) - const plugins = createRouterCodeSplitterPlugin( - { - target: 'react', - autoCodeSplitting: true, - codeSplittingOptions: { - addHmr: false, - defaultBehavior: combined - ? [['component', 'loader']] - : [['component'], ['loader']], - }, - }, - context, - ) - await configurePlugin(getReferencePlugin(plugins), 'build') - return async (code: string) => { - const reference = getCode( - await transformReferenceRoute( - getReferencePlugin(plugins), - code, - routeFile, - ), - )! - const virtual = getCode( - await transformReferenceRoute( - getCodeSplitterPlugin(plugins, virtualPluginName), - code, - `${routeFile}?tsr-split=${combined ? 'component---loader' : 'component'}`, - ), - )! - const shared = getCode( - await transformReferenceRoute( - getCodeSplitterPlugin( - plugins, - 'tanstack-router:code-splitter:compile-shared-file', - ), - code, - `${routeFile}?tsr-shared=1`, - ), - )! - return { reference, virtual, shared } - } - } - const separate = await setup(false) - const combined = await setup(true) - const first = await separate(source('firstState', 'first version')) - expect(first.reference).toContain('tsr-split=component') - const virtualImports = parseAst({ - code: first.virtual, - }).program.body.filter((statement) => t.isImportDeclaration(statement)) - expect(virtualImports).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - source: expect.objectContaining({ - value: expect.stringContaining('tsr-shared'), - }), - specifiers: expect.arrayContaining([ - expect.objectContaining({ - type: 'ImportSpecifier', - imported: expect.objectContaining({ name: 'firstState' }), - local: expect.objectContaining({ name: 'firstState' }), - }), - ]), - }), - ]), - ) - expect(first.shared).toContain('first version') - - const second = await separate(source('secondState', 'second version')) - for (const output of Object.values(second)) { - expect(output).not.toContain('firstState') - } - expect(second.virtual).toContain('secondState') - expect(second.shared).toContain('second version') - const together = await combined(source('secondState', 'second version')) - expect(together.reference).not.toContain('tsr-shared') - expect(together.virtual).toContain('second version') - expect(together.virtual).not.toContain('tsr-shared') - expect(await separate(source('secondState', 'second version'))).toEqual( - second, - ) - }) - - it.each([ - { mode: 'production', production: true }, - { mode: 'development with addHmr disabled', production: false }, - ])( - 'does not run React HMR compiler plugins in $mode', - async ({ production }) => { - const routeFile = normalizePath( - path.join(process.cwd(), 'src/routes/lowercase.tsx'), - ) - const routeCode = ` -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/lowercase')({ component }) - -function component() { - return <div>Hello</div> -} -` - - const context = createRouterPluginContext() - context.routesByFile.set(routeFile, { routeId: '/lowercase' }) - - if (production) { - vi.stubEnv('NODE_ENV', 'production') - } - - try { - const plugins = createRouterCodeSplitterPlugin( - { - target: 'react', - autoCodeSplitting: true, - codeSplittingOptions: production ? undefined : { addHmr: false }, - }, - context, - ) - const referencePlugin = getReferencePlugin(plugins) - const virtualPlugin = getCodeSplitterPlugin(plugins, virtualPluginName) - - await configurePlugin(referencePlugin, production ? 'build' : 'serve') - - const referenceCode = getCode( - await transformReferenceRoute(referencePlugin, routeCode, routeFile), - ) - const virtualCode = getCode( - await transformReferenceRoute( - virtualPlugin, - routeCode, - `${routeFile}?tsr-split=component`, - ), - ) - - expect(referenceCode).not.toContain('TSRFastRefreshAnchor') - expect(virtualCode).toContain('function component()') - expect(virtualCode).toContain('export { component }') - expect(virtualCode).not.toContain('SplitComponent') - } finally { - if (production) { - vi.unstubAllEnvs() - } - } - }, - ) - - it('does not install the standalone route HMR plugin in production', () => { - vi.stubEnv('NODE_ENV', 'production') - - try { - const plugins = unpluginRouterComposedFactory( - { target: 'react', autoCodeSplitting: false }, - { framework: 'vite', versions: {} }, - ) - - const pluginArray = Array.isArray(plugins) ? plugins : [plugins] - expect( - pluginArray.some((plugin) => plugin.name === 'tanstack-router:hmr'), - ).toBe(false) - } finally { - vi.unstubAllEnvs() - } - }) - - it('keeps multiple code-splitter instances isolated by explicit context', async () => { - const routeFile = normalizePath( - path.join(process.cwd(), 'src/routes-a/owned.tsx'), - ) - const otherRouteFile = normalizePath( - path.join(process.cwd(), 'src/routes-b/other.tsx'), - ) - - const routeCode = ` -import { createFileRoute } from '@tanstack/react-router' - -function Component() { - return <div>Hello</div> -} - -export const Route = createFileRoute('/owned')({ - component: Component, -}) -` - - const contextA = createRouterPluginContext() - contextA.routesByFile.set(routeFile, { routeId: '/owned' }) - - const contextB = createRouterPluginContext() - contextB.routesByFile.set(otherRouteFile, { routeId: '/other' }) - - const configA = { - target: 'react', - routesDirectory: './src/routes-a', - generatedRouteTree: './src/routeTree-a.gen.ts', - autoCodeSplitting: true, - } satisfies Partial<Config> - - const configB = { - target: 'react', - routesDirectory: './src/routes-b', - generatedRouteTree: './src/routeTree-b.gen.ts', - autoCodeSplitting: true, - } satisfies Partial<Config> - - const splitterA = getReferencePlugin( - createRouterCodeSplitterPlugin(configA, contextA), - ) - const splitterB = getReferencePlugin( - createRouterCodeSplitterPlugin(configB, contextB), - ) - - await configurePlugin(splitterA) - await configurePlugin(splitterB) - - const firstResult = await transformReferenceRoute( - splitterA, - routeCode, - routeFile, - ) - const firstCode = getCode(firstResult) - - expect(firstCode).not.toBeNull() - expect(countHotAccepts(firstCode!)).toBe(1) - - const secondResult = await transformReferenceRoute( - splitterB, - firstCode!, - routeFile, - ) - - expect(secondResult).toBeNull() - }) - - it('normalizes HMR options before the first transform', async () => { - const routeFile = normalizePath( - path.join(process.cwd(), 'src/routes/owned.tsx'), - ) - - const routeCode = ` -import { createFileRoute } from '@tanstack/react-router' - -function Component() { - return <div>Hello</div> -} - -export const Route = createFileRoute('/owned')({ - component: Component, -}) -` - - const context = createRouterPluginContext() - context.routesByFile.set(routeFile, { routeId: '/owned' }) - - const hmrPlugin = createRouterHmrPlugin({}, context) - const hmrResult = await transformReferenceRoute( - Array.isArray(hmrPlugin) ? hmrPlugin[0]! : hmrPlugin, - routeCode, - routeFile, - ) - - const hmrCode = getCode(hmrResult) - - expect(hmrCode).not.toBeNull() - expect(hmrCode).toContain('TSRFastRefreshAnchor') - }) -}) diff --git a/packages/router-plugin/tests/source-maps.test.ts b/packages/router-plugin/tests/source-maps.test.ts deleted file mode 100644 index 3217dd9aa3..0000000000 --- a/packages/router-plugin/tests/source-maps.test.ts +++ /dev/null @@ -1,322 +0,0 @@ -/** - * Source maps of split routes point at the route file the user wrote: a throw - * in a split component, or in code the route module and a split chunk share, - * maps to its line in the route file, in real webpack and Rspack builds and - * in Vite's dev server, and the map names the route file itself, not the - * `?tsr-split` / `?tsr-shared` module id. Issues #3828 and #6667. - */ -import { - mkdir, - mkdtemp, - readFile, - readdir, - rm, - writeFile, -} from 'node:fs/promises' -import { SourceMap } from 'node:module' -import path from 'node:path' -import { rspack } from '@rsbuild/core' -import { createServer } from 'vite' -import webpack from 'webpack' -import { describe, expect, test } from 'vitest' -import type { SourceMapPayload } from 'node:module' - -const timeout = 60_000 - -/** - * A route whose split component throws, and whose loader and component share - * a function that throws, each on its own line. - */ -function routeSource({ types }: { types: boolean }) { - const never = types ? ': never' : '' - return `import { createFileRoute } from '@tanstack/react-router' - -function fail()${never} { - throw new Error('MARK_SHARED_THROW') -} - -function Page()${never} { - throw new Error('MARK_PAGE_THROW ' + typeof fail) -} - -export const Route = createFileRoute('/')({ - loader: () => fail(), - component: Page, -}) -` -} - -const rootSource = `import { createRootRoute } from '@tanstack/react-router' -export const Route = createRootRoute({}) -` - -/** The 1-based line of `marker` in `code`. */ -function lineOf(code: string, marker: string) { - return code.slice(0, code.indexOf(marker)).split('\n').length -} - -/** - * Where `code`'s source map sends the opening quote of the string `marker`: - * the source as `source` gives it, and the 1-based line. - */ -function originalPositionOf( - code: string, - map: SourceMapPayload, - marker: string, - source: (name: string) => string, -) { - const lines = code.slice(0, code.indexOf(marker) - 1).split('\n') - const entry = new SourceMap(map).findEntry( - lines.length - 1, - lines.at(-1)!.length, - ) - if (!('originalSource' in entry)) { - return undefined - } - return { - source: source(entry.originalSource), - line: entry.originalLine + 1, - } -} - -/** Writes `files` into a new app directory inside the package. */ -async function createApp(files: Record<string, string>) { - // Keep the app inside the package so runtime imports resolve. - const root = await mkdtemp(path.join(__dirname, '.source-maps-')) - await mkdir(path.join(root, 'routes')) - for (const [file, code] of Object.entries(files)) { - await writeFile(path.join(root, file), code) - } - return root -} - -function routerOptions(root: string) { - return { - target: 'react', - routesDirectory: path.join(root, 'routes'), - generatedRouteTree: path.join(root, 'routeTree.gen.ts'), - autoCodeSplitting: true, - codeSplittingOptions: { addHmr: false }, - } as const -} - -/** A client production build of `entry`, unminified, with source maps. */ -function compilerConfig(root: string, entry: string) { - return { - context: root, - mode: 'production', - target: 'web', - devtool: 'source-map', - entry: `./${entry}`, - output: { path: path.join(root, 'dist') }, - optimization: { minimize: false }, - } as const -} - -interface Compiler { - run: ( - callback: ( - error: Error | null, - stats?: { - hasErrors: () => boolean - toString: (options: object) => string - }, - ) => void, - ) => void - close: (callback: (error?: Error | null) => void) => void -} - -/** Runs one build and settles once the compiler has closed. */ -function runCompiler(compiler: Compiler) { - return new Promise<void>((resolve, reject) => { - compiler.run((error, stats) => { - // The test removes the app afterwards: wait for the compiler to finish. - compiler.close((closeError) => { - if (error ?? closeError) { - reject(error ?? closeError) - } else if (stats?.hasErrors()) { - reject(new Error(stats.toString({ all: false, errors: true }))) - } else { - resolve() - } - }) - }) - }) -} - -const bundlers = [ - { - name: 'webpack', - // webpack parses no TypeScript: the router plugin is the only loader. - extension: 'js', - async build(root: string, entry: string) { - const { tanstackRouter } = await import('../src/webpack') - await runCompiler( - webpack({ - ...compilerConfig(root, entry), - // The test app is not part of the package's TypeScript project. - resolve: { tsconfig: false }, - plugins: [tanstackRouter(routerOptions(root))], - }), - ) - }, - }, - { - name: 'rspack', - // As in Rsbuild: SWC compiles the router plugin's output. - extension: 'tsx', - async build(root: string, entry: string) { - const { tanstackRouter } = await import('../src/rspack') - await runCompiler( - rspack({ - ...compilerConfig(root, entry), - module: { - rules: [ - { - test: /\.tsx?$/, - loader: 'builtin:swc-loader', - options: { - jsc: { parser: { syntax: 'typescript', tsx: true } }, - }, - type: 'javascript/auto', - }, - ], - }, - plugins: [tanstackRouter(routerOptions(root))], - }), - ) - }, - }, -] as const - -describe.each(bundlers)('$name build', (bundler) => { - test( - 'a throw in a split component, and in code it shares, maps to its line in the route file', - async () => { - const route = routeSource({ types: bundler.extension === 'tsx' }) - const routeFile = `routes/index.${bundler.extension}` - const entry = `entry.${bundler.extension}` - const root = await createApp({ - [`routes/__root.${bundler.extension}`]: rootSource, - [routeFile]: route, - [entry]: `import { Route } from './${routeFile}'\nglobalThis.route = Route\n`, - }) - try { - await bundler.build(root, entry) - const dist = path.join(root, 'dist') - const chunks = new Map<string, string>() - for (const file of await readdir(dist)) { - if (file.endsWith('.js')) { - chunks.set(file, await readFile(path.join(dist, file), 'utf8')) - } - } - for (const marker of ['MARK_PAGE_THROW', 'MARK_SHARED_THROW']) { - const [file, code] = - [...chunks].find(([, chunk]) => chunk.includes(marker)) ?? [] - expect(file, `the chunk holding ${marker}`).toBeDefined() - if (marker === 'MARK_PAGE_THROW') { - expect(file, 'the component is split').not.toBe('main.js') - } - const map = JSON.parse( - await readFile(path.join(dist, `${file}.map`), 'utf8'), - ) as SourceMapPayload - expect( - originalPositionOf(code!, map, marker, (source) => - source.replace(/^webpack:\/\/[^/]*\/\.\//, ''), - ), - `${marker} in ${file}`, - ).toEqual({ source: routeFile, line: lineOf(route, marker) }) - } - } finally { - await rm(root, { recursive: true, force: true }) - } - }, - timeout, - ) -}) - -function inlineSourceMap(code: string) { - const data = - /\/\/# sourceMappingURL=data:application\/json;(?:charset=utf-8;)?base64,(\S+)\s*$/.exec( - code, - )?.[1] - expect(data, 'the module has an inline source map').toBeDefined() - return JSON.parse( - Buffer.from(data!, 'base64').toString('utf8'), - ) as SourceMapPayload -} - -/** - * The route module served at `routeUrl` and every module derived from it - * (imports of the route file's path with a query), by URL. - */ -async function routeModules(routeUrl: URL) { - const modules = new Map<string, string>() - const pending = [routeUrl.href] - while (pending.length > 0) { - const url = pending.pop()! - if (modules.has(url)) { - continue - } - const code = await (await fetch(url)).text() - modules.set(url, code) - for (const [, specifier] of code.matchAll(/["']([^"'\s]+)["']/g)) { - const derived = new URL(specifier!, url) - if (derived.pathname === routeUrl.pathname && derived.search) { - pending.push(derived.href) - } - } - } - return modules -} - -describe('vite dev', () => { - test( - 'the modules of a split route map a throw to its line in the route file, which their maps name as their source', - async () => { - const route = routeSource({ types: true }) - const root = await createApp({ - 'routes/__root.tsx': rootSource, - 'routes/index.tsx': route, - }) - const { tanstackRouter } = await import('../src/vite') - const server = await createServer({ - root, - configFile: false, - logLevel: 'silent', - plugins: [tanstackRouter(routerOptions(root))], - optimizeDeps: { noDiscovery: true, include: [] }, - server: { port: 0, hmr: false, ws: false }, - }) - try { - await server.listen() - const routeUrl = new URL( - '/routes/index.tsx', - server.resolvedUrls!.local[0], - ) - const modules = await routeModules(routeUrl) - for (const marker of ['MARK_PAGE_THROW', 'MARK_SHARED_THROW']) { - const [url, code] = - [...modules].find(([, module]) => module.includes(marker)) ?? [] - expect(url, `the module holding ${marker}`).toBeDefined() - if (marker === 'MARK_PAGE_THROW') { - expect(url, 'the component is split').not.toBe(routeUrl.href) - } - expect( - originalPositionOf( - code!, - inlineSourceMap(code!), - marker, - (source) => new URL(source, url).href, - ), - `${marker} in ${url}`, - ).toEqual({ source: routeUrl.href, line: lineOf(route, marker) }) - } - } finally { - await server.close() - await rm(root, { recursive: true, force: true }) - } - }, - timeout, - ) -}) diff --git a/packages/router-plugin/tests/utils.test.ts b/packages/router-plugin/tests/utils.test.ts index 530880858e..c19ab27e6a 100644 --- a/packages/router-plugin/tests/utils.test.ts +++ b/packages/router-plugin/tests/utils.test.ts @@ -1,22 +1,14 @@ import * as babel from '@babel/core' +import * as t from '@babel/types' import { parseAst } from '@tanstack/router-utils' import { describe, expect, it } from 'vitest' import { + getObjectPropertyKeyName, getUniqueProgramIdentifier, normalizePath, - routeFactoryCallCodeFilter, } from '../src/core/utils' -import type * as t from '@babel/types' import type { NodePath } from '@babel/core' -function matchesRouteFactoryCallCodeFilter(code: string) { - return routeFactoryCallCodeFilter.some((pattern) => { - const result = pattern.test(code) - pattern.lastIndex = 0 - return result - }) -} - function getProgramPath(code: string): NodePath<t.Program> { const ast = parseAst({ code }) let programPath: NodePath<t.Program> | undefined @@ -108,34 +100,39 @@ describe('getUniqueProgramIdentifier', () => { }) }) -describe('routeFactoryCallCodeFilter', () => { - it('matches route factory calls with TypeScript type arguments', () => { - expect( - matchesRouteFactoryCallCodeFilter( - 'createRootRouteWithContext<MyContext>()({})', - ), - ).toBe(true) +describe('getObjectPropertyKeyName', () => { + it('returns identifier keys', () => { + const prop = t.objectProperty(t.identifier('component'), t.identifier('x')) + + expect(getObjectPropertyKeyName(prop)).toBe('component') }) - it('matches route factory calls without TypeScript type arguments', () => { - expect( - matchesRouteFactoryCallCodeFilter('createRootRouteWithContext()({})'), - ).toBe(true) - expect(matchesRouteFactoryCallCodeFilter('createRootRoute({})')).toBe(true) - expect( - matchesRouteFactoryCallCodeFilter("createFileRoute('/posts')({})"), - ).toBe(true) + it('returns string literal keys', () => { + const prop = t.objectProperty( + t.stringLiteral('errorComponent'), + t.identifier('x'), + ) + + expect(getObjectPropertyKeyName(prop)).toBe('errorComponent') }) - it('matches route factory calls with whitespace before invocation', () => { - expect( - matchesRouteFactoryCallCodeFilter( - 'createRootRouteWithContext <MyContext>()({})', - ), - ).toBe(true) - expect(matchesRouteFactoryCallCodeFilter('createRootRoute ({})')).toBe(true) - expect( - matchesRouteFactoryCallCodeFilter("createFileRoute ('/posts')({})"), - ).toBe(true) + it('returns undefined for computed identifier keys', () => { + const prop = t.objectProperty( + t.identifier('component'), + t.identifier('x'), + true, + ) + + expect(getObjectPropertyKeyName(prop)).toBeUndefined() + }) + + it('returns undefined for computed member expression keys', () => { + const prop = t.objectProperty( + t.memberExpression(t.identifier('foo'), t.identifier('bar')), + t.identifier('x'), + true, + ) + + expect(getObjectPropertyKeyName(prop)).toBeUndefined() }) }) diff --git a/packages/router-plugin/tests/validate-module.ts b/packages/router-plugin/tests/validate-module.ts deleted file mode 100644 index 4e0884a436..0000000000 --- a/packages/router-plugin/tests/validate-module.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { stripVTControlCharacters } from 'node:util' -import { parseSync, transformWithOxc } from 'vite' - -/** - * Validates generated code the way a browser or bundler sees it, without using - * the compiler's own parser: erase TypeScript (keeping every value import) and - * parse the result as a JavaScript module with semantic checks. This rejects - * syntax errors, nameless function/class declarations, duplicate bindings - * (including an import redeclared by a local declaration) and exports of - * undeclared bindings. - * - * @returns the error messages; an empty array means the module is valid. - */ -export async function getModuleErrors( - code: string, - filename = 'module.tsx', -): Promise<Array<string>> { - let javascript: string - try { - const result = await transformWithOxc(code, filename, { - jsx: 'preserve', - typescript: { onlyRemoveTypeImports: true }, - }) - javascript = result.code - } catch (error) { - return [stripVTControlCharacters((error as Error).message)] - } - const { errors } = parseSync('module.jsx', javascript, { - sourceType: 'module', - showSemanticErrors: true, - }) - return errors.map((error) => error.message) -} - -/** Matches a declaration of `name` in generated code, however it is printed. */ -export function declarationOf(name: string): RegExp { - return new RegExp(String.raw`\b(?:const|let|var|function|class)\s+${name}\b`) -} diff --git a/packages/router-plugin/tsconfig.build.json b/packages/router-plugin/tsconfig.build.json deleted file mode 100644 index 92be18587f..0000000000 --- a/packages/router-plugin/tsconfig.build.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "rootDir": "./src" - }, - "include": ["src"] -} diff --git a/packages/router-plugin/tsconfig.json b/packages/router-plugin/tsconfig.json index 0e74c8c099..37d21ef6ca 100644 --- a/packages/router-plugin/tsconfig.json +++ b/packages/router-plugin/tsconfig.json @@ -3,7 +3,6 @@ "include": ["src", "vite.config.ts", "tests"], "exclude": ["tests/**/test-files/**", "tests/**/snapshots/**"], "compilerOptions": { - "jsx": "react-jsx", - "types": ["node"] + "jsx": "react-jsx" } } diff --git a/packages/router-plugin/vite.config.ts b/packages/router-plugin/vite.config.ts index e80f073d21..80c007b8cd 100644 --- a/packages/router-plugin/vite.config.ts +++ b/packages/router-plugin/vite.config.ts @@ -14,10 +14,8 @@ const config = defineConfig({ export default mergeConfig( config, tanstackViteConfig({ - tsconfigPath: './tsconfig.build.json', entry: [ './src/index.ts', - './src/context.ts', './src/vite.ts', './src/rspack.ts', './src/webpack.ts', diff --git a/packages/router-ssr-query-core/AGENTS.md b/packages/router-ssr-query-core/AGENTS.md deleted file mode 100644 index 76d3fe022f..0000000000 --- a/packages/router-ssr-query-core/AGENTS.md +++ /dev/null @@ -1,9 +0,0 @@ -# SSR query integration - -Register QueryClient teardown at SSR attachment, before loading/dehydration can fail. The transport subscribes after initial dehydration. Render completion flushes pending queries, unsubscribes, and closes the stream. Request cleanup also clears the QueryClient, including canceled streams and late dehydration results; preserve these distinct lifecycles in `tests/index.test.ts`. - -For query retention or cleanup changes, enable the GC tests that normal unit runs skip. `RUN_SSR_GC_TESTS=1` configures forked workers with exposed GC. Bypass Nx cache so a previous run with the gate disabled cannot count as validation. - -```sh -RUN_SSR_GC_TESTS=1 CI=1 NX_DAEMON=false pnpm nx run-many -p @tanstack/router-ssr-query-core -t test:unit --skipRemoteCache --skipNxCache -- tests/index.test.ts -``` diff --git a/packages/router-ssr-query-core/CHANGELOG.md b/packages/router-ssr-query-core/CHANGELOG.md index 6ab0afbabe..6e45255763 100644 --- a/packages/router-ssr-query-core/CHANGELOG.md +++ b/packages/router-ssr-query-core/CHANGELOG.md @@ -1,59 +1,5 @@ # @tanstack/router-ssr-query-core -## 1.169.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 `<Scripts>` 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 `<Await>` without a `fallback` no longer holds the streamed shell; it renders inside the nearest `<Suspense>` 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. - -## 1.169.2 - -### Patch Changes - -- [#8175](https://github.com/TanStack/router/pull/8175) [`79e3533`](https://github.com/TanStack/router/commit/79e35335b4bb1c3b5e2275a8df5181aa05036628) - Dehydrate only queries for SSR transport, preserve pending-query promises, batch render-time query streaming, and clean up request-owned QueryClient resources. - -## 1.169.1 - -### Patch Changes - -- [#7497](https://github.com/TanStack/router/pull/7497) [`d1997b6`](https://github.com/TanStack/router/commit/d1997b66d7c24c1d64772bb8bab5caf9c6d9cc48) - fix streaming - -## 1.169.0 - -### Minor Changes - -- Clean minor bump, fresh start ([#7395](https://github.com/TanStack/router/pull/7395)) - -## 1.168.0 - -### Minor Changes - -- Add support for custom `dehydrateOptions` and `hydrateOptions` in the SSR query integration ([#7246](https://github.com/TanStack/router/pull/7246)) - -## 1.167.1 - -### Patch Changes - -- migrate createStore > createAtom for simpler API ([#7150](https://github.com/TanStack/router/pull/7150)) - ## 1.167.0 ### Minor Changes diff --git a/packages/router-ssr-query-core/INTERNALS.md b/packages/router-ssr-query-core/INTERNALS.md deleted file mode 100644 index 7439cb10aa..0000000000 --- a/packages/router-ssr-query-core/INTERNALS.md +++ /dev/null @@ -1,456 +0,0 @@ -# Internals of SSR Query Integration - -## Purpose - -This package connects server-side rendering (SSR) in TanStack Router to a TanStack Query `QueryClient`. - -The integration sends the initial Query state with Router dehydration data. It sends render-time queries through a `ReadableStream`. - -The React, Solid, and Vue packages call the same core function. This document gives details of that shared implementation. - -Query Core details refer to version `5.102.0`, which this workspace installs. A newer version of Query Core can change these details. - -The package accepts `@tanstack/query-core >=5.102.0`. - -## Supported Lifecycle - -The supported lifecycle has this order: - -1. The application creates a Router and a request-owned `QueryClient`. -2. The application calls `setupCoreRouterSsrQueryIntegration`. -3. Router attaches the server SSR utilities. -4. Router loads the routes. -5. The request handler calls `serverSsr.dehydrate()`. -6. Seroval starts to serialize Router data, Query data, promises, and streams. -7. The framework renders the application. -8. A framework adapter or Router stream transform reports render completion. -9. Router releases the resources for the request. - -The supported use requires integration setup before Router attaches the server SSR utilities. The usual `getRouter()` flow obeys this requirement. - -The one-time `onServerSsrAttach` event lets the integration register Query cleanup for the request. - -Standard Router and Start handlers call `serverSsr.dehydrate()` one time. Router enforces this lifecycle and rejects a second completed call. - -Direct dehydration calls occur sequentially in the supported lifecycle. - -## Transport Shape - -The integration adds one `query` property to the Router dehydration data: - -```ts -type DehydratedRouterQueryState = { - query: { - initial?: Array<DehydratedQuery> - stream: ReadableStream<Array<DehydratedQuery>> - } -} -``` - -The `query` property groups the Query transport data. The `stream` property is always present in data that the client receives. - -When available, `initial` contains an array of queries from initial dehydration. - -The integration adds `initial` only when initial dehydration selects one or more queries. - -The transport contains Query entries exclusively. - -`RouterSsrQueryOptions.dehydrateOptions` keeps the `DehydrateOptions` type from Query Core. - -The transport uses `shouldDehydrateQuery`, `serializeData`, and `shouldRedactErrors` from these options. - -Each initial entry and each stream entry has the `DehydratedQuery` shape. - -Thus, the initial payload and all stream chunks use the same query data shape. - -Router serializes the stream and pending promises with Seroval. The browser receives a separate reconstructed `ReadableStream`. - -Server request cleanup controls the lifetime of the server stream. - -## Server Setup - -The server branch keeps the dehydration function that Router already has. The integration calls this function first. - -Then the integration reads the Query cache and calls `dehydrateQuery` for each selected query. - -Query writes from the Router function can enter the initial Query state. - -The integration adds an `onServerSsrAttach` listener. This listener registers Query cleanup before Router loads the routes. - -A redirect or loader error before dehydration can stop the request. The cleanup listener clears the request-owned `QueryClient`. - -`shouldDehydrateAllQueries` is the fallback Query filter. - -This filter selects every Query status, including `pending`. An explicit filter or a Query filter in the current defaults replaces this fallback. - -## Initial Dehydration - -Initial dehydration uses the usual precedence of TanStack Query options: - -- The explicit `dehydrateOptions.shouldDehydrateQuery` filter -- The Query filter in the default options at that time -- The `shouldDehydrateAllQueries` fallback. - -The integration uses the first available filter. - -The integration selects this filter after it awaits the Router dehydration function. Thus, changes to Query defaults in that function apply. - -At the same time, the integration selects `serializeData` and `shouldRedactErrors`. Explicit options have priority over the current Query defaults. - -The integration uses these selected options for the initial queries and the Query stream. - -The initial Query state can contain completed queries and pending queries. A selected pending query can contain an active retryer promise. - -For every selected pending query, `dehydrateQuery` adds the `promise` property. - -An active retryer supplies the property value. An inactive retryer supplies `undefined`. - -The integration calls `dehydrateQuery` for each selected query. This preserves query state, pending promises, `meta`, and `queryType`. - -The initial loop records each selected query hash in `sentQueries`. - -The integration associates each hash with its first transported query version for the request. - -After the initial Query state exists, the integration creates the Query stream. Then it subscribes before framework rendering starts. - -When one or more initial queries exist, the returned `query.initial` contains the initial Query state. - -The selected payload contains Query state and can contain `meta` and `queryType`. - -The application configures general Query options and cache configuration separately. - -The stream remains present for render-time queries. - -## Stream State - -`QueryStreamState` owns these active server resources: - -- The stream controller -- The set of sent query hashes -- The function that unsubscribes from the Query cache -- The optional pending-query map. - -`streamState` contains one full `QueryStreamState` object or `undefined`. The `undefined` value represents an inactive Query stream. - -This type keeps all active stream resources together. The controller and unsubscribe function always exist together. - -`finalizeQueryStream` sets `streamState` to `undefined`. Then it unsubscribes from the Query cache. - -If `finalizeQueryStream` receives an error, the function puts the stream in an error state. Otherwise, the function closes the stream. - -A cancelled stream is already terminal. Finalization still removes the Query cache subscription and releases the stream state. - -A queued microtask sees the inactive state after finalization and exits. - -## Query Selection - -The Query cache can emit multiple events for one query. The integration stores one `Query` reference for each hash. - -The pending-query map removes duplicate events in one batch. The set of sent query hashes removes duplicate transport across all payloads. - -Query can install its promise after the first cache event. - -The next applicable event exposes `event.query.promise`. The integration then adds the query to the pending-query map. - -The stream path dehydrates the stored `Query` references directly. Its work is proportional to the selected render-time queries. - -A larger Query cache increases the work that direct dehydration of stored `Query` references avoids. - -## Stream Filter - -The stream path uses the `shouldDehydrateQuery` filter that initial dehydration selected. - -The stream path uses the `serializeData` and `shouldRedactErrors` values that initial dehydration selected. - -The selected filter, serialization function, and error-redaction function stay fixed for the stream lifetime. - -Query Core uses `shouldRedactErrors` for a dehydrated pending promise that later rejects. Existing `state.error` values retain their original value. - -## Batching - -The first eligible event creates the pending-query map. The integration queues one microtask for that map. - -More applicable events can occur before the microtask operates. These events enter the same map and the same stream chunk. - -The microtask dehydrates the queries before a timer callback runs. - -Thus, dehydration occurs before React continues the related Suspense boundaries. - -The React E2E suite examines final server-origin values and Query payload placement before the Router serialization-end marker. - -The core unit test examines array batching directly. - -`flushPendingQueries` removes the pending-query map first. Then the function dehydrates the stored queries. - -A query that settles after this flush can create a new pending-query map. This map produces a new stream chunk. - -`flushPendingQueries` sends one array when one or more queries pass the stream filter. - -## Render Completion - -The integration registers `finishRendering` with `serverSsr.onRenderFinished`. A framework adapter or Router stream transform reports render completion. - -`finishRendering` calls `flushPendingQueries` synchronously and supersedes the scheduled microtask. - -Then `finishRendering` removes the Query cache subscription. Finally, it closes the Query stream. - -If streamed dehydration fails, the integration removes the subscription. Then the integration puts the stream in an error state. - -Request cleanup clears the `QueryClient` after render completion. - -Seroval serialization can continue after rendering completes. A transformed streaming response waits for application output and Router serialization. - -This streaming path can transport Query output that Seroval produces after render completion. - -Built-in string renderers use the HTML buffered at render completion. Then they release the request resources. - -Transport output depends on filters, first-hash selection, errors, aborts, and lifetime limits. - -## Request Cleanup - -Request cleanup sets `cleanedUp` to `true`. Then cleanup removes the Query cache subscription. - -Then cleanup closes the Query stream. - -Cleanup releases the pending-query map and its unflushed data. - -Finally, cleanup calls `QueryClient.clear()`. This call removes the cache entries for the request. - -Query removal clears GC timers. It cancels active retryers. It also aborts the query-function signal. - -A query function that obeys the signal stops after the abort. - -SSR must use a request-owned Router and `QueryClient`. Setup occurs one time for this request-owned pair. - -A request-owned client isolates the request data and cleanup. - -A reused integrated Router keeps `cleanedUp` set to `true`. Subsequent Query dehydration from that Router returns `undefined`. - -Cleanup can occur before the Router dehydration function completes. An aborted request is one cause of this race. - -The integration uses a `finally` block around the Router dehydration function. - -The block clears entries that the Router dehydration function creates after cleanup. - -If cleanup occurs first and Router dehydration succeeds, the integration returns `undefined`. - -If Router dehydration fails, the error propagates. If cleanup starts first, cleanup takes priority over successful dehydration data. - -## Client Hydration - -The client branch first awaits the hydration function that Router already has. Then it restores the initial Query cache synchronously. - -It passes the query-only object `{ queries: query.initial }` to Query Core. - -Then the integration gets the stream reader. Then it schedules the first read. - -Router hydration resolves after reader setup. Stream chunks and transported pending promises continue independently. - -If the stream buffer contains the first chunk, chunk hydration can occur before Router resumes. Otherwise, Router can resume before the chunk arrives. - -The reader processes one chunk at a time. It wraps each chunk as `{ queries: value }` for `hydrateQueryClient`. - -The reader starts the next read after it hydrates the current chunk. The reader is the only reader for this stream. - -The reader holds the stream lock for the lifetime of the read chain. - -If a read or chunk hydration fails, the reader stops. The integration writes `Error reading query stream:` and the error to the console. - -## Pending Promise Hydration - -A pending query can contain a serialized promise. Query Core first examines that promise for an inline result. - -Router reconstructs a native promise. Thus, Router normally reports the promise result asynchronously. - -If the timestamp and cache-state tests pass, Query Core can use an unresolved promise as `initialPromise`. - -The first fetch attempt uses that transported promise. A rejected promise can enter normal retry behavior. - -A subsequent retry can call an available query function. - -An active retryer supplies the transported promise. - -For an `undefined` promise value, a later client fetch uses the available query function. - -## Redirect Errors - -The integration enables client redirect handling by default. The client branch installs these handlers. - -The client branch installs redirect handlers on the QueryClient caches. It preserves all other cache configuration. - -Redirect handlers operate after Query Core completes its retry process. They store the Router location at that time in `error.options._fromLocation`. - -Then the integration resolves the redirect. Then it calls `router.navigate`. - -The redirect path uses the integration handler in place of the previous cache error function. - -`handleRedirects: false` preserves the original error functions for both caches. - -## Error Paths - -An error from the Router dehydration function propagates before Query stream creation. - -An error during initial Query dehydration also propagates to Router. Router request cleanup then clears the request-owned `QueryClient`. - -If streamed dehydration fails, the integration puts the stream in an error state. Finalization also removes the Query cache subscription. - -An initial hydration error rejects Router hydration. This category includes an error from initial Router or Query hydration. - -After the read chain starts, a stream read error only writes a console error. A chunk hydration error has the same behavior. - -An accepted pending-promise rejection uses Query retry and cache error behavior after Router hydration resolves. - -Query Core consults `shouldRedactErrors` when a dehydrated pending promise rejects. - -Only `false` preserves the original rejection error. Other values cause `Error('redacted')`. - -## Ownership Boundaries - -This package owns these resources: - -- The Query cache subscription for the render phase -- The set of sent query hashes -- The pending-query map -- The controller for the server Query stream -- The cleanup action for the request-owned `QueryClient`. - -Router core owns these resources: - -- Seroval serialization of streams and promises -- `ServerSsr` listener dispatch and cleanup idempotence -- Backpressure, cancellation, and lifetime limits for the transformed stream. - -TanStack Start or `createRequestHandler` owns the standard request order and request-signal connection. - -Framework adapters and the Router stream transform report render completion. The host runtime owns the HTTP connection. - -The application owns `QueryClient` creation. SSR must use a new `QueryClient` for each request. - -## Assumptions - -These assumptions are necessary for the implementation: - -- Setup occurs before server SSR attachment. -- Standard handlers call `serverSsr.dehydrate()` one time. -- Direct dehydration calls occur sequentially. -- Initial Query dehydration callbacks complete before cleanup starts. -- The first transported query version for each hash is sufficient for the request. - -These assumptions keep the lifecycle small. The component that defines each lifecycle rule controls that rule. - -## Core Test Coverage - -The core unit tests cover these behaviors: - -- Explicit serialization and filtering for initial and streamed dehydration -- Explicit deserialization for initial and streamed hydration -- Default transport of pending queries and their promises -- Query-only initial cache access -- Creation and removal of the Query cache subscription -- Cleanup during asynchronous dehydration -- Same-turn batching from stored `Query` references -- A default serializer changed after setup -- A streamed serialization error -- Cleanup during an active render-time query -- Cleanup after Query stream cancellation -- Cleanup before dehydration -- Query cancellation during cleanup -- Cleanup registration during server SSR attachment. - -Additional validation can cover these behaviors: - -- Duplicate-hash suppression after transport -- `shouldRedactErrors` -- Redirect handling -- Errors from a detached client stream -- Cleanup from an HTTP request abort -- Terminal serialization for built-in string rendering -- Cleanup that starts inside an initial dehydration callback -- Reuse of an integrated Router. - -## E2E Coverage - -The E2E suite for the React Query integration includes an awaited loader query and an unawaited loader query. - -The suite also covers render-time `useSuspenseQuery`. In its plain `useQuery` case, the browser calls the query function. - -The Solid and Vue suites include the two loader cases and loader-prefetched `useQuery`. - -These suites examine final server-origin or client-origin values. - -The React query-heavy suite includes nine render-time `useSuspenseQuery` calls. Three queries return immediately. - -Six queries return after delays. - -The suite examines server-origin values, browser hydration, and client navigation. - -It also finds the `slow-async-3` payload before Router emits the `$_TSR.e()` serialization-end marker. - -One emitted script with `.next(` contains all three immediate values. Script buffering can combine more than one Seroval operation. - -The script assertion provides serialization-placement evidence. The core unit test provides direct array-batching evidence. - -## Performance Tests - -`tests/dehydrate.bench.ts` first compares the output of two dehydration methods. It removes `dehydratedAt` from the comparison because this value changes. - -Then it compares full-cache filtering with direct query-reference dehydration. The cache sizes are 10, 100, 1,000, and 10,000 queries. - -`tests/server-lifecycle.bench.ts` measures six synthetic operations: - -- Stream creation and closure -- Query cache subscription and removal -- Setup and cleanup before dehydration -- Setup and dehydration for an empty request -- One hundred `setQueryData` writes in a baseline `QueryClient` -- One hundred `setQueryData` writes with the integration. - -The lifecycle benchmark measures these synthetic operations directly. - -These benchmarks provide informational measurements. - -## Maintainer Commands - -After a Query Core update, reexamine this document. - -Do the core unit tests from the repository root: - -```sh -CI=1 NX_DAEMON=false pnpm nx run @tanstack/router-ssr-query-core:test:unit --outputStyle=stream --skipRemoteCache -- tests/index.test.ts -``` - -Do the optional GC test with the Nx local cache disabled: - -```sh -RUN_SSR_GC_TESTS=1 CI=1 NX_DAEMON=false pnpm nx run @tanstack/router-ssr-query-core:test:unit --outputStyle=stream --skipRemoteCache --skipNxCache -- tests/index.test.ts -``` - -Do the performance tests: - -```sh -CI=1 NX_DAEMON=false pnpm nx run @tanstack/router-ssr-query-core:test:perf --outputStyle=stream --skipRemoteCache -``` - -Do the E2E tests for the React Query integration: - -```sh -CI=1 NX_DAEMON=false pnpm nx run tanstack-react-start-e2e-query-integration:test:e2e --outputStyle=stream --skipRemoteCache -``` - -Do the E2E tests for the Solid Query integration: - -```sh -CI=1 NX_DAEMON=false pnpm nx run tanstack-solid-start-e2e-query-integration:test:e2e --outputStyle=stream --skipRemoteCache -``` - -Do the E2E tests for the Vue Query integration: - -```sh -CI=1 NX_DAEMON=false pnpm nx run tanstack-vue-start-e2e-query-integration:test:e2e --outputStyle=stream --skipRemoteCache -``` - -Do the E2E tests for the React query-heavy suite: - -```sh -CI=1 NX_DAEMON=false pnpm nx run tanstack-react-start-e2e-streaming-ssr:test:e2e --outputStyle=stream --skipRemoteCache -- tests/query-heavy.spec.ts -``` diff --git a/packages/router-ssr-query-core/package.json b/packages/router-ssr-query-core/package.json index 8254eaae81..bac7f01c8c 100644 --- a/packages/router-ssr-query-core/package.json +++ b/packages/router-ssr-query-core/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/router-ssr-query-core", - "version": "1.169.3", + "version": "1.167.0", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", @@ -27,16 +27,14 @@ "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": "node ../../node_modules/typescript59/lib/tsc.js", - "test:types:ts60": "tsc6", - "test:types:ts70": "tsc", - "test:unit": "vitest", + "test:types:ts59": "tsc", + "test:unit": "exit 0; vitest", "test:unit:dev": "pnpm run test:unit --watch", - "test:perf": "vitest bench", - "test:perf:dev": "pnpm run test:perf --watch --hideSkippedTests", "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", "build": "vite build" }, @@ -66,18 +64,12 @@ "node": ">=20.19" }, "devDependencies": { - "@tanstack/router-core": "workspace:*", - "@tanstack/query-core": ">=5.102.0", - "vite": "catalog:", - "@tanstack/vite-config": "catalog:", - "vitest": "catalog:", - "jsdom": "catalog:", - "@arethetypeswrong/cli": "catalog:", - "publint": "catalog:", - "rimraf": "catalog:" + "@tanstack/router-core": ">=1.168.0", + "@tanstack/query-core": ">=5.90.0", + "vite": "*" }, "peerDependencies": { - "@tanstack/router-core": ">=1.171.28", - "@tanstack/query-core": ">=5.102.0" + "@tanstack/router-core": ">=1.127.0", + "@tanstack/query-core": ">=5.90.0" } } diff --git a/packages/router-ssr-query-core/src/index.ts b/packages/router-ssr-query-core/src/index.ts index a36eeddba1..4549804660 100644 --- a/packages/router-ssr-query-core/src/index.ts +++ b/packages/router-ssr-query-core/src/index.ts @@ -1,33 +1,18 @@ import { - dehydrateQuery, - hydrate as hydrateQueryClient, + dehydrate as queryDehydrate, + hydrate as queryHydrate, } from '@tanstack/query-core' import { isRedirect } from '@tanstack/router-core' import { isServer } from '@tanstack/router-core/isServer' import type { AnyRouter } from '@tanstack/router-core' import type { - DehydrateOptions, - HydrateOptions, - Query, QueryClient, + DehydratedState as QueryDehydratedState, } from '@tanstack/query-core' -type DehydratedQuery = ReturnType<typeof dehydrateQuery> - -const shouldDehydrateAllQueries = () => true - -type QueryStreamState = { - controller: ReadableStreamDefaultController<Array<DehydratedQuery>> - sentQueries: Set<string> - unsubscribe: () => void - pendingQueries?: Map<string, Query> -} - export type RouterSsrQueryOptions<TRouter extends AnyRouter> = { router: TRouter queryClient: QueryClient - dehydrateOptions?: DehydrateOptions - hydrateOptions?: HydrateOptions /** * If `true`, the QueryClient will handle errors thrown by `redirect()` inside of mutations and queries. @@ -39,251 +24,171 @@ export type RouterSsrQueryOptions<TRouter extends AnyRouter> = { } type DehydratedRouterQueryState = { - query: { - initial?: Array<DehydratedQuery> - stream: ReadableStream<Array<DehydratedQuery>> - } + dehydratedQueryClient?: QueryDehydratedState + queryStream: ReadableStream<QueryDehydratedState> } export function setupCoreRouterSsrQueryIntegration<TRouter extends AnyRouter>({ router, queryClient, - dehydrateOptions, - hydrateOptions, handleRedirects = true, }: RouterSsrQueryOptions<TRouter>) { + const ogHydrate = router.options.hydrate + const ogDehydrate = router.options.dehydrate + if (isServer ?? router.isServer) { - const originalDehydrate = router.options.dehydrate - let streamState: QueryStreamState | undefined - let cleanedUp = false + const sentQueries = new Set<string>() + const queryStream = createPushableStream() + let unsubscribe: (() => void) | undefined = undefined + router.options.dehydrate = + async (): Promise<DehydratedRouterQueryState> => { + router.serverSsr!.onRenderFinished(() => { + queryStream.close() + unsubscribe?.() + unsubscribe = undefined + }) + const ogDehydrated = await ogDehydrate?.() - const finalizeQueryStream = (failure?: { error: unknown }) => { - const state = streamState - streamState = undefined - if (!state) { - return - } - - state.unsubscribe() - - try { - if (failure) { - state.controller.error(failure.error) - } else { - state.controller.close() - } - } catch { - // The stream consumer can already have cancelled the stream. - } - } - - const teardown = () => { - cleanedUp = true - finalizeQueryStream() - // Clearing destroys queries, aborts in-flight work, and cancels gcTime - // handles that would otherwise retain request state for up to 5 minutes. - queryClient.clear() - } - - // Register teardown as soon as SSR attaches. attachRouterServerSsrUtils() - // runs before router.load(), so this covers redirects/errors thrown before - // router.options.dehydrate() can run. - router.serverSsrLifecycle = { - ...router.serverSsrLifecycle, - onServerSsrAttach: [ - ...(router.serverSsrLifecycle?.onServerSsrAttach ?? []), - (serverSsr) => serverSsr.onCleanup(teardown), - ], - } - - router.options.dehydrate = async (): Promise< - DehydratedRouterQueryState | undefined - > => { - let originalDehydrated: Awaited< - ReturnType<NonNullable<typeof originalDehydrate>> - > - try { - originalDehydrated = await originalDehydrate?.() - } finally { - if (cleanedUp) { - queryClient.clear() - } - } - - if (cleanedUp) { - return - } - - const currentDehydrateOptions = queryClient.getDefaultOptions().dehydrate - const shouldDehydrateQuery = - dehydrateOptions?.shouldDehydrateQuery ?? - currentDehydrateOptions?.shouldDehydrateQuery ?? - shouldDehydrateAllQueries - const serializeData = - dehydrateOptions?.serializeData ?? - currentDehydrateOptions?.serializeData - const shouldRedactErrors = - dehydrateOptions?.shouldRedactErrors ?? - currentDehydrateOptions?.shouldRedactErrors - const initialQueries = new Array<DehydratedQuery>() - const sentQueries = new Set<string>() - - for (const query of queryClient.getQueryCache().getAll()) { - if (shouldDehydrateQuery(query)) { - initialQueries.push( - dehydrateQuery(query, serializeData, shouldRedactErrors), - ) - sentQueries.add(query.queryHash) - } - } - - let controller!: ReadableStreamDefaultController<Array<DehydratedQuery>> - const stream = new ReadableStream<Array<DehydratedQuery>>({ - start(value) { - controller = value - }, - }) - const flushPendingQueries = () => { - const state = streamState - const queries = state?.pendingQueries - if (!state || !queries) { - return - } - state.pendingQueries = undefined - - const dehydratedQueries = new Array<DehydratedQuery>() - - for (const query of queries.values()) { - if ( - state.sentQueries.has(query.queryHash) || - !shouldDehydrateQuery(query) - ) { - continue - } - - dehydratedQueries.push( - dehydrateQuery(query, serializeData, shouldRedactErrors), - ) - state.sentQueries.add(query.queryHash) + const dehydratedRouter = { + ...ogDehydrated, + // prepare the stream for queries coming up during rendering + queryStream: queryStream.stream, } - if (dehydratedQueries.length > 0) { - state.controller.enqueue(dehydratedQueries) - } - } - const unsubscribe = queryClient.getQueryCache().subscribe((event) => { - const state = streamState - if (!state) { - return - } - if ( - state.sentQueries.has(event.query.queryHash) || - // The promise is not set yet for the first query-cache event. - !event.query.promise - ) { - return - } - - if (!state.pendingQueries) { - state.pendingQueries = new Map() - // Flush before React resumes resolved Suspense boundaries while - // still batching queries that settle in the same turn. - queueMicrotask(() => { - try { - flushPendingQueries() - } catch (error) { - finalizeQueryStream({ error }) - } + const dehydratedQueryClient = queryDehydrate(queryClient) + if (dehydratedQueryClient.queries.length > 0) { + dehydratedQueryClient.queries.forEach((query) => { + sentQueries.add(query.queryHash) }) + dehydratedRouter.dehydratedQueryClient = dehydratedQueryClient } - state.pendingQueries.set(event.query.queryHash, event.query) - }) - streamState = { controller, sentQueries, unsubscribe } - const finishRendering = () => { - try { - flushPendingQueries() - } catch (error) { - finalizeQueryStream({ error }) - return - } - finalizeQueryStream() + return dehydratedRouter } - router.serverSsr!.onRenderFinished(finishRendering) - return { - ...originalDehydrated, - query: { - ...(initialQueries.length > 0 && { - initial: initialQueries, - }), - stream, - }, - } - } - return - } - const originalHydrate = router.options.hydrate - router.options.hydrate = async (dehydrated: DehydratedRouterQueryState) => { - const query = dehydrated.query - try { - await originalHydrate?.(dehydrated) + const ogClientOptions = queryClient.getDefaultOptions() + queryClient.setDefaultOptions({ + ...ogClientOptions, + dehydrate: { + shouldDehydrateQuery: () => true, + ...ogClientOptions.dehydrate, + }, + }) - if (query.initial) { - hydrateQueryClient( - queryClient, - { queries: query.initial }, - hydrateOptions, + unsubscribe = queryClient.getQueryCache().subscribe((event) => { + // before rendering starts, we do not stream individual queries + // instead we dehydrate the entire query client in router's dehydrate() + // if attachRouterServerSsrUtils() has not been called yet, `router.serverSsr` will be undefined and we also do not stream + if (!router.serverSsr?.isDehydrated()) { + return + } + if (sentQueries.has(event.query.queryHash)) { + return + } + // promise not yet set on the query, so we cannot stream it yet + if (!event.query.promise) { + return + } + if (queryStream.isClosed()) { + console.warn( + `tried to stream query ${event.query.queryHash} after stream was already closed`, ) + return + } + sentQueries.add(event.query.queryHash) + queryStream.enqueue( + queryDehydrate(queryClient, { + shouldDehydrateQuery: (query) => { + if (query.queryHash === event.query.queryHash) { + return ( + ogClientOptions.dehydrate?.shouldDehydrateQuery?.(query) ?? true + ) + } + return false + }, + }), + ) + }) + // on the client + } else { + router.options.hydrate = async (dehydrated: DehydratedRouterQueryState) => { + await ogHydrate?.(dehydrated) + // hydrate the query client with the dehydrated data (if it was dehydrated on the server) + if (dehydrated.dehydratedQueryClient) { + queryHydrate(queryClient, dehydrated.dehydratedQueryClient) } - } catch (error) { - void query.stream.cancel(error).catch(() => {}) - throw error - } - const reader = query.stream.getReader() - void (async () => { - try { - for (;;) { - const { done, value } = await reader.read() + // read the query stream and hydrate the queries as they come in + const reader = dehydrated.queryStream.getReader() + reader + .read() + .then(async function handle({ done, value }) { + queryHydrate(queryClient, value) if (done) { return } - hydrateQueryClient(queryClient, { queries: value }, hydrateOptions) - } - } catch (error) { - console.error('Error reading query stream:', error) - void reader.cancel(error).catch(() => {}) - } finally { - reader.releaseLock() - } - })() - } - if (handleRedirects) { - const originalMutationCacheConfig = queryClient.getMutationCache().config - queryClient.getMutationCache().config = { - ...originalMutationCacheConfig, - onError: (error, ...rest) => { - if (isRedirect(error)) { - error.options._fromLocation = router.stores.location.get() - return router.navigate(router.resolveRedirect(error).options) - } - - return originalMutationCacheConfig.onError?.(error, ...rest) - }, + const result = await reader.read() + return handle(result) + }) + .catch((err) => { + console.error('Error reading query stream:', err) + }) } + if (handleRedirects) { + const ogMutationCacheConfig = queryClient.getMutationCache().config + queryClient.getMutationCache().config = { + ...ogMutationCacheConfig, + onError: (error, ...rest) => { + if (isRedirect(error)) { + error.options._fromLocation = router.stores.location.state + return router.navigate(router.resolveRedirect(error).options) + } - const originalQueryCacheConfig = queryClient.getQueryCache().config - queryClient.getQueryCache().config = { - ...originalQueryCacheConfig, - onError: (error, ...rest) => { - if (isRedirect(error)) { - error.options._fromLocation = router.stores.location.get() - return router.navigate(router.resolveRedirect(error).options) - } + return ogMutationCacheConfig.onError?.(error, ...rest) + }, + } - return originalQueryCacheConfig.onError?.(error, ...rest) - }, + const ogQueryCacheConfig = queryClient.getQueryCache().config + queryClient.getQueryCache().config = { + ...ogQueryCacheConfig, + onError: (error, ...rest) => { + if (isRedirect(error)) { + error.options._fromLocation = router.stores.location.state + return router.navigate(router.resolveRedirect(error).options) + } + + return ogQueryCacheConfig.onError?.(error, ...rest) + }, + } } } } + +type PushableStream = { + stream: ReadableStream + enqueue: (chunk: unknown) => void + close: () => void + isClosed: () => boolean + error: (err: unknown) => void +} + +function createPushableStream(): PushableStream { + let controllerRef: ReadableStreamDefaultController + const stream = new ReadableStream({ + start(controller) { + controllerRef = controller + }, + }) + let _isClosed = false + + return { + stream, + enqueue: (chunk) => controllerRef.enqueue(chunk), + close: () => { + controllerRef.close() + _isClosed = true + }, + isClosed: () => _isClosed, + error: (err: unknown) => controllerRef.error(err), + } +} diff --git a/packages/router-ssr-query-core/tests/dehydrate.bench.ts b/packages/router-ssr-query-core/tests/dehydrate.bench.ts deleted file mode 100644 index 7f9dfeb9b6..0000000000 --- a/packages/router-ssr-query-core/tests/dehydrate.bench.ts +++ /dev/null @@ -1,89 +0,0 @@ -// @vitest-environment node - -import { QueryClient, dehydrate, dehydrateQuery } from '@tanstack/query-core' -import { afterAll, describe, expect, test } from 'vitest' -import type { Query } from '@tanstack/query-core' - -type DehydratedQuery = ReturnType<typeof dehydrateQuery> - -let benchmarkSink = 0 - -describe.each([ - { cachedQueryCount: 10, selectedQueryCount: 1 }, - { cachedQueryCount: 100, selectedQueryCount: 10 }, - { cachedQueryCount: 1_000, selectedQueryCount: 10 }, - { cachedQueryCount: 10_000, selectedQueryCount: 10 }, -])( - 'dehydrate $selectedQueryCount of $cachedQueryCount cached queries', - ({ cachedQueryCount, selectedQueryCount }) => { - const queryClient = new QueryClient() - - for (let index = 0; index < cachedQueryCount; index++) { - queryClient.setQueryData(['query', index], `data-${index}`) - } - - const selectedQueries = new Map<string, Query>() - for ( - let index = cachedQueryCount - selectedQueryCount; - index < cachedQueryCount; - index++ - ) { - const query = queryClient.getQueryCache().find({ - queryKey: ['query', index], - })! - selectedQueries.set(query.queryHash, query) - } - const selectedQueryHashes = new Set(selectedQueries.keys()) - - const scannedQueries = dehydrate(queryClient, { - shouldDehydrateQuery: (query) => selectedQueryHashes.has(query.queryHash), - }).queries - const directlyDehydratedQueries = Array.from( - selectedQueries.values(), - (query) => dehydrateQuery(query), - ) - - expect(directlyDehydratedQueries.map(comparableQuery)).toEqual( - scannedQueries.map(comparableQuery), - ) - - afterAll(() => queryClient.clear()) - - test('filter full query cache', async ({ bench }) => { - await bench('filter full query cache', () => { - const dehydratedQueries = dehydrate(queryClient, { - shouldDehydrateQuery: (query) => - selectedQueryHashes.has(query.queryHash), - }).queries - benchmarkSink = consumeQueries(dehydratedQueries) - }).run() - }) - - test('dehydrate direct query references', async ({ bench }) => { - await bench('dehydrate direct query references', () => { - const dehydratedQueries = new Array<DehydratedQuery>() - for (const query of selectedQueries.values()) { - dehydratedQueries.push(dehydrateQuery(query)) - } - benchmarkSink = consumeQueries(dehydratedQueries) - }).run() - }) - }, -) - -function comparableQuery({ dehydratedAt: _, ...query }: DehydratedQuery) { - return query -} - -function consumeQueries(queries: Array<DehydratedQuery>) { - let value = 0 - for (const query of queries) { - value += (query.dehydratedAt ?? 0) + query.queryHash.length - if (typeof query.state.data === 'string') { - value += query.state.data.length - } - } - return value -} - -void benchmarkSink diff --git a/packages/router-ssr-query-core/tests/index.test.ts b/packages/router-ssr-query-core/tests/index.test.ts deleted file mode 100644 index af76a7579f..0000000000 --- a/packages/router-ssr-query-core/tests/index.test.ts +++ /dev/null @@ -1,781 +0,0 @@ -import { QueryClient } from '@tanstack/query-core' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { setupCoreRouterSsrQueryIntegration } from '../src' - -type TestRouter = { - isServer: boolean - options: { - dehydrate?: () => unknown | Promise<unknown> - hydrate?: (dehydrated: any) => unknown | Promise<unknown> - } - serverSsr?: { - onRenderFinished: (listener: () => void) => void - onCleanup: (listener: () => void) => void - } - serverSsrLifecycle?: { - onServerSsrAttach: Array< - (serverSsr: NonNullable<TestRouter['serverSsr']>) => void - > - } -} - -function createServerRouter() { - const renderFinishedListeners = new Array<() => void>() - const cleanupListeners = new Array<() => void>() - let cleanedUp = false - const serverSsr = { - onRenderFinished: (listener: () => void) => { - if (!cleanedUp) { - renderFinishedListeners.push(listener) - } - }, - onCleanup: (listener: () => void) => { - if (!cleanedUp) { - cleanupListeners.push(listener) - } - }, - } - const router: TestRouter = { - isServer: true, - options: {}, - } - - return { - router, - attachServerSsr() { - router.serverSsr = serverSsr - router.serverSsrLifecycle?.onServerSsrAttach.forEach((listener) => { - listener(serverSsr) - }) - }, - finishRender() { - if (!cleanedUp) { - renderFinishedListeners.splice(0).forEach((listener) => listener()) - } - }, - triggerCleanup() { - if (cleanedUp) { - return - } - cleanedUp = true - cleanupListeners.splice(0).forEach((listener) => listener()) - renderFinishedListeners.length = 0 - router.serverSsr = undefined - }, - } -} - -async function readStream<T>(stream: ReadableStream<T>): Promise<Array<T>> { - const reader = stream.getReader() - const chunks = new Array<T>() - - while (true) { - const result = await reader.read() - if (result.done) { - return chunks - } - chunks.push(result.value) - } -} - -function createDeferred<T>() { - let resolve!: (value: T) => void - const promise = new Promise<T>((res) => { - resolve = res - }) - return { promise, resolve } -} - -function createDehydratedQueryState(data: string) { - return { - data, - dataUpdateCount: 1, - dataUpdatedAt: 1, - error: null, - errorUpdateCount: 0, - errorUpdatedAt: 0, - fetchFailureCount: 0, - fetchFailureReason: null, - fetchMeta: null, - fetchStatus: 'idle' as const, - isInvalidated: false, - status: 'success' as const, - } -} - -const trackedQueryClients = new Set<QueryClient>() -function track<T extends QueryClient>(client: T): T { - trackedQueryClients.add(client) - return client -} - -afterEach(() => { - vi.restoreAllMocks() - for (const client of trackedQueryClients) { - client.clear() - } - trackedQueryClients.clear() -}) - -describe('setupCoreRouterSsrQueryIntegration', () => { - it('uses custom dehydration options for initial and streamed queries', async () => { - const queryClient = track( - new QueryClient({ - defaultOptions: { - dehydrate: { shouldDehydrateQuery: () => false }, - }, - }), - ) - const { router, attachServerSsr, finishRender, triggerCleanup } = - createServerRouter() - - setupCoreRouterSsrQueryIntegration({ - router: router as any, - queryClient, - dehydrateOptions: { - serializeData: (data) => `${data}-serialized`, - shouldDehydrateQuery: (query) => - !String(query.queryKey[0]).startsWith('skip'), - }, - }) - attachServerSsr() - queryClient.setQueryData(['include'], 'initial') - queryClient.setQueryData(['skip'], 'ignored') - - const dehydrated = (await router.options.dehydrate?.()) as { - query: { - initial?: Array<{ - queryKey: Array<unknown> - state: { data: unknown } - }> - stream: ReadableStream< - Array<{ queryKey: Array<unknown>; state: { data: unknown } }> - > - } - } - - expect(dehydrated.query.initial).toMatchObject([ - { queryKey: ['include'], state: { data: 'initial-serialized' } }, - ]) - - const streamedQueriesPromise = readStream(dehydrated.query.stream) - const includedDeferred = createDeferred<string>() - const skippedDeferred = createDeferred<string>() - const included = queryClient.fetchQuery({ - queryKey: ['streamed'], - queryFn: () => includedDeferred.promise, - }) - const skipped = queryClient.fetchQuery({ - queryKey: ['skip-streamed'], - queryFn: () => skippedDeferred.promise, - }) - - includedDeferred.resolve('next') - skippedDeferred.resolve('ignored') - await Promise.all([included, skipped]) - finishRender() - - expect(await streamedQueriesPromise).toMatchObject([ - [{ queryKey: ['streamed'], state: { data: 'next-serialized' } }], - ]) - triggerCleanup() - }) - - it('dehydrates pending queries by default', async () => { - const queryClient = track(new QueryClient()) - const { router, attachServerSsr, finishRender, triggerCleanup } = - createServerRouter() - const queryStarted = createDeferred<void>() - const queryData = createDeferred<string>() - - setupCoreRouterSsrQueryIntegration({ - router: router as any, - queryClient, - }) - attachServerSsr() - const pendingQuery = queryClient.fetchQuery({ - queryKey: ['pending'], - queryFn: () => { - queryStarted.resolve() - return queryData.promise - }, - }) - await queryStarted.promise - - const dehydrated = (await router.options.dehydrate?.()) as { - query: { - initial: Array<{ - promise?: Promise<unknown> - queryKey: Array<unknown> - state: { status: string } - }> - stream: ReadableStream<Array<unknown>> - } - } - - expect(dehydrated.query.initial).toMatchObject([ - { queryKey: ['pending'], state: { status: 'pending' } }, - ]) - expect(dehydrated.query.initial[0]?.promise).toBeInstanceOf(Promise) - - const streamedQueriesPromise = readStream(dehydrated.query.stream) - queryData.resolve('data') - await pendingQuery - finishRender() - - expect(await streamedQueriesPromise).toEqual([]) - triggerCleanup() - }) - - it('uses custom hydration options for initial and streamed queries', async () => { - const queryClient = track(new QueryClient()) - const router: TestRouter = { isServer: false, options: {} } - const stream = new ReadableStream({ - start(controller) { - controller.enqueue([ - { - queryHash: '["streamed"]', - queryKey: ['streamed'], - state: createDehydratedQueryState('stream'), - }, - { - queryHash: '["streamed-batch"]', - queryKey: ['streamed-batch'], - state: createDehydratedQueryState('batch'), - }, - ]) - controller.close() - }, - }) - - setupCoreRouterSsrQueryIntegration({ - router: router as any, - queryClient, - hydrateOptions: { - defaultOptions: { - deserializeData: (data) => `${String(data)}-hydrated`, - }, - }, - }) - await router.options.hydrate?.({ - query: { - initial: [ - { - queryHash: '["initial"]', - queryKey: ['initial'], - state: createDehydratedQueryState('initial'), - }, - ], - stream, - }, - }) - await Promise.resolve() - await Promise.resolve() - - expect(queryClient.getQueryData(['initial'])).toBe('initial-hydrated') - expect(queryClient.getQueryData(['streamed'])).toBe('stream-hydrated') - expect(queryClient.getQueryData(['streamed-batch'])).toBe('batch-hydrated') - expect(stream.locked).toBe(false) - }) - - it('releases a failed query stream reader', async () => { - const queryClient = track(new QueryClient()) - const router: TestRouter = { isServer: false, options: {} } - const error = new Error('stream failed') - const stream = new ReadableStream<Array<never>>({ - start(controller) { - controller.error(error) - }, - }) - const consoleError = vi - .spyOn(console, 'error') - .mockImplementation(() => undefined) - - setupCoreRouterSsrQueryIntegration({ - router: router as any, - queryClient, - }) - await router.options.hydrate?.({ query: { stream } }) - await vi.waitFor(() => { - expect(stream.locked).toBe(false) - }) - - expect(consoleError).toHaveBeenCalledWith( - 'Error reading query stream:', - error, - ) - }) - - it('cancels the query stream when hydration fails', async () => { - const queryClient = track(new QueryClient()) - const router: TestRouter = { isServer: false, options: {} } - const error = new Error('hydration failed') - const cancel = vi.fn(() => new Promise<void>(() => {})) - const stream = new ReadableStream({ - start(controller) { - controller.enqueue([ - { - queryHash: '["streamed"]', - queryKey: ['streamed'], - state: createDehydratedQueryState('stream'), - }, - ]) - }, - cancel, - }) - const consoleError = vi - .spyOn(console, 'error') - .mockImplementation(() => undefined) - - setupCoreRouterSsrQueryIntegration({ - router: router as any, - queryClient, - hydrateOptions: { - defaultOptions: { - deserializeData: () => { - throw error - }, - }, - }, - }) - await router.options.hydrate?.({ query: { stream } }) - await vi.waitFor(() => { - expect(cancel).toHaveBeenCalledWith(error) - expect(stream.locked).toBe(false) - }) - - expect(consoleError).toHaveBeenCalledWith( - 'Error reading query stream:', - error, - ) - }) - - it('cancels the query stream when initial hydration fails', async () => { - const queryClient = track(new QueryClient()) - const router: TestRouter = { isServer: false, options: {} } - const error = new Error('initial hydration failed') - const cancel = vi.fn(() => new Promise<void>(() => {})) - const stream = new ReadableStream({ cancel }) - - setupCoreRouterSsrQueryIntegration({ - router: router as any, - queryClient, - hydrateOptions: { - defaultOptions: { - deserializeData: () => { - throw error - }, - }, - }, - }) - await expect( - router.options.hydrate?.({ - query: { - initial: [ - { - queryHash: '["initial"]', - queryKey: ['initial'], - state: createDehydratedQueryState('initial'), - }, - ], - stream, - }, - }), - ).rejects.toBe(error) - - expect(cancel).toHaveBeenCalledWith(error) - expect(stream.locked).toBe(false) - }) - - it('subscribes after initial dehydration and releases after rendering', async () => { - const queryClient = track(new QueryClient()) - const { router, attachServerSsr, finishRender, triggerCleanup } = - createServerRouter() - - setupCoreRouterSsrQueryIntegration({ - router: router as any, - queryClient, - }) - expect(queryClient.getQueryCache().hasListeners()).toBe(false) - - attachServerSsr() - const dehydrated = (await router.options.dehydrate?.()) as { - query: { stream: ReadableStream<Array<unknown>> } - } - expect(queryClient.getQueryCache().hasListeners()).toBe(true) - - const streamedQueriesPromise = readStream(dehydrated.query.stream) - finishRender() - expect(await streamedQueriesPromise).toEqual([]) - expect(queryClient.getQueryCache().hasListeners()).toBe(false) - triggerCleanup() - }) - - it('does not read or dehydrate mutations during initial dehydration', async () => { - const shouldDehydrateMutation = vi.fn(() => true) - const queryClient = track( - new QueryClient({ - defaultOptions: { - dehydrate: { shouldDehydrateMutation }, - }, - }), - ) - const { router, attachServerSsr, finishRender, triggerCleanup } = - createServerRouter() - const getAllMutations = vi.spyOn(queryClient.getMutationCache(), 'getAll') - - queryClient.getMutationCache().build( - queryClient, - { mutationKey: ['paused'] }, - { - context: undefined, - data: undefined, - error: null, - failureCount: 0, - failureReason: null, - isPaused: true, - status: 'pending', - variables: undefined, - submittedAt: 1, - }, - ) - queryClient.setQueryData(['query'], 'data') - setupCoreRouterSsrQueryIntegration({ - router: router as any, - queryClient, - }) - attachServerSsr() - - const dehydrated = (await router.options.dehydrate?.()) as { - query: { - initial: Array<{ queryKey: Array<unknown> }> - stream: ReadableStream<Array<unknown>> - } - } - const streamedQueriesPromise = readStream(dehydrated.query.stream) - finishRender() - - expect(dehydrated.query.initial).toMatchObject([{ queryKey: ['query'] }]) - expect(getAllMutations).not.toHaveBeenCalled() - expect(shouldDehydrateMutation).not.toHaveBeenCalled() - expect(await streamedQueriesPromise).toEqual([]) - triggerCleanup() - }) - - it('returns no query data when cleanup occurs during dehydration', async () => { - const queryClient = track(new QueryClient()) - const { router, attachServerSsr, triggerCleanup } = createServerRouter() - const deferred = createDeferred<void>() - - router.options.dehydrate = async () => { - await deferred.promise - queryClient.setQueryData(['late'], 'data') - return { original: true } - } - setupCoreRouterSsrQueryIntegration({ - router: router as any, - queryClient, - }) - attachServerSsr() - - const dehydrating = router.options.dehydrate?.() - triggerCleanup() - deferred.resolve() - - await expect(dehydrating).resolves.toBeUndefined() - expect(queryClient.getQueryCache().getAll()).toEqual([]) - expect(queryClient.getQueryCache().hasListeners()).toBe(false) - }) - - it('batches same-turn query settlements without scanning the cache', async () => { - const queryClient = track(new QueryClient()) - const { router, attachServerSsr, finishRender, triggerCleanup } = - createServerRouter() - - setupCoreRouterSsrQueryIntegration({ - router: router as any, - queryClient, - }) - attachServerSsr() - const dehydrated = (await router.options.dehydrate?.()) as { - query: { - stream: ReadableStream< - Array<{ queryHash: string; queryKey: Array<unknown> }> - > - } - } - const getAll = vi.spyOn(queryClient.getQueryCache(), 'getAll') - const streamedQueriesPromise = readStream(dehydrated.query.stream) - const firstDeferred = createDeferred<string>() - const secondDeferred = createDeferred<string>() - const laterDeferred = createDeferred<string>() - - const first = queryClient.fetchQuery({ - queryKey: ['first'], - queryFn: () => firstDeferred.promise, - }) - const second = queryClient.fetchQuery({ - queryKey: ['second'], - queryFn: () => secondDeferred.promise, - }) - firstDeferred.resolve('first-data') - secondDeferred.resolve('second-data') - await Promise.all([first, second]) - await new Promise((resolve) => setTimeout(resolve, 0)) - - const later = queryClient.fetchQuery({ - queryKey: ['later'], - queryFn: () => laterDeferred.promise, - }) - laterDeferred.resolve('later-data') - await later - finishRender() - - expect(getAll).not.toHaveBeenCalled() - expect(await streamedQueriesPromise).toMatchObject([ - [{ queryKey: ['first'] }, { queryKey: ['second'] }], - [{ queryKey: ['later'] }], - ]) - triggerCleanup() - }) - - it('snapshots QueryClient dehydration defaults after Router dehydration', async () => { - const queryClient = track(new QueryClient()) - const { router, attachServerSsr, finishRender, triggerCleanup } = - createServerRouter() - - setupCoreRouterSsrQueryIntegration({ - router: router as any, - queryClient, - }) - attachServerSsr() - queryClient.setDefaultOptions({ - ...queryClient.getDefaultOptions(), - dehydrate: { - ...queryClient.getDefaultOptions().dehydrate, - serializeData: (data) => `${data}-current`, - }, - }) - queryClient.setQueryData(['initial'], 'initial') - - const dehydrated = (await router.options.dehydrate?.()) as { - query: { - initial: Array<{ state: { data: unknown } }> - stream: ReadableStream<Array<{ state: { data: unknown } }>> - } - } - const streamedQueriesPromise = readStream(dehydrated.query.stream) - queryClient.setDefaultOptions({ - ...queryClient.getDefaultOptions(), - dehydrate: { - ...queryClient.getDefaultOptions().dehydrate, - serializeData: (data) => `${data}-later`, - }, - }) - await queryClient.fetchQuery({ - queryKey: ['streamed'], - queryFn: () => 'streamed', - }) - finishRender() - - expect(dehydrated.query.initial[0]?.state.data).toBe('initial-current') - expect((await streamedQueriesPromise)[0]?.[0]?.state.data).toBe( - 'streamed-current', - ) - triggerCleanup() - }) - - it('errors and unsubscribes when streamed serialization throws', async () => { - const queryClient = track(new QueryClient()) - const { router, attachServerSsr, finishRender, triggerCleanup } = - createServerRouter() - const error = new Error('serialize failed') - - setupCoreRouterSsrQueryIntegration({ - router: router as any, - queryClient, - dehydrateOptions: { - serializeData: () => { - throw error - }, - }, - }) - attachServerSsr() - const dehydrated = (await router.options.dehydrate?.()) as { - query: { stream: ReadableStream<Array<unknown>> } - } - const streamedQueriesPromise = readStream(dehydrated.query.stream) - await queryClient.fetchQuery({ - queryKey: ['throws'], - queryFn: () => 'data', - }) - finishRender() - - await expect(streamedQueriesPromise).rejects.toBe(error) - expect(queryClient.getQueryCache().hasListeners()).toBe(false) - triggerCleanup() - }) - - it('closes the stream and aborts an in-flight render query on cleanup', async () => { - const queryClient = track(new QueryClient()) - const { router, attachServerSsr, triggerCleanup } = createServerRouter() - const queryStarted = createDeferred<void>() - let aborted = false - - setupCoreRouterSsrQueryIntegration({ - router: router as any, - queryClient, - }) - attachServerSsr() - const dehydrated = (await router.options.dehydrate?.()) as { - query: { stream: ReadableStream<Array<unknown>> } - } - const streamedQueriesPromise = readStream(dehydrated.query.stream) - const query = queryClient.fetchQuery({ - queryKey: ['in-flight'], - queryFn: ({ signal }) => - new Promise<string>((_resolve, reject) => { - signal.addEventListener('abort', () => { - aborted = true - reject(new Error('aborted')) - }) - queryStarted.resolve() - }), - }) - query.catch(() => {}) - await queryStarted.promise - triggerCleanup() - - expect(await streamedQueriesPromise).toEqual([]) - expect(queryClient.getQueryCache().getAll()).toEqual([]) - expect(queryClient.getQueryCache().hasListeners()).toBe(false) - expect(aborted).toBe(true) - }) - - it('clears the QueryClient when the stream is already cancelled', async () => { - const queryClient = track(new QueryClient()) - const { router, attachServerSsr, triggerCleanup } = createServerRouter() - - setupCoreRouterSsrQueryIntegration({ - router: router as any, - queryClient, - }) - attachServerSsr() - queryClient.setQueryData(['cancelled-stream'], 'data') - const dehydrated = (await router.options.dehydrate?.()) as { - query: { stream: ReadableStream<Array<unknown>> } - } - await dehydrated.query.stream.cancel() - - expect(() => triggerCleanup()).not.toThrow() - expect(queryClient.getQueryCache().getAll()).toEqual([]) - expect(queryClient.getQueryCache().hasListeners()).toBe(false) - }) -}) - -describe('SSR cleanup', () => { - it('clears queries when a request ends before dehydration', () => { - const queryClient = track(new QueryClient()) - const { router, attachServerSsr, triggerCleanup } = createServerRouter() - - setupCoreRouterSsrQueryIntegration({ - router: router as any, - queryClient, - }) - attachServerSsr() - queryClient.setQueryData(['loader'], 'data') - triggerCleanup() - - expect(queryClient.getQueryCache().getAll()).toEqual([]) - }) - - it('aborts in-flight queries', async () => { - const queryClient = track(new QueryClient()) - const { router, attachServerSsr, triggerCleanup } = createServerRouter() - const queryStarted = createDeferred<void>() - let aborted = false - - setupCoreRouterSsrQueryIntegration({ - router: router as any, - queryClient, - }) - attachServerSsr() - const query = queryClient.fetchQuery({ - queryKey: ['slow'], - queryFn: ({ signal }) => - new Promise<string>((_resolve, reject) => { - signal.addEventListener('abort', () => { - aborted = true - reject(new Error('aborted')) - }) - queryStarted.resolve() - }), - }) - query.catch(() => {}) - await queryStarted.promise - - triggerCleanup() - await Promise.resolve() - - expect(aborted).toBe(true) - }) - - it('registers cleanup when Router attaches server SSR', () => { - const queryClient = track(new QueryClient()) - const { router, attachServerSsr, triggerCleanup } = createServerRouter() - - setupCoreRouterSsrQueryIntegration({ - router: router as any, - queryClient, - }) - queryClient.setQueryData(['before-attach'], 'data') - attachServerSsr() - triggerCleanup() - - expect(queryClient.getQueryCache().getAll()).toEqual([]) - }) -}) - -const gcAvailable = typeof (globalThis as any).gc === 'function' -const gcTestsEnabled = process.env.RUN_SSR_GC_TESTS === '1' && gcAvailable - -async function forceGc() { - for (let index = 0; index < 6; index++) { - ;(globalThis as any).gc() - await new Promise((resolve) => setTimeout(resolve, 0)) - } -} - -describe.runIf(gcTestsEnabled)('SSR memory', () => { - it('releases the request QueryClient and Router after cleanup', async () => { - let queryClient: QueryClient | null = new QueryClient({ - defaultOptions: { queries: { gcTime: 5 * 60 * 1000 } }, - }) - let fixture: ReturnType<typeof createServerRouter> | null = - createServerRouter() - - setupCoreRouterSsrQueryIntegration({ - router: fixture.router as any, - queryClient, - }) - fixture.attachServerSsr() - queryClient.setQueryData(['data'], 'value') - const dehydrated = (await fixture.router.options.dehydrate?.()) as { - query: { stream: ReadableStream<Array<unknown>> } - } - const streamedQueriesPromise = readStream(dehydrated.query.stream) - fixture.finishRender() - await streamedQueriesPromise - - const queryClientRef = new WeakRef(queryClient) - const routerRef = new WeakRef(fixture.router) - fixture.triggerCleanup() - queryClient = null - fixture = null - - await forceGc() - - expect(queryClientRef.deref()).toBeUndefined() - expect(routerRef.deref()).toBeUndefined() - }) -}) diff --git a/packages/router-ssr-query-core/tests/server-lifecycle.bench.ts b/packages/router-ssr-query-core/tests/server-lifecycle.bench.ts deleted file mode 100644 index f66e3f234b..0000000000 --- a/packages/router-ssr-query-core/tests/server-lifecycle.bench.ts +++ /dev/null @@ -1,153 +0,0 @@ -// @vitest-environment node - -import { QueryClient } from '@tanstack/query-core' -import { afterAll, describe, test } from 'vitest' -import { setupCoreRouterSsrQueryIntegration } from '../src' - -let benchmarkSink = 0 - -describe('server request lifecycle', () => { - test('create and close a ReadableStream', async ({ bench }) => { - await bench('create and close a ReadableStream', () => { - let controller!: ReadableStreamDefaultController<unknown> - const stream = new ReadableStream({ - start(value) { - controller = value - }, - }) - controller.close() - benchmarkSink += stream.locked ? 1 : 0 - }).run() - }) - - const subscriptionClient = new QueryClient() - const queryCache = subscriptionClient.getQueryCache() - const listener = () => {} - afterAll(() => subscriptionClient.clear()) - - test('subscribe and unsubscribe from QueryCache', async ({ bench }) => { - await bench('subscribe and unsubscribe from QueryCache', () => { - const unsubscribe = queryCache.subscribe(listener) - unsubscribe() - }).run() - }) - - test('setup and cleanup before dehydrate', async ({ bench }) => { - await bench('setup and cleanup before dehydrate', () => { - const queryClient = new QueryClient() - const fixture = createServerRouter() - - setupCoreRouterSsrQueryIntegration({ - router: fixture.router as any, - queryClient, - }) - fixture.attach() - fixture.cleanup() - benchmarkSink += fixture.cleanupListenerCount() - }).run() - }) - - test('setup and dehydrate an empty request', async ({ bench }) => { - await bench('setup and dehydrate an empty request', async () => { - const queryClient = new QueryClient() - const fixture = createServerRouter() - - setupCoreRouterSsrQueryIntegration({ - router: fixture.router as any, - queryClient, - }) - fixture.attach() - const dehydrated = await fixture.router.options.dehydrate?.() - fixture.finishRender() - fixture.cleanup() - benchmarkSink += dehydrated?.query.stream.locked ? 1 : 0 - }).run() - }) - - test('write 100 loader queries without integration', async ({ bench }) => { - await bench('write 100 loader queries without integration', () => { - const queryClient = new QueryClient() - populateQueryClient(queryClient, 100) - benchmarkSink += queryClient.getQueryCache().getAll().length - queryClient.clear() - }).run() - }) - - test('write 100 loader queries before dehydrate', async ({ bench }) => { - await bench('write 100 loader queries before dehydrate', () => { - const queryClient = new QueryClient() - const fixture = createServerRouter() - - setupCoreRouterSsrQueryIntegration({ - router: fixture.router as any, - queryClient, - }) - fixture.attach() - populateQueryClient(queryClient, 100) - benchmarkSink += queryClient.getQueryCache().getAll().length - fixture.cleanup() - }).run() - }) -}) - -function populateQueryClient(queryClient: QueryClient, queryCount: number) { - for (let index = 0; index < queryCount; index++) { - queryClient.setQueryData(['query', index], `data-${index}`) - } -} - -function createServerRouter() { - const renderFinishedListeners = new Array<() => void>() - const cleanupListeners = new Array<() => void>() - const serverSsr = { - onRenderFinished: (listener: () => void) => { - renderFinishedListeners.push(listener) - }, - onCleanup: (listener: () => void) => { - cleanupListeners.push(listener) - }, - } - const router = { - isServer: true, - options: {} as { - dehydrate?: () => - | { - query: { stream: ReadableStream<unknown> } - } - | Promise<{ - query: { stream: ReadableStream<unknown> } - }> - }, - serverSsr: undefined as typeof serverSsr | undefined, - serverSsrLifecycle: undefined as - | { - onServerSsrAttach: Array<(value: typeof serverSsr) => void> - } - | undefined, - } - - return { - router, - attach() { - router.serverSsr = serverSsr - router.serverSsrLifecycle?.onServerSsrAttach.forEach((listener) => { - listener(serverSsr) - }) - }, - finishRender() { - for (const listener of renderFinishedListeners.splice(0)) { - listener() - } - }, - cleanup() { - for (const listener of cleanupListeners.splice(0)) { - listener() - } - }, - cleanupListenerCount() { - return cleanupListeners.length - }, - } -} - -void benchmarkSink diff --git a/packages/router-ssr-query-core/tsconfig.build.json b/packages/router-ssr-query-core/tsconfig.build.json deleted file mode 100644 index 92be18587f..0000000000 --- a/packages/router-ssr-query-core/tsconfig.build.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "rootDir": "./src" - }, - "include": ["src"] -} diff --git a/packages/router-ssr-query-core/vite.config.ts b/packages/router-ssr-query-core/vite.config.ts index 811b179d2d..5883c6fd90 100644 --- a/packages/router-ssr-query-core/vite.config.ts +++ b/packages/router-ssr-query-core/vite.config.ts @@ -1,15 +1,8 @@ -import path from 'node:path' import { defineConfig, mergeConfig } from 'vitest/config' import { tanstackViteConfig } from '@tanstack/vite-config' import packageJson from './package.json' import type { ViteUserConfig } from 'vitest/config' -// GC/WeakRef tests are flaky in CI because V8 does not guarantee reclamation -// timing. They are env-gated and only run with RUN_SSR_GC_TESTS=1. When the -// flag is set we additionally enable --expose-gc and use the forks pool so -// globalThis.gc() is available. -const runGcTests = process.env.RUN_SSR_GC_TESTS === '1' - const config = defineConfig({ test: { name: packageJson.name, @@ -17,24 +10,12 @@ const config = defineConfig({ watch: false, environment: 'jsdom', typecheck: { enabled: true }, - alias: { - // For tests only, resolve to development.ts which returns undefined - // so that router.isServer fallback is used (mirrors router-core). - '@tanstack/router-core/isServer': path.resolve( - __dirname, - '../router-core/src/isServer/development.ts', - ), - }, - ...(runGcTests - ? { pool: 'forks' as const, execArgv: ['--expose-gc'] } - : {}), }, }) export default mergeConfig( config, tanstackViteConfig({ - tsconfigPath: './tsconfig.build.json', entry: ['./src/index.ts'], srcDir: './src', }), diff --git a/packages/router-utils/CHANGELOG.md b/packages/router-utils/CHANGELOG.md index 55ce3a571b..6e8c68408e 100644 --- a/packages/router-utils/CHANGELOG.md +++ b/packages/router-utils/CHANGELOG.md @@ -1,61 +1,5 @@ # @tanstack/router-utils -## 1.163.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 - -- [#8867](https://github.com/TanStack/router/pull/8867) [`ff157f0`](https://github.com/TanStack/router/commit/ff157f0079982e90d62be7fdeecfb77e4fdcec69) - Parse decorators placed after `export` (`export @dec class Store {}`). A route file with one is now read by the route generator and split, instead of logging a parse error, leaving the route tree unwritten and the route unsplit. Start's compilers, which share the parser, accept it too. - -## 1.162.4 - -### Patch Changes - -- [#8709](https://github.com/TanStack/router/pull/8709) [`923d98b`](https://github.com/TanStack/router/commit/923d98b18b6cd90b6219591e20e86115dc61048e) - Bump `diff` dependency to `^9.0.0`. - -## 1.162.3 - -### Patch Changes - -- [#8300](https://github.com/TanStack/router/pull/8300) [`49bcd4d`](https://github.com/TanStack/router/commit/49bcd4db743dba4a783d5533a42a0f97a5721292) - Refresh compatible build and runtime dependencies. - -## 1.162.2 - -### 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. - -## 1.162.1 - -### 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.162.0 - -### Minor Changes - -- Clean minor bump, fresh start ([#7395](https://github.com/TanStack/router/pull/7395)) - -## 1.161.8 - -### 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)) - -## 1.161.7 - -### Patch Changes - -- rsbuild ([#7228](https://github.com/TanStack/router/pull/7228)) - ## 1.161.6 ### Patch Changes diff --git a/packages/router-utils/package.json b/packages/router-utils/package.json index 0ce243718f..d25db93ed0 100644 --- a/packages/router-utils/package.json +++ b/packages/router-utils/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/router-utils", - "version": "1.163.0", + "version": "1.161.6", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", @@ -27,13 +27,13 @@ "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": "node ../../node_modules/typescript59/lib/tsc.js", - "test:types:ts60": "tsc6", - "test:types:ts70": "tsc", - "test:unit": "vitest", + "test:types:ts59": "tsc", + "test:unit": "exit 0; vitest --typecheck", "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", "build": "vite build" }, @@ -60,26 +60,23 @@ "src" ], "engines": { - "node": "^20.19.0 || >=22.12.0" + "node": ">=20.19" }, "dependencies": { - "@babel/generator": "^7.29.8", - "@babel/parser": "^7.29.8", - "@babel/types": "catalog:", - "ansis": "^4.3.1", + "@babel/core": "^7.28.5", + "@babel/generator": "^7.28.5", + "@babel/parser": "^7.28.5", + "@babel/types": "^7.28.5", + "ansis": "^4.1.0", "babel-dead-code-elimination": "^1.0.12", - "diff": "^9.0.0", - "pathe": "catalog:", - "tinyglobby": "catalog:" + "diff": "^8.0.2", + "pathe": "^2.0.3", + "tinyglobby": "^0.2.15" }, "devDependencies": { + "@types/babel__core": "^7.20.5", "@types/babel__generator": "^7.27.0", - "vite": "*", - "@types/node": ">=20", - "@tanstack/vite-config": "catalog:", - "vitest": "catalog:", - "@arethetypeswrong/cli": "catalog:", - "publint": "catalog:", - "rimraf": "catalog:" + "@types/diff": "^7.0.2", + "vite": "*" } } diff --git a/packages/router-utils/src/ast.ts b/packages/router-utils/src/ast.ts index 6448adcbad..72525b8b8d 100644 --- a/packages/router-utils/src/ast.ts +++ b/packages/router-utils/src/ast.ts @@ -11,53 +11,17 @@ import type * as _babel_types from '@babel/types' export type ParseAstOptions = ParserOptions & { code: string - filename?: string } export type ParseAstResult = ParseResult<_babel_types.File> -export function parseAst({ - code, - filename, - sourceFilename, - plugins, - ...opts -}: ParseAstOptions): ParseAstResult { - const inferredFilename = filename ?? sourceFilename +export function parseAst({ code, ...opts }: ParseAstOptions): ParseAstResult { return parse(code, { - plugins: plugins ?? getDefaultParserPluginsForFilename(inferredFilename), + plugins: ['jsx', 'typescript', 'explicitResourceManagement'], sourceType: 'module', - sourceFilename, ...opts, }) } -function getDefaultParserPluginsForFilename( - filename: string | undefined, -): NonNullable<ParserOptions['plugins']> { - const plugins: NonNullable<ParserOptions['plugins']> = [ - 'typescript', - 'explicitResourceManagement', - 'importAttributes', - 'deprecatedImportAssert', - 'decorators', - 'decoratorAutoAccessors', - ] - - if (!isPlainTypeScriptFile(filename)) { - plugins.unshift('jsx') - } - - return plugins -} - -function isPlainTypeScriptFile(filename: string | undefined): boolean { - if (!filename) { - return false - } - - return /\.[cm]?ts(?:$|[?#])/.test(filename) -} - let generate = _generate if ('default' in generate) { diff --git a/packages/router-utils/src/compiler-helpers.ts b/packages/router-utils/src/compiler-helpers.ts deleted file mode 100644 index 5460c34914..0000000000 --- a/packages/router-utils/src/compiler-helpers.ts +++ /dev/null @@ -1,902 +0,0 @@ -import * as t from '@babel/types' - -type CompilerNodePath<TNode extends t.Node = t.Node> = { - node: TNode - parentPath: CompilerNodePath | null - isVariableDeclarator: () => boolean -} - -type ReplacePathNode<TPath, TNode extends t.Node> = Omit<TPath, 'node'> & { - node: TNode -} - -type IdentifierScopeFrame = { - kind: 'program' | 'function' | 'block' - bindings: Set<string> -} -type IdentifierScopeStack = Array<IdentifierScopeFrame> - -export type ModuleInfoBinding = - | { - type: 'import' - source: string - importedName: string - } - | { - type: 'var' - init: t.Expression | null - } - -export interface ExtractedModuleInfo { - bindings: Map<string, ModuleInfoBinding> - exports: Map<string, string> - reExportAllSources: Array<string> -} - -function getTransparentWrapperExpression(node: t.Node): t.Expression | null { - if ( - t.isTSAsExpression(node) || - t.isTSSatisfiesExpression(node) || - t.isTSTypeAssertion(node) || - t.isTSNonNullExpression(node) || - t.isParenthesizedExpression(node) - ) { - return node.expression - } - - return null -} - -export function unwrapExpression(expr: t.Expression): t.Expression { - let inner = getTransparentWrapperExpression(expr) - while (inner) { - expr = inner - inner = getTransparentWrapperExpression(expr) - } - - return expr -} - -export function getVariableDeclaratorForExpressionPath< - TPath extends CompilerNodePath<t.Expression>, ->(path: TPath): ReplacePathNode<TPath, t.VariableDeclarator> | null { - let currentPath: CompilerNodePath = path - let parentPath = currentPath.parentPath - - while ( - parentPath && - getTransparentWrapperExpression(parentPath.node) === currentPath.node - ) { - currentPath = parentPath - parentPath = parentPath.parentPath - } - - if ( - parentPath?.isVariableDeclarator() && - t.isVariableDeclarator(parentPath.node) && - parentPath.node.init === currentPath.node - ) { - return parentPath as ReplacePathNode<TPath, t.VariableDeclarator> - } - - return null -} - -function getModuleExportName(node: t.Identifier | t.StringLiteral) { - return t.isIdentifier(node) ? node.name : node.value -} - -function addVariableDeclarationModuleInfo( - declaration: t.VariableDeclaration, - bindings: Map<string, ModuleInfoBinding>, - exportMap?: Map<string, string>, -) { - for (const declarator of declaration.declarations) { - for (const name of collectIdentifiersFromPattern(declarator.id)) { - bindings.set(name, { - type: 'var', - init: declarator.init ?? null, - }) - exportMap?.set(name, name) - } - } -} - -function addDeclarationModuleInfo( - declaration: t.Declaration, - bindings: Map<string, ModuleInfoBinding>, - exportMap?: Map<string, string>, -) { - if (t.isVariableDeclaration(declaration)) { - addVariableDeclarationModuleInfo(declaration, bindings, exportMap) - return - } - - if ( - (t.isFunctionDeclaration(declaration) || - t.isClassDeclaration(declaration)) && - declaration.id - ) { - bindings.set(declaration.id.name, { - type: 'var', - init: null, - }) - exportMap?.set(declaration.id.name, declaration.id.name) - } -} - -function hasIdentifierBinding(scopes: IdentifierScopeStack, name: string) { - for (let i = scopes.length - 1; i >= 0; i--) { - if (scopes[i]!.bindings.has(name)) { - return true - } - } - return false -} - -function currentIdentifierScope(scopes: IdentifierScopeStack) { - return scopes[scopes.length - 1]! -} - -function nearestFunctionIdentifierScope(scopes: IdentifierScopeStack) { - for (let i = scopes.length - 1; i >= 0; i--) { - const scope = scopes[i]! - if (scope.kind === 'function' || scope.kind === 'program') { - return scope - } - } - return currentIdentifierScope(scopes) -} - -function addIdentifierPatternBindings( - pattern: t.LVal | t.Node | null | undefined, - scope: IdentifierScopeFrame, -) { - for (const name of collectIdentifiersFromPattern(pattern)) { - scope.bindings.add(name) - } -} - -function addIdentifierDeclarationBindings( - declaration: t.Node, - scopes: IdentifierScopeStack, -) { - if (t.isVariableDeclaration(declaration)) { - const scope = - declaration.kind === 'var' - ? nearestFunctionIdentifierScope(scopes) - : currentIdentifierScope(scopes) - for (const declarator of declaration.declarations) { - addIdentifierPatternBindings(declarator.id, scope) - } - return - } - - if ( - (t.isFunctionDeclaration(declaration) || - t.isClassDeclaration(declaration) || - t.isTSTypeAliasDeclaration(declaration) || - t.isTSInterfaceDeclaration(declaration) || - t.isTSEnumDeclaration(declaration)) && - declaration.id - ) { - currentIdentifierScope(scopes).bindings.add(declaration.id.name) - } -} - -function addIdentifierImportBindings( - node: t.ImportDeclaration, - scope: IdentifierScopeFrame, -) { - for (const specifier of node.specifiers) { - scope.bindings.add(specifier.local.name) - } -} - -function createNestedIdentifierScope( - kind: IdentifierScopeFrame['kind'], - scopes: IdentifierScopeStack, -): IdentifierScopeStack { - return [...scopes, { kind, bindings: new Set() }] -} - -function addIdentifierBlockBindings( - body: Array<t.Node>, - scopes: IdentifierScopeStack, -) { - for (const statement of body) { - if (t.isImportDeclaration(statement)) { - addIdentifierImportBindings(statement, currentIdentifierScope(scopes)) - } else if (t.isExportNamedDeclaration(statement) && statement.declaration) { - addIdentifierDeclarationBindings(statement.declaration, scopes) - } else { - addIdentifierDeclarationBindings(statement, scopes) - } - } -} - -function walkIdentifierChildren( - current: t.Node, - parent: t.Node | undefined, - scopes: IdentifierScopeStack, - ids: Set<string>, -) { - for (const key of t.VISITOR_KEYS[current.type] ?? []) { - const child = (current as any)[key] - if (Array.isArray(child)) { - for (const item of child) { - if (item && typeof item.type === 'string') { - walkIdentifierNode(item, current, parent, key, scopes, ids) - } - } - } else if (child && typeof child.type === 'string') { - walkIdentifierNode(child, current, parent, key, scopes, ids) - } - } -} - -function walkIdentifierNode( - current: t.Node | null | undefined, - parent: t.Node | undefined, - grandparent: t.Node | undefined, - parentKey: string | undefined, - scopes: IdentifierScopeStack, - ids: Set<string>, -) { - if (!current) return - - if (t.isIdentifier(current)) { - if ( - (!parent || t.isReferenced(current, parent, grandparent)) && - !hasIdentifierBinding(scopes, current.name) - ) { - ids.add(current.name) - } - return - } - - if (t.isJSXIdentifier(current)) { - if (parent && t.isJSXAttribute(parent) && parentKey === 'name') { - return - } - - if (parent && t.isJSXMemberExpression(parent) && parentKey === 'property') { - return - } - - const first = current.name[0] - if (first && first === first.toLowerCase()) { - return - } - - if (!hasIdentifierBinding(scopes, current.name)) { - ids.add(current.name) - } - return - } - - if (t.isProgram(current)) { - const nestedScopes = createNestedIdentifierScope('program', scopes) - addIdentifierBlockBindings(current.body, nestedScopes) - for (const child of current.body) { - walkIdentifierNode(child, current, parent, 'body', nestedScopes, ids) - } - return - } - - if (t.isBlockStatement(current)) { - const nestedScopes = createNestedIdentifierScope('block', scopes) - addIdentifierBlockBindings(current.body, nestedScopes) - for (const child of current.body) { - walkIdentifierNode(child, current, parent, 'body', nestedScopes, ids) - } - return - } - - if ( - t.isFunctionDeclaration(current) || - t.isFunctionExpression(current) || - t.isArrowFunctionExpression(current) || - t.isObjectMethod(current) || - t.isClassMethod(current) || - t.isClassPrivateMethod(current) - ) { - if (t.isFunctionDeclaration(current) && current.id) { - currentIdentifierScope(scopes).bindings.add(current.id.name) - } - - const nestedScopes = createNestedIdentifierScope('function', scopes) - if ( - (t.isFunctionDeclaration(current) || t.isFunctionExpression(current)) && - current.id - ) { - currentIdentifierScope(nestedScopes).bindings.add(current.id.name) - } - for (const param of current.params) { - addIdentifierPatternBindings(param, currentIdentifierScope(nestedScopes)) - } - - walkIdentifierChildren(current, parent, nestedScopes, ids) - return - } - - if (t.isCatchClause(current)) { - const nestedScopes = createNestedIdentifierScope('block', scopes) - addIdentifierPatternBindings( - current.param, - currentIdentifierScope(nestedScopes), - ) - walkIdentifierNode( - current.param, - current, - parent, - 'param', - nestedScopes, - ids, - ) - walkIdentifierNode(current.body, current, parent, 'body', nestedScopes, ids) - return - } - - if (t.isImportDeclaration(current)) { - addIdentifierImportBindings(current, currentIdentifierScope(scopes)) - return - } - - if (t.isClassDeclaration(current) || t.isClassExpression(current)) { - if (t.isClassDeclaration(current) && current.id) { - currentIdentifierScope(scopes).bindings.add(current.id.name) - } - - const nestedScopes = current.id - ? createNestedIdentifierScope('block', scopes) - : scopes - if (current.id) { - currentIdentifierScope(nestedScopes).bindings.add(current.id.name) - } - - walkIdentifierChildren(current, parent, nestedScopes, ids) - return - } - - if (t.isVariableDeclaration(current)) { - addIdentifierDeclarationBindings(current, scopes) - } else if (t.isVariableDeclarator(current)) { - const scope = - parent && t.isVariableDeclaration(parent) && parent.kind === 'var' - ? nearestFunctionIdentifierScope(scopes) - : currentIdentifierScope(scopes) - addIdentifierPatternBindings(current.id, scope) - } else if ( - t.isTSTypeAliasDeclaration(current) || - t.isTSInterfaceDeclaration(current) || - t.isTSEnumDeclaration(current) - ) { - currentIdentifierScope(scopes).bindings.add(current.id.name) - } - - walkIdentifierChildren(current, parent, scopes, ids) -} - -/** - * Recursively walk an AST node and collect referenced identifier-like names. - * This avoids Babel path/scope allocation for module-level dependency scans. - */ -export function collectIdentifiersFromNode(node: t.Node): Set<string> { - const ids = new Set<string>() - walkIdentifierNode( - node, - undefined, - undefined, - undefined, - [{ kind: 'program', bindings: new Set() }], - ids, - ) - return ids -} - -export function collectIdentifiersFromPattern( - node: t.LVal | t.Node | null | undefined, -): Array<string> { - if (!node) { - return [] - } - - if (t.isIdentifier(node)) { - return [node.name] - } - - if (t.isAssignmentPattern(node)) { - return collectIdentifiersFromPattern(node.left) - } - - if (t.isRestElement(node)) { - return collectIdentifiersFromPattern(node.argument) - } - - if (t.isObjectPattern(node)) { - return node.properties.flatMap((prop) => { - if (t.isObjectProperty(prop)) { - return collectIdentifiersFromPattern(prop.value as t.LVal) - } - if (t.isRestElement(prop)) { - return collectIdentifiersFromPattern(prop.argument) - } - return [] - }) - } - - if (t.isArrayPattern(node)) { - return node.elements.flatMap((element) => - collectIdentifiersFromPattern(element), - ) - } - - return [] -} - -export function collectLocalBindingsFromStatement( - node: t.Statement | t.ModuleDeclaration, - bindings: Set<string>, -) { - const declaration = - t.isExportNamedDeclaration(node) && node.declaration - ? node.declaration - : t.isExportDefaultDeclaration(node) - ? node.declaration - : node - - if (t.isVariableDeclaration(declaration)) { - for (const declarator of declaration.declarations) { - for (const name of collectIdentifiersFromPattern(declarator.id)) { - bindings.add(name) - } - } - } else if (t.isFunctionDeclaration(declaration) && declaration.id) { - bindings.add(declaration.id.name) - } else if (t.isClassDeclaration(declaration) && declaration.id) { - bindings.add(declaration.id.name) - } -} - -export function extractModuleInfoFromAst(ast: t.File): ExtractedModuleInfo { - const bindings = new Map<string, ModuleInfoBinding>() - const exportMap = new Map<string, string>() - const reExportAllSources: Array<string> = [] - - for (const node of ast.program.body) { - if (t.isImportDeclaration(node)) { - const source = node.source.value - for (const specifier of node.specifiers) { - if (t.isImportSpecifier(specifier)) { - bindings.set(specifier.local.name, { - type: 'import', - source, - importedName: getModuleExportName(specifier.imported), - }) - } else if (t.isImportDefaultSpecifier(specifier)) { - bindings.set(specifier.local.name, { - type: 'import', - source, - importedName: 'default', - }) - } else if (t.isImportNamespaceSpecifier(specifier)) { - bindings.set(specifier.local.name, { - type: 'import', - source, - importedName: '*', - }) - } - } - continue - } - - if (t.isVariableDeclaration(node)) { - addVariableDeclarationModuleInfo(node, bindings) - continue - } - - if (t.isFunctionDeclaration(node) || t.isClassDeclaration(node)) { - addDeclarationModuleInfo(node, bindings) - continue - } - - if (t.isExportNamedDeclaration(node)) { - if (node.declaration) { - addDeclarationModuleInfo(node.declaration, bindings, exportMap) - } - - for (const specifier of node.specifiers) { - if (t.isExportNamespaceSpecifier(specifier)) { - const exported = getModuleExportName(specifier.exported) - exportMap.set(exported, exported) - if (node.source) { - bindings.set(exported, { - type: 'import', - source: node.source.value, - importedName: '*', - }) - } - } else if (t.isExportSpecifier(specifier)) { - const local = getModuleExportName(specifier.local) - const exported = getModuleExportName(specifier.exported) - exportMap.set(exported, local) - - if (node.source) { - bindings.set(local, { - type: 'import', - source: node.source.value, - importedName: local, - }) - } - } - } - continue - } - - if (t.isExportDefaultDeclaration(node)) { - const declaration = node.declaration - if (t.isIdentifier(declaration)) { - exportMap.set('default', declaration.name) - } else if ( - (t.isFunctionDeclaration(declaration) || - t.isClassDeclaration(declaration)) && - declaration.id - ) { - bindings.set(declaration.id.name, { - type: 'var', - init: null, - }) - exportMap.set('default', declaration.id.name) - } else { - const synth = '__default_export__' - bindings.set(synth, { - type: 'var', - init: t.isExpression(declaration) ? declaration : null, - }) - exportMap.set('default', synth) - } - continue - } - - if (t.isExportAllDeclaration(node)) { - reExportAllSources.push(node.source.value) - } - } - - return { - bindings, - exports: exportMap, - reExportAllSources, - } -} - -export function buildDeclarationMap(ast: t.File): Map<string, t.Node> { - const map = new Map<string, t.Node>() - - for (const statement of ast.program.body) { - const declaration = - t.isExportNamedDeclaration(statement) && statement.declaration - ? statement.declaration - : t.isExportDefaultDeclaration(statement) - ? statement.declaration - : statement - - if (t.isVariableDeclaration(declaration)) { - for (const declarator of declaration.declarations) { - for (const name of collectIdentifiersFromPattern(declarator.id)) { - map.set(name, declarator) - } - } - } else if (t.isFunctionDeclaration(declaration) && declaration.id) { - map.set(declaration.id.name, declaration) - } else if (t.isClassDeclaration(declaration) && declaration.id) { - map.set(declaration.id.name, declaration) - } - } - - return map -} - -export function buildDependencyGraph( - declarationMap: Map<string, t.Node>, - localBindings: Set<string>, -): Map<string, Set<string>> { - const graph = new Map<string, Set<string>>() - - for (const [name, declarationNode] of declarationMap) { - if (!localBindings.has(name)) continue - - const dependencies = new Set<string>() - for (const id of collectIdentifiersFromNode(declarationNode)) { - if (id !== name && localBindings.has(id)) { - dependencies.add(id) - } - } - graph.set(name, dependencies) - } - - return graph -} - -export function collectModuleLevelRefsFromNode( - node: t.Node, - localModuleLevelBindings: Set<string>, -): Set<string> { - const refs = new Set<string>() - - for (const name of collectIdentifiersFromNode(node)) { - if (localModuleLevelBindings.has(name)) { - refs.add(name) - } - } - - return refs -} - -export function expandTransitively( - bindings: Set<string>, - dependencyGraph: Map<string, Set<string>>, -) { - const queue = [...bindings] - const visited = new Set<string>() - - while (queue.length > 0) { - const name = queue.pop()! - if (visited.has(name)) continue - visited.add(name) - - const dependencies = dependencyGraph.get(name) - if (!dependencies) continue - - for (const dependency of dependencies) { - if (!bindings.has(dependency)) { - bindings.add(dependency) - queue.push(dependency) - } - } - } -} - -export function expandSharedDestructuredDeclarators( - ast: t.File, - refsByGroup: Map<string, Set<number>>, - sharedBindings: Set<string>, -) { - for (const statement of ast.program.body) { - const declaration = - t.isExportNamedDeclaration(statement) && statement.declaration - ? statement.declaration - : statement - - if (!t.isVariableDeclaration(declaration)) continue - - for (const declarator of declaration.declarations) { - if ( - !t.isObjectPattern(declarator.id) && - !t.isArrayPattern(declarator.id) - ) { - continue - } - - const names = collectIdentifiersFromPattern(declarator.id) - const usedGroups = new Set<number>() - - for (const name of names) { - const groups = refsByGroup.get(name) - if (!groups) continue - for (const group of groups) { - usedGroups.add(group) - } - } - - if (usedGroups.size >= 2) { - for (const name of names) { - sharedBindings.add(name) - } - } - } - } -} - -export function expandDestructuredDeclarations( - ast: t.File, - bindings: Set<string>, -) { - for (const statement of ast.program.body) { - const declaration = - t.isExportNamedDeclaration(statement) && statement.declaration - ? statement.declaration - : statement - - if (!t.isVariableDeclaration(declaration)) continue - - for (const declarator of declaration.declarations) { - if ( - !t.isObjectPattern(declarator.id) && - !t.isArrayPattern(declarator.id) - ) { - continue - } - - const names = collectIdentifiersFromPattern(declarator.id) - if (names.some((name) => bindings.has(name))) { - for (const name of names) { - bindings.add(name) - } - } - } - } -} - -export function removeBindingsTransitivelyDependingOn( - bindings: Set<string>, - dependencyGraph: Map<string, Set<string>>, - roots: Iterable<string>, -) { - const reverseGraph = new Map<string, Set<string>>() - - for (const [name, dependencies] of dependencyGraph) { - for (const dependency of dependencies) { - let parents = reverseGraph.get(dependency) - if (!parents) { - parents = new Set() - reverseGraph.set(dependency, parents) - } - parents.add(name) - } - } - - const visited = new Set<string>() - const queue = [...roots] - - while (queue.length > 0) { - const current = queue.pop()! - if (visited.has(current)) continue - visited.add(current) - - const parents = reverseGraph.get(current) - if (!parents) continue - - for (const parent of parents) { - if (!visited.has(parent)) { - queue.push(parent) - } - } - } - - for (const name of [...bindings]) { - if (visited.has(name)) { - bindings.delete(name) - } - } -} - -export function removeModuleLevelBindings( - ast: t.File, - namesToRemove: Set<string>, -) { - ast.program.body = ast.program.body.filter((statement) => { - const declaration = - t.isExportNamedDeclaration(statement) && statement.declaration - ? statement.declaration - : statement - - if (t.isVariableDeclaration(declaration)) { - declaration.declarations = declaration.declarations.filter( - (declarator) => - !collectIdentifiersFromPattern(declarator.id).some((name) => - namesToRemove.has(name), - ), - ) - return declaration.declarations.length > 0 - } - - if (t.isFunctionDeclaration(declaration) && declaration.id) { - return !namesToRemove.has(declaration.id.name) - } - - if (t.isClassDeclaration(declaration) && declaration.id) { - return !namesToRemove.has(declaration.id.name) - } - - if (t.isExportDefaultDeclaration(statement)) { - const defaultDeclaration = statement.declaration - if ( - (t.isFunctionDeclaration(defaultDeclaration) || - t.isClassDeclaration(defaultDeclaration)) && - defaultDeclaration.id - ) { - return !namesToRemove.has(defaultDeclaration.id.name) - } - } - - return true - }) -} - -export function retainModuleLevelDeclarations( - ast: t.File, - bindingsToKeep: Set<string>, -) { - ast.program.body = ast.program.body.filter((statement) => { - if (t.isImportDeclaration(statement)) return true - - const declaration = - t.isExportNamedDeclaration(statement) && statement.declaration - ? statement.declaration - : statement - - if (t.isVariableDeclaration(declaration)) { - declaration.declarations = declaration.declarations.filter((declarator) => - collectIdentifiersFromPattern(declarator.id).some((name) => - bindingsToKeep.has(name), - ), - ) - return declaration.declarations.length > 0 - } - - if (t.isFunctionDeclaration(declaration) && declaration.id) { - return bindingsToKeep.has(declaration.id.name) - } - - if (t.isClassDeclaration(declaration) && declaration.id) { - return bindingsToKeep.has(declaration.id.name) - } - - return false - }) -} - -export function unwrapExportedDeclarations(ast: t.File) { - const body: Array<t.Statement | t.ModuleDeclaration> = [] - - for (const statement of ast.program.body) { - if (t.isExportNamedDeclaration(statement)) { - if (statement.declaration) { - body.push(statement.declaration) - } - continue - } - - if (t.isExportDefaultDeclaration(statement)) { - const declaration = statement.declaration - if ( - (t.isFunctionDeclaration(declaration) || - t.isClassDeclaration(declaration)) && - declaration.id - ) { - body.push(declaration) - } - continue - } - - if (t.isExportAllDeclaration(statement)) { - continue - } - - body.push(statement) - } - - ast.program.body = body -} - -export function stripUnreferencedTopLevelExpressionStatements(ast: t.File) { - const locallyBound = new Set<string>() - - for (const statement of ast.program.body) { - collectLocalBindingsFromStatement(statement, locallyBound) - } - - ast.program.body = ast.program.body.filter((statement) => { - if (!t.isExpressionStatement(statement)) return true - - for (const name of collectIdentifiersFromNode(statement)) { - if (locallyBound.has(name)) { - return true - } - } - - return false - }) -} diff --git a/packages/router-utils/src/index.ts b/packages/router-utils/src/index.ts index 12c3c8e20c..3b072ae419 100644 --- a/packages/router-utils/src/index.ts +++ b/packages/router-utils/src/index.ts @@ -9,26 +9,3 @@ export type { ParseAstOptions, ParseAstResult, GeneratorResult } from './ast' export { logDiff } from './logger' export { copyFilesPlugin } from './copy-files-plugin' - -export { createIdentifier, decodeIdentifier } from './path-ids' - -export { - buildDeclarationMap, - buildDependencyGraph, - collectIdentifiersFromNode, - collectIdentifiersFromPattern, - collectLocalBindingsFromStatement, - collectModuleLevelRefsFromNode, - expandDestructuredDeclarations, - expandSharedDestructuredDeclarators, - expandTransitively, - extractModuleInfoFromAst, - getVariableDeclaratorForExpressionPath, - removeBindingsTransitivelyDependingOn, - removeModuleLevelBindings, - retainModuleLevelDeclarations, - stripUnreferencedTopLevelExpressionStatements, - unwrapExpression, - unwrapExportedDeclarations, -} from './compiler-helpers' -export type { ExtractedModuleInfo, ModuleInfoBinding } from './compiler-helpers' diff --git a/packages/router-utils/tests/compiler-helpers.test.ts b/packages/router-utils/tests/compiler-helpers.test.ts deleted file mode 100644 index 00b75d67e5..0000000000 --- a/packages/router-utils/tests/compiler-helpers.test.ts +++ /dev/null @@ -1,249 +0,0 @@ -import * as t from '@babel/types' -import { describe, expect, test } from 'vitest' -import { - buildDeclarationMap, - collectIdentifiersFromNode, - collectLocalBindingsFromStatement, - extractModuleInfoFromAst, -} from '../src/compiler-helpers' -import { parseAst } from '../src/ast' - -function getVariableInit(code: string) { - const ast = parseAst({ code, filename: 'test.tsx' }) - const declaration = ast.program.body.find((node) => - t.isVariableDeclaration(node), - ) as t.VariableDeclaration - return declaration.declarations[0]!.init! -} - -function collectSortedIdentifiers(node: t.Node) { - return [...collectIdentifiersFromNode(node)].sort() -} - -function collectSortedStatementBindings(code: string) { - const ast = parseAst({ code, filename: 'test.tsx' }) - const bindings = new Set<string>() - for (const statement of ast.program.body) { - collectLocalBindingsFromStatement(statement, bindings) - } - return [...bindings].sort() -} - -function collectSortedDeclarationMapEntries(code: string) { - const ast = parseAst({ code, filename: 'test.tsx' }) - return [...buildDeclarationMap(ast)] - .map(([name, node]): [string, string] => [name, node.type]) - .sort((left, right) => (left[0] < right[0] ? -1 : 1)) -} - -function collectModuleInfoSnapshot(code: string) { - const ast = parseAst({ code, filename: 'test.tsx' }) - const info = extractModuleInfoFromAst(ast) - return { - bindings: [...info.bindings] - .map(([name, binding]) => [ - name, - binding.type === 'import' - ? `${binding.source}:${binding.importedName}` - : (binding.init?.type ?? null), - ]) - .sort((left, right) => (left[0]! < right[0]! ? -1 : 1)), - exports: [...info.exports].sort((left, right) => - left[0] < right[0] ? -1 : 1, - ), - reExportAllSources: info.reExportAllSources, - } -} - -describe('collectIdentifiersFromNode', () => { - test('collects free identifiers without reporting nested local bindings', () => { - const init = getVariableInit(` -const value = outer + (() => { - const local = dep - - function nested(param = fallback) { - const Inner = () => <LocalComponent value={param} /> - const LocalExpr = class NamedLocal { - method() { - return NamedLocal + local + param - } - } - - class LocalComponent {} - - return local + param + imported + Inner + LocalExpr - } - - return nested() -})() -`) - - expect(collectSortedIdentifiers(init)).toMatchInlineSnapshot(` - [ - "dep", - "fallback", - "imported", - "outer", - ] - `) - }) - - test('respects nested variable, parameter, catch, and import shadowing', () => { - const ast = parseAst({ - code: ` -import { external as localImport } from 'pkg' - -const value = (localParam = defaultValue) => { - const localShadow = factory(localImport) - - try { - throw thrown - } catch (thrown) { - const factory = () => localShadow + localParam + thrown - return factory() - } -} -`, - filename: 'test.ts', - }) - - expect(collectSortedIdentifiers(ast.program)).toMatchInlineSnapshot(` - [ - "defaultValue", - "factory", - "thrown", - ] - `) - }) -}) - -describe('collectLocalBindingsFromStatement', () => { - test('collects ids from named default function and class declarations', () => { - expect({ - class: collectSortedStatementBindings( - `export default class DefaultComponent {}`, - ), - function: collectSortedStatementBindings( - `export default function DefaultRoute() {}`, - ), - anonymous: collectSortedStatementBindings( - `export default function () {}`, - ), - }).toMatchInlineSnapshot(` - { - "anonymous": [], - "class": [ - "DefaultComponent", - ], - "function": [ - "DefaultRoute", - ], - } - `) - }) -}) - -describe('buildDeclarationMap', () => { - test('maps named default function and class declarations', () => { - expect({ - class: collectSortedDeclarationMapEntries( - `export default class DefaultComponent {}`, - ), - function: collectSortedDeclarationMapEntries( - `export default function DefaultRoute() {}`, - ), - anonymous: collectSortedDeclarationMapEntries(`export default class {}`), - }).toMatchInlineSnapshot(` - { - "anonymous": [], - "class": [ - [ - "DefaultComponent", - "ClassDeclaration", - ], - ], - "function": [ - [ - "DefaultRoute", - "FunctionDeclaration", - ], - ], - } - `) - }) -}) - -describe('extractModuleInfoFromAst', () => { - test('extracts imports, local exports, default exports, and re-export sources', () => { - expect( - collectModuleInfoSnapshot(` - import defaultImport, { named as localNamed } from 'pkg' - import * as ns from 'pkg-ns' - const local = localNamed - export const exported = local - export function loader() {} - export default class DefaultRoute {} - export { remote as renamed } from './remote' - export * from './all' - `), - ).toMatchInlineSnapshot(` - { - "bindings": [ - [ - "DefaultRoute", - null, - ], - [ - "defaultImport", - "pkg:default", - ], - [ - "exported", - "Identifier", - ], - [ - "loader", - null, - ], - [ - "local", - "Identifier", - ], - [ - "localNamed", - "pkg:named", - ], - [ - "ns", - "pkg-ns:*", - ], - [ - "remote", - "./remote:remote", - ], - ], - "exports": [ - [ - "default", - "DefaultRoute", - ], - [ - "exported", - "exported", - ], - [ - "loader", - "loader", - ], - [ - "renamed", - "remote", - ], - ], - "reExportAllSources": [ - "./all", - ], - } - `) - }) -}) diff --git a/packages/router-utils/tests/stripTypeExports.test.ts b/packages/router-utils/tests/stripTypeExports.test.ts index 32d25f1cbe..4a8f82ac3f 100644 --- a/packages/router-utils/tests/stripTypeExports.test.ts +++ b/packages/router-utils/tests/stripTypeExports.test.ts @@ -11,30 +11,6 @@ function transform(code: string): string { } describe('stripTypeExports', () => { - describe('import attributes parsing', () => { - test('parses import attributes with with syntax', () => { - const code = `import data from './data.json' with { type: 'json' } -export const value = data` - - expect(() => parseAst({ code })).not.toThrow() - }) - - test('parses import attributes with deprecated assert syntax', () => { - const code = `import data from './data.json' assert { type: 'json' } -export const value = data` - - expect(() => parseAst({ code })).not.toThrow() - }) - - test('parses angle-bracket type assertions in .ts files without JSX', () => { - const code = `export function cast<T>(value: any): T { - return <T>value -}` - - expect(() => parseAst({ code, filename: 'cast.ts' })).not.toThrow() - }) - }) - describe('type alias declarations', () => { test('preserves top-level type alias declaration (non-exported)', () => { const code = `type Foo = string; @@ -123,7 +99,7 @@ type TypeOnly = string; export { value, type TypeOnly };` const result = transform(code) expect(result).toContain('export { value }') - expect(result).toContain('type TypeOnly = string') + expect(result).not.toContain('TypeOnly') }) test('removes entire export if all specifiers are type-only', () => { @@ -133,8 +109,8 @@ export { type Foo, type Bar }; export const value = 1;` const result = transform(code) expect(result).not.toContain('export { type Foo') - expect(result).toContain('type Foo = string') - expect(result).toContain('type Bar = number') + expect(result).not.toContain('Foo') + expect(result).not.toContain('Bar') expect(result).toContain('export const value = 1') }) }) @@ -233,11 +209,9 @@ export { helper, type HelperType };` expect(result).not.toContain('./types') expect(result).not.toContain('HelperType') - // Should preserve local type declarations - expect(result).toContain('type LocalType = string') - expect(result).toContain('interface LocalInterface') - - // Should remove exported type declarations + // Should remove type declarations + expect(result).not.toContain('type LocalType') + expect(result).not.toContain('interface LocalInterface') expect(result).not.toContain('type ExportedType') expect(result).not.toContain('interface ExportedInterface') diff --git a/packages/router-utils/tsconfig.build.json b/packages/router-utils/tsconfig.build.json deleted file mode 100644 index 92be18587f..0000000000 --- a/packages/router-utils/tsconfig.build.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "rootDir": "./src" - }, - "include": ["src"] -} diff --git a/packages/router-utils/tsconfig.json b/packages/router-utils/tsconfig.json index 0506ca3d49..604fde5556 100644 --- a/packages/router-utils/tsconfig.json +++ b/packages/router-utils/tsconfig.json @@ -1,8 +1,5 @@ { "extends": "../../tsconfig.json", "include": ["src", "vite.config.ts", "tests"], - "exclude": ["tests/generator/**/**"], - "compilerOptions": { - "types": ["node"] - } + "exclude": ["tests/generator/**/**"] } diff --git a/packages/router-utils/vite.config.ts b/packages/router-utils/vite.config.ts index 5e305866b6..c24b19ec98 100644 --- a/packages/router-utils/vite.config.ts +++ b/packages/router-utils/vite.config.ts @@ -14,7 +14,6 @@ const config = defineConfig({ export default mergeConfig( config, tanstackViteConfig({ - tsconfigPath: './tsconfig.build.json', entry: './src/index.ts', srcDir: './src', }), diff --git a/packages/router-vite-plugin/CHANGELOG.md b/packages/router-vite-plugin/CHANGELOG.md index 90d47e813e..708dd74dc6 100644 --- a/packages/router-vite-plugin/CHANGELOG.md +++ b/packages/router-vite-plugin/CHANGELOG.md @@ -1,590 +1,5 @@ # @tanstack/router-vite-plugin -## 1.167.49 - -### Patch Changes - -- 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), [`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)]: - - @tanstack/router-plugin@1.169.0 - -## 1.167.48 - -### Patch Changes - -- Updated dependencies [[`32a3360`](https://github.com/TanStack/router/commit/32a3360cba0e0f884b3215813a48c63467f5a53c), [`647cb73`](https://github.com/TanStack/router/commit/647cb737a5622813d276d6042766692ca5ae67ed)]: - - @tanstack/router-plugin@1.168.48 - -## 1.167.47 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.168.47 - -## 1.167.46 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.168.46 - -## 1.167.45 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.168.45 - -## 1.167.44 - -### Patch Changes - -- Updated dependencies [[`e66da18`](https://github.com/TanStack/router/commit/e66da18266859ab49e20a7b8c858232449ee5290)]: - - @tanstack/router-plugin@1.168.44 - -## 1.167.43 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.168.43 - -## 1.167.42 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.168.42 - -## 1.167.41 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.168.41 - -## 1.167.40 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.168.40 - -## 1.167.39 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.168.39 - -## 1.167.38 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.168.38 - -## 1.167.37 - -### Patch Changes - -- Updated dependencies [[`49bcd4d`](https://github.com/TanStack/router/commit/49bcd4db743dba4a783d5533a42a0f97a5721292)]: - - @tanstack/router-plugin@1.168.37 - -## 1.167.36 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.168.36 - -## 1.167.35 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.168.35 - -## 1.167.34 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.168.34 - -## 1.167.33 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.168.33 - -## 1.167.32 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.168.32 - -## 1.167.31 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.168.31 - -## 1.167.30 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.168.30 - -## 1.167.29 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.168.29 - -## 1.167.28 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.168.28 - -## 1.167.27 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.168.27 - -## 1.167.26 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.168.26 - -## 1.167.25 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.168.25 - -## 1.167.24 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.168.24 - -## 1.167.23 - -### Patch Changes - -- Updated dependencies [[`49f6863`](https://github.com/TanStack/router/commit/49f686324574ea65851317cbba084eb386a911c6)]: - - @tanstack/router-plugin@1.168.23 - -## 1.167.22 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.168.22 - -## 1.167.21 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.168.21 - -## 1.167.20 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.168.20 - -## 1.167.19 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.168.19 - -## 1.167.18 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.168.18 - -## 1.167.17 - -### Patch Changes - -- Updated dependencies [[`837897f`](https://github.com/TanStack/router/commit/837897f0733b836dd63880546eec4c20cf06be59)]: - - @tanstack/router-plugin@1.168.17 - -## 1.167.16 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.168.16 - -## 1.167.15 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.168.15 - -## 1.167.14 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.168.14 - -## 1.167.13 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.168.13 - -## 1.167.12 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.168.12 - -## 1.167.11 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.168.11 - -## 1.167.10 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.168.10 - -## 1.167.9 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.168.9 - -## 1.167.8 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.168.8 - -## 1.167.7 - -### 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 - -## 1.167.6 - -### Patch Changes - -- Updated dependencies [[`b60eb36`](https://github.com/TanStack/router/commit/b60eb36e59e8a468ee0742cbcf7f47aca1ff1c67)]: - - @tanstack/router-plugin@1.168.6 - -## 1.167.5 - -### Patch Changes - -- Updated dependencies [[`8146db7`](https://github.com/TanStack/router/commit/8146db7e54f5d508f1fb7d3927edd0a2f71dc930)]: - - @tanstack/router-plugin@1.168.5 - -## 1.167.4 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.168.4 - -## 1.167.3 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.168.3 - -## 1.167.2 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.168.2 - -## 1.167.1 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@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 [[`201e150`](https://github.com/TanStack/router/commit/201e150bd1412bae2faa9ce53f0fefcb7574ac14)]: - - @tanstack/router-plugin@1.168.0 - -## 1.166.50 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.167.35 - -## 1.166.49 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.167.34 - -## 1.166.48 - -### Patch Changes - -- Updated dependencies [[`056337e`](https://github.com/TanStack/router/commit/056337ef02ccbeaf45ec8533a227761be869e8f3)]: - - @tanstack/router-plugin@1.167.33 - -## 1.166.47 - -### Patch Changes - -- Updated dependencies [[`96818b8`](https://github.com/TanStack/router/commit/96818b8ba5ead6f1f027094841330182aff415b2)]: - - @tanstack/router-plugin@1.167.32 - -## 1.166.46 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.167.31 - -## 1.166.45 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.167.30 - -## 1.166.44 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.167.29 - -## 1.166.43 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.167.28 - -## 1.166.42 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.167.27 - -## 1.166.41 - -### Patch Changes - -- Updated dependencies [[`8b97002`](https://github.com/TanStack/router/commit/8b97002af3f6d15204e60c55d3f5735b78bd7efe)]: - - @tanstack/router-plugin@1.167.26 - -## 1.166.40 - -### Patch Changes - -- Updated dependencies [[`1e371b6`](https://github.com/TanStack/router/commit/1e371b60f1832c158ff4953a4ae6c5ccfe8460b3)]: - - @tanstack/router-plugin@1.167.25 - -## 1.166.39 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.167.24 - -## 1.166.38 - -### Patch Changes - -- Updated dependencies [[`91a7089`](https://github.com/TanStack/router/commit/91a708989d00537a21911e74ff60bbfec8266295)]: - - @tanstack/router-plugin@1.167.23 - -## 1.166.37 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.167.22 - -## 1.166.36 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.167.21 - -## 1.166.35 - -### Patch Changes - -- Updated dependencies [[`96ac2d8`](https://github.com/TanStack/router/commit/96ac2d8ed378340d63b88afeec3633e56e29b5f8)]: - - @tanstack/router-plugin@1.167.20 - -## 1.166.34 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.167.19 - -## 1.166.33 - -### Patch Changes - -- Updated dependencies [[`656a2a0`](https://github.com/TanStack/router/commit/656a2a040e79df7721d776e3751c8d634666570b)]: - - @tanstack/router-plugin@1.167.18 - -## 1.166.32 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.167.17 - -## 1.166.31 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.167.16 - -## 1.166.30 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.167.15 - -## 1.166.29 - -### Patch Changes - -- Updated dependencies [[`6355bb7`](https://github.com/TanStack/router/commit/6355bb75f7637ba77f06a923c18fdaf37720bb48)]: - - @tanstack/router-plugin@1.167.14 - -## 1.166.28 - -### Patch Changes - -- Updated dependencies [[`459057c`](https://github.com/TanStack/router/commit/459057cd2d90cff20d20e51d4964b0a8c950555e)]: - - @tanstack/router-plugin@1.167.13 - -## 1.166.27 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.167.12 - -## 1.166.26 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.167.11 - -## 1.166.25 - -### Patch Changes - -- Updated dependencies [[`f8351a8`](https://github.com/TanStack/router/commit/f8351a8d7aa9f5a341377f96966451892acb39f1)]: - - @tanstack/router-plugin@1.167.10 - -## 1.166.24 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.167.9 - -## 1.166.23 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.167.8 - -## 1.166.22 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.167.7 - -## 1.166.21 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.167.6 - -## 1.166.20 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.167.5 - -## 1.166.19 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.167.4 - -## 1.166.18 - -### Patch Changes - -- Updated dependencies []: - - @tanstack/router-plugin@1.167.3 - ## 1.166.17 ### Patch Changes diff --git a/packages/router-vite-plugin/package.json b/packages/router-vite-plugin/package.json index 8e411904cb..fa4b497661 100644 --- a/packages/router-vite-plugin/package.json +++ b/packages/router-vite-plugin/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/router-vite-plugin", - "version": "1.167.49", + "version": "1.166.17", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", @@ -29,12 +29,12 @@ "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": "node ../../node_modules/typescript59/lib/tsc.js", - "test:types:ts60": "tsc6", - "test:types:ts70": "tsc", + "test:types:ts59": "tsc", "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", "build": "vite build" }, @@ -67,11 +67,6 @@ "@tanstack/router-plugin": "workspace:*" }, "devDependencies": { - "vite": "*", - "@tanstack/vite-config": "catalog:", - "vitest": "catalog:", - "@arethetypeswrong/cli": "catalog:", - "publint": "catalog:", - "rimraf": "catalog:" + "vite": "*" } } diff --git a/packages/router-vite-plugin/tsconfig.build.json b/packages/router-vite-plugin/tsconfig.build.json deleted file mode 100644 index 92be18587f..0000000000 --- a/packages/router-vite-plugin/tsconfig.build.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "rootDir": "./src" - }, - "include": ["src"] -} diff --git a/packages/router-vite-plugin/vite.config.ts b/packages/router-vite-plugin/vite.config.ts index 7401092b13..7e4ae12a99 100644 --- a/packages/router-vite-plugin/vite.config.ts +++ b/packages/router-vite-plugin/vite.config.ts @@ -6,7 +6,6 @@ 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/solid-router-devtools/CHANGELOG.md b/packages/solid-router-devtools/CHANGELOG.md index 709d8cd23d..5844cc0476 100644 --- a/packages/solid-router-devtools/CHANGELOG.md +++ b/packages/solid-router-devtools/CHANGELOG.md @@ -1,69 +1,51 @@ # @tanstack/solid-router-devtools -## 1.167.3 +## 2.0.0-alpha.4 ### Patch Changes -- Updated dependencies [[`bbf9b75`](https://github.com/TanStack/router/commit/bbf9b75808d8eee497a6dd1663f0cf08426512e0)]: - - @tanstack/router-devtools-core@1.168.3 +- Update to beta.4 ([#6991](https://github.com/TanStack/router/pull/6991)) -## 1.167.2 +- Updated dependencies [[`0f8dca9`](https://github.com/TanStack/router/commit/0f8dca93e7f8cd8f48d06d2dffa4e5d66c6b3b1e)]: + - @tanstack/solid-router@2.0.0-alpha.6 + +## 2.0.0-alpha.3 ### 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), [`9b2adaf`](https://github.com/TanStack/router/commit/9b2adaf8c3fca905f156c42f6a4fe17a787afcc8), [`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), [`9872d2a`](https://github.com/TanStack/router/commit/9872d2ac39fc05f4ef6566c0b421f71ceb115244), [`9b2adaf`](https://github.com/TanStack/router/commit/9b2adaf8c3fca905f156c42f6a4fe17a787afcc8), [`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/solid-router@1.170.34 - - @tanstack/router-devtools-core@1.168.2 +- fix: add vite 8 compat ([`dfd64e4`](https://github.com/TanStack/router/commit/dfd64e4a08e74ef292c6bd7baab77283c258bb92)) -## 1.167.1 +- Updated dependencies [[`dfd64e4`](https://github.com/TanStack/router/commit/dfd64e4a08e74ef292c6bd7baab77283c258bb92)]: + - @tanstack/solid-router@2.0.0-alpha.5 + +## 2.0.0-alpha.2 ### Patch Changes -- Updated dependencies [[`45c4ad8`](https://github.com/TanStack/router/commit/45c4ad8d629e291fab70c37900525449e415ffcd)]: - - @tanstack/router-core@1.171.16 - - @tanstack/solid-router@1.170.19 - - @tanstack/router-devtools-core@1.168.1 +- build: bundle packages with rolldown ([#6931](https://github.com/TanStack/router/pull/6931)) -## 1.167.0 +- Updated dependencies [[`b95b106`](https://github.com/TanStack/router/commit/b95b1061d34579e1fe7fd7ec781e743ec6fe31fe)]: + - @tanstack/solid-router@2.0.0-alpha.3 -### Minor Changes - -- Clean minor bump, fresh start ([#7395](https://github.com/TanStack/router/pull/7395)) +## 2.0.0-alpha.1 ### 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/router-devtools-core@1.168.0 - - @tanstack/solid-router@1.170.0 +- bump to alpha.1 ([`4c5bb71`](https://github.com/TanStack/router/commit/4c5bb71d320df8aa9cb41a67103b671335a1bb7d)) -## 1.166.13 +- Updated dependencies [[`4c5bb71`](https://github.com/TanStack/router/commit/4c5bb71d320df8aa9cb41a67103b671335a1bb7d)]: + - @tanstack/solid-router@2.0.0-alpha.1 + +## 2.0.0-alpha.0 + +### Major Changes + +- solid v2 pre-release for solid-router and start ([#6904](https://github.com/TanStack/router/pull/6904)) ### Patch Changes -- Updated dependencies [[`6355bb7`](https://github.com/TanStack/router/commit/6355bb75f7637ba77f06a923c18fdaf37720bb48)]: - - @tanstack/router-devtools-core@1.167.3 - - @tanstack/solid-router@1.168.14 - - @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/solid-router@1.168.13 - - @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/solid-router@1.168.2 - - @tanstack/router-core@1.168.2 +- Updated dependencies [[`a0191af`](https://github.com/TanStack/router/commit/a0191afd21afe0e7571af8b0faab171f62e71db7)]: + - @tanstack/solid-router@2.0.0-alpha.0 ## 1.166.10 diff --git a/packages/solid-router-devtools/README.md b/packages/solid-router-devtools/README.md index cf8c44252d..2011760db8 100644 --- a/packages/solid-router-devtools/README.md +++ b/packages/solid-router-devtools/README.md @@ -1,22 +1,5 @@ <img src="https://static.scarf.sh/a.png?x-pxid=d988eb79-b0fc-4a2b-8514-6a1ab932d188" /> -<div align="center"> - <picture> - <source - media="(prefers-color-scheme: dark)" - srcset="https://tanstack.com/api/readme/router.png?framework=solid&theme=dark" - /> - <source - media="(prefers-color-scheme: light)" - srcset="https://tanstack.com/api/readme/router.png?framework=solid" - /> - <img - src="https://tanstack.com/api/readme/router.png?framework=solid" - alt="TanStack Solid Router" - width="900" - /> - </picture> -</div> # TanStack Solid Router Devtools See https://tanstack.com/router/latest/docs/framework/solid/devtools diff --git a/packages/solid-router-devtools/package.json b/packages/solid-router-devtools/package.json index bcc006458f..b2a3283d39 100644 --- a/packages/solid-router-devtools/package.json +++ b/packages/solid-router-devtools/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/solid-router-devtools", - "version": "1.167.3", + "version": "2.0.0-alpha.4", "description": "Modern and scalable routing for Solid 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": "node ../../node_modules/typescript59/lib/tsc.js", - "test:types:ts60": "tsc6", - "test:types:ts70": "tsc", + "test:types:ts59": "tsc", "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", "build": "vite build && tsc -p tsconfig.build.json" }, @@ -66,23 +66,20 @@ "node": ">=20.19" }, "dependencies": { + "@solidjs/web": "2.0.0-beta.4", "@tanstack/router-devtools-core": "workspace:*" }, "devDependencies": { - "solid-js": "catalog:", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", "vite": "*", - "vite-plugin-solid": "catalog:", - "@types/node": ">=20", - "@tanstack/vite-config": "catalog:", - "vitest": "catalog:", - "@arethetypeswrong/cli": "catalog:", - "publint": "catalog:", - "rimraf": "catalog:" + "vite-plugin-solid": "3.0.0-next.3" }, "peerDependencies": { "@tanstack/router-core": "workspace:^", "@tanstack/solid-router": "workspace:^", - "solid-js": "^1.9.10" + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4" }, "peerDependenciesMeta": { "@tanstack/router-core": { diff --git a/packages/solid-router-devtools/src/TanStackRouterDevtools.tsx b/packages/solid-router-devtools/src/TanStackRouterDevtools.tsx index 7f46f33268..7e8772b709 100644 --- a/packages/solid-router-devtools/src/TanStackRouterDevtools.tsx +++ b/packages/solid-router-devtools/src/TanStackRouterDevtools.tsx @@ -1,6 +1,6 @@ import { useRouter, useRouterState } from '@tanstack/solid-router' import { TanStackRouterDevtoolsCore } from '@tanstack/router-devtools-core' -import { createEffect, createSignal, onCleanup, onMount } from 'solid-js' +import { createEffect, createSignal, onCleanup } from 'solid-js' import type { AnyRouter } from '@tanstack/solid-router' import type { Component, JSX } from 'solid-js' @@ -54,20 +54,20 @@ export const TanStackRouterDevtools: Component< routerState: activeRouterState, } - let devToolRef: HTMLDivElement | undefined + const [devToolRef, setDevToolRef] = createSignal<HTMLDivElement>() const [devtools] = createSignal(new TanStackRouterDevtoolsCore(usedProps)) // Update devtools when props change - createEffect(() => { - devtools().setRouter(usedProps.router) + createEffect(devtools, (d) => { + d.setRouter(usedProps.router) }) - createEffect(() => { - devtools().setRouterState(usedProps.routerState) + createEffect(devtools, (d) => { + d.setRouterState(usedProps.routerState) }) - createEffect(() => { - devtools().setOptions({ + createEffect(devtools, (d) => { + d.setOptions({ initialIsOpen: usedProps.initialIsOpen, panelProps: usedProps.panelProps, closeButtonProps: usedProps.closeButtonProps, @@ -78,19 +78,26 @@ export const TanStackRouterDevtools: Component< }) }) - onMount(() => { - if (devToolRef) { - devtools().mount(devToolRef) + createEffect( + () => ({ d: devtools(), el: devToolRef() }), + ({ d, el }) => { + if (el) { + d.mount(el) - onCleanup(() => { - devtools().unmount() - }) - } - }) + onCleanup(() => { + d.unmount() + }) + } + }, + ) return ( <> - <div ref={devToolRef} /> + <div + ref={(el) => { + setDevToolRef(el) + }} + /> </> ) } diff --git a/packages/solid-router-devtools/src/TanStackRouterDevtoolsPanel.tsx b/packages/solid-router-devtools/src/TanStackRouterDevtoolsPanel.tsx index dcacd451c7..36ff8c89fb 100644 --- a/packages/solid-router-devtools/src/TanStackRouterDevtoolsPanel.tsx +++ b/packages/solid-router-devtools/src/TanStackRouterDevtoolsPanel.tsx @@ -1,6 +1,6 @@ import { useRouter, useRouterState } from '@tanstack/solid-router' import { TanStackRouterDevtoolsPanelCore } from '@tanstack/router-devtools-core' -import { createEffect, createSignal, onCleanup, onMount } from 'solid-js' +import { createEffect, createSignal, onCleanup } from 'solid-js' import type { AnyRouter } from '@tanstack/solid-router' import type { Component, JSX } from 'solid-js' @@ -47,41 +47,44 @@ export const TanStackRouterDevtoolsPanel: Component< routerState: activeRouterState, } - let devToolRef: HTMLDivElement | undefined + const [devToolRef, setDevToolRef] = createSignal<HTMLDivElement>() const [devtools] = createSignal( new TanStackRouterDevtoolsPanelCore(usedProps), ) // Update devtools when props change - createEffect(() => { - devtools().setRouter(usedProps.router) + createEffect(devtools, (d) => { + d.setRouter(usedProps.router) }) - createEffect(() => { - devtools().setRouterState(usedProps.routerState) + createEffect(devtools, (d) => { + d.setRouterState(usedProps.routerState) }) - createEffect(() => { - devtools().setOptions({ + createEffect(devtools, (d) => { + d.setOptions({ className: usedProps.className, style: usedProps.style, shadowDOMTarget: usedProps.shadowDOMTarget, }) }) - onMount(() => { - if (devToolRef) { - devtools().mount(devToolRef) + createEffect( + () => ({ d: devtools(), el: devToolRef() }), + ({ d, el }) => { + if (el) { + d.mount(el) - onCleanup(() => { - devtools().unmount() - }) - } - }) + onCleanup(() => { + d.unmount() + }) + } + }, + ) return ( <> - <div ref={devToolRef} /> + <div ref={setDevToolRef} /> </> ) } diff --git a/packages/solid-router-devtools/tsconfig.build.json b/packages/solid-router-devtools/tsconfig.build.json index e460be5cfb..9ac13b1566 100644 --- a/packages/solid-router-devtools/tsconfig.build.json +++ b/packages/solid-router-devtools/tsconfig.build.json @@ -1,6 +1,8 @@ { - "extends": "./tsconfig.json", + "extends": "../../tsconfig.json", "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "solid-js", "moduleResolution": "Bundler", "rootDir": "src", "outDir": "dist/source", diff --git a/packages/solid-router-devtools/tsconfig.json b/packages/solid-router-devtools/tsconfig.json index 3e806f6d62..1b802b64d1 100644 --- a/packages/solid-router-devtools/tsconfig.json +++ b/packages/solid-router-devtools/tsconfig.json @@ -2,8 +2,7 @@ "extends": "../../tsconfig.json", "compilerOptions": { "jsx": "preserve", - "jsxImportSource": "solid-js", - "types": ["node"] + "jsxImportSource": "solid-js" }, "include": ["src", "vite.config.ts"] } diff --git a/packages/solid-router-devtools/vite.config.ts b/packages/solid-router-devtools/vite.config.ts index 633c31d005..53c000c53a 100644 --- a/packages/solid-router-devtools/vite.config.ts +++ b/packages/solid-router-devtools/vite.config.ts @@ -9,7 +9,6 @@ const config = defineConfig({ export default mergeConfig( config, tanstackViteConfig({ - tsconfigPath: './tsconfig.build.json', entry: './src/index.tsx', srcDir: './src', }), diff --git a/packages/solid-router-ssr-query/CHANGELOG.md b/packages/solid-router-ssr-query/CHANGELOG.md index bf0c385751..94c2dc1033 100644 --- a/packages/solid-router-ssr-query/CHANGELOG.md +++ b/packages/solid-router-ssr-query/CHANGELOG.md @@ -1,70 +1,54 @@ # @tanstack/solid-router-ssr-query -## 1.167.3 +## 2.0.0-alpha.6 ### 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. +- Update to beta.4 ([#6991](https://github.com/TanStack/router/pull/6991)) - 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 `<Scripts>` 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 `<Await>` without a `fallback` no longer holds the streamed shell; it renders inside the nearest `<Suspense>` 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 +## 2.0.0-alpha.5 ### Patch Changes -- Updated dependencies [[`79e3533`](https://github.com/TanStack/router/commit/79e35335b4bb1c3b5e2275a8df5181aa05036628)]: - - @tanstack/router-ssr-query-core@1.169.2 +- fix: use solid-query 6.0.0-alpha.0 ([#6989](https://github.com/TanStack/router/pull/6989)) -## 1.167.1 +## 2.0.0-alpha.4 ### Patch Changes -- Updated dependencies [[`d1997b6`](https://github.com/TanStack/router/commit/d1997b66d7c24c1d64772bb8bab5caf9c6d9cc48)]: - - @tanstack/router-ssr-query-core@1.169.1 +- fix: add vite 8 compat ([`dfd64e4`](https://github.com/TanStack/router/commit/dfd64e4a08e74ef292c6bd7baab77283c258bb92)) -## 1.167.0 - -### Minor Changes - -- Clean minor bump, fresh start ([#7395](https://github.com/TanStack/router/pull/7395)) +## 2.0.0-alpha.3 ### Patch Changes -- Updated dependencies [[`201e150`](https://github.com/TanStack/router/commit/201e150bd1412bae2faa9ce53f0fefcb7574ac14)]: - - @tanstack/router-ssr-query-core@1.169.0 +- fix: use solid v2 compatible solid-query ([#6938](https://github.com/TanStack/router/pull/6938)) -## 1.166.12 +## 2.0.0-alpha.2 ### Patch Changes -- Updated dependencies [[`b12f57b`](https://github.com/TanStack/router/commit/b12f57bbb44e47d5452d46e9e67ea4d63cdb5b55)]: - - @tanstack/router-ssr-query-core@1.168.0 +- build: bundle packages with rolldown ([#6931](https://github.com/TanStack/router/pull/6931)) -## 1.166.11 +## 2.0.0-alpha.1 ### Patch Changes -- Updated dependencies [[`459057c`](https://github.com/TanStack/router/commit/459057cd2d90cff20d20e51d4964b0a8c950555e)]: - - @tanstack/router-ssr-query-core@1.167.1 +- bump to alpha.1 ([`4c5bb71`](https://github.com/TanStack/router/commit/4c5bb71d320df8aa9cb41a67103b671335a1bb7d)) + +- Updated dependencies [[`4c5bb71`](https://github.com/TanStack/router/commit/4c5bb71d320df8aa9cb41a67103b671335a1bb7d)]: + - @tanstack/solid-router@2.0.0-alpha.1 + +## 2.0.0-alpha.0 + +### Major Changes + +- solid v2 pre-release for solid-router and start ([#6904](https://github.com/TanStack/router/pull/6904)) + +### Patch Changes + +- Updated dependencies [[`a0191af`](https://github.com/TanStack/router/commit/a0191afd21afe0e7571af8b0faab171f62e71db7)]: + - @tanstack/solid-router@2.0.0-alpha.0 ## 1.166.10 diff --git a/packages/solid-router-ssr-query/README.md b/packages/solid-router-ssr-query/README.md index 2aadc50710..f7c1691123 100644 --- a/packages/solid-router-ssr-query/README.md +++ b/packages/solid-router-ssr-query/README.md @@ -1,18 +1,4 @@ -<picture> - <source - media="(prefers-color-scheme: dark)" - srcset="https://tanstack.com/api/readme/router.png?framework=solid&theme=dark" - /> - <source - media="(prefers-color-scheme: light)" - srcset="https://tanstack.com/api/readme/router.png?framework=solid" - /> - <img - src="https://tanstack.com/api/readme/router.png?framework=solid" - alt="TanStack Solid Router" - width="900" - /> -</picture> +![TanStack Router Header](https://raw.githubusercontent.com/TanStack/router/main/media/header_router.png) # @tanstack/solid-router-ssr-query diff --git a/packages/solid-router-ssr-query/package.json b/packages/solid-router-ssr-query/package.json index 4b1ece0f78..cbc5f76d56 100644 --- a/packages/solid-router-ssr-query/package.json +++ b/packages/solid-router-ssr-query/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/solid-router-ssr-query", - "version": "1.167.3", + "version": "2.0.0-alpha.6", "description": "Modern and scalable routing for Solid 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": "node ../../node_modules/typescript59/lib/tsc.js", - "test:types:ts60": "tsc6", - "test:types:ts70": "tsc", + "test:types:ts59": "tsc", "test:unit": "exit 0; vitest", "test:unit:dev": "pnpm run test:unit --watch", "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", @@ -67,23 +67,19 @@ "@tanstack/router-ssr-query-core": "workspace:*" }, "devDependencies": { - "@tanstack/solid-query": ">=5.102.0", + "@solidjs/web": "2.0.0-beta.4", + "@tanstack/solid-query": "6.0.0-alpha.1", "@tanstack/solid-router": "workspace:*", "eslint-plugin-solid": "^0.14.5", - "solid-js": "catalog:", + "solid-js": "2.0.0-beta.4", "vite": "*", - "vite-plugin-solid": "catalog:", - "@tanstack/vite-config": "catalog:", - "vitest": "catalog:", - "jsdom": "catalog:", - "@arethetypeswrong/cli": "catalog:", - "publint": "catalog:", - "rimraf": "catalog:" + "vite-plugin-solid": "3.0.0-next.3" }, "peerDependencies": { - "@tanstack/query-core": ">=5.102.0", - "@tanstack/solid-query": ">=5.102.0", - "@tanstack/solid-router": ">=1.170.31", - "solid-js": "^1.9.10" + "@solidjs/web": "2.0.0-beta.4", + "@tanstack/query-core": ">=5.90.0", + "@tanstack/solid-query": ">=5.90.0", + "@tanstack/solid-router": ">=2.0.0-alpha.1", + "solid-js": "2.0.0-beta.4" } } diff --git a/packages/solid-router-ssr-query/tsconfig.build.json b/packages/solid-router-ssr-query/tsconfig.build.json deleted file mode 100644 index 92be18587f..0000000000 --- a/packages/solid-router-ssr-query/tsconfig.build.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "rootDir": "./src" - }, - "include": ["src"] -} diff --git a/packages/solid-router-ssr-query/vite.config.ts b/packages/solid-router-ssr-query/vite.config.ts index 52b38213cb..08669023b8 100644 --- a/packages/solid-router-ssr-query/vite.config.ts +++ b/packages/solid-router-ssr-query/vite.config.ts @@ -17,7 +17,6 @@ const config = defineConfig({ export default mergeConfig( config, tanstackViteConfig({ - tsconfigPath: './tsconfig.build.json', entry: './src/index.tsx', srcDir: './src', }), diff --git a/packages/solid-router/CHANGELOG.md b/packages/solid-router/CHANGELOG.md index 3a40aa28c3..92edcac826 100644 --- a/packages/solid-router/CHANGELOG.md +++ b/packages/solid-router/CHANGELOG.md @@ -1,666 +1,46 @@ # @tanstack/solid-router -## 1.170.43 +## 2.0.0-alpha.6 ### 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/<package>#<skill>`) instead of relative file links that break once packages are installed. +- Update to beta.4 ([#6991](https://github.com/TanStack/router/pull/6991)) -- Updated dependencies [[`32a3360`](https://github.com/TanStack/router/commit/32a3360cba0e0f884b3215813a48c63467f5a53c)]: - - @tanstack/router-core@1.171.39 - -## 1.170.42 - -### Patch Changes - -- Updated dependencies [[`18154b1`](https://github.com/TanStack/router/commit/18154b1c45454a70aa77e9d6d27c8a6e0733d031)]: - - @tanstack/router-core@1.171.38 - -## 1.170.41 - -### Patch Changes - -- Updated dependencies [[`d6ba115`](https://github.com/TanStack/router/commit/d6ba115d5751c75e20943f0062577cf17b446d82)]: - - @tanstack/router-core@1.171.37 - -## 1.170.40 - -### Patch Changes - -- Updated dependencies [[`94d6d8e`](https://github.com/TanStack/router/commit/94d6d8e49694e225cb07e2a6777633d08aeeb3c5)]: - - @tanstack/router-core@1.171.36 - -## 1.170.39 - -### Patch Changes - -- [#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. - -- [#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. - -- [#8619](https://github.com/TanStack/router/pull/8619) [`e7ab157`](https://github.com/TanStack/router/commit/e7ab1570ec3ba461cd1ef2c75d5fab2011cf1043) - Solid Links resolve their own props through one reactive memo instead of two, which makes mounting and updating many Links slightly faster. - -- [#8602](https://github.com/TanStack/router/pull/8602) [`efc2042`](https://github.com/TanStack/router/commit/efc2042c2d02a9780c3e7efe81f123d066a869eb) - Solid and Vue Links reuse the router's built destination across navigations and derive their state through fewer reactive nodes. Solid Links call a user `ref` once per element and create no reactive nodes on the server. - -- 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.38 - -### Patch Changes - -- Updated dependencies [[`d521abd`](https://github.com/TanStack/router/commit/d521abd71c69f1ff010bb3def4d417cb5fa058cb)]: - - @tanstack/router-core@1.171.34 - -## 1.170.37 - -### 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.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 - -## 1.170.35 - -### 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 `<Scripts>` 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 `<Await>` without a `fallback` no longer holds the streamed shell; it renders inside the nearest `<Suspense>` 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 - -## 1.170.34 - -### Patch Changes - -- [#8318](https://github.com/TanStack/router/pull/8318) [`9b2adaf`](https://github.com/TanStack/router/commit/9b2adaf8c3fca905f156c42f6a4fe17a787afcc8) - Keep Solid Link's computed `href`, `target`, and `disabled` values authoritative when active or inactive state props contain routing options, while preserving state-prop refs, event handlers, and class/style merging. - -- [#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. - -- [#8318](https://github.com/TanStack/router/pull/8318) [`9b2adaf`](https://github.com/TanStack/router/commit/9b2adaf8c3fca905f156c42f6a4fe17a787afcc8) - Reduce Link bundle size by sharing exact/fuzzy active-path checks and resolving only the selected active or inactive props. Avoid unnecessary class/style allocations while preserving reactive style updates, server rendering, and each framework's prop-override behavior. - -- 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.33 - -### Patch Changes - -- [#8316](https://github.com/TanStack/router/pull/8316) [`b1c9219`](https://github.com/TanStack/router/commit/b1c92194397e57cecfab72de70e2dd8064a4f6d5) - Skip client-only hydration, preloading, observer, and event-handler setup for all server-rendered links. - -- [#8270](https://github.com/TanStack/router/pull/8270) [`76239a3`](https://github.com/TanStack/router/commit/76239a34b732ca19d1b16d42efb83824b1de1c69) - Avoid duplicate external script execution when a Solid script includes both `src` and children. Reuse each Solid hydration boundary's marker element instead of scanning all document markers on mount. - -## 1.170.32 - -### 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. - -- 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.31 - -### 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<TError>` 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`. - -- 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.30 +## 2.0.0-alpha.5 ### 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. +- fix: add vite 8 compat ([`dfd64e4`](https://github.com/TanStack/router/commit/dfd64e4a08e74ef292c6bd7baab77283c258bb92)) -- [#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.29 - -### Patch Changes - -- Updated dependencies [[`3e016ac`](https://github.com/TanStack/router/commit/3e016ac84ffec8119f0c25cfdd1fb17e5292bd34)]: - - @tanstack/router-core@1.171.26 - -## 1.170.28 - -### Patch Changes - -- [#8084](https://github.com/TanStack/router/pull/8084) [`5d3785d`](https://github.com/TanStack/router/commit/5d3785dcc366b66b1c261b5d01e66af778ff1175) - preserve pending UI across retained routes - -- 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.27 - -### 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.26 - -### 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. - -- [#8002](https://github.com/TanStack/router/pull/8002) [`3848503`](https://github.com/TanStack/router/commit/38485038c52ff898777cabeeeb2eaaa29c93f789) - Keep active route components mounted by default when route params change. - -- Updated dependencies [[`31882c7`](https://github.com/TanStack/router/commit/31882c7fa87debef236228831655cb112c20ce90)]: - - @tanstack/router-core@1.171.23 - -## 1.170.25 +## 2.0.0-alpha.4 ### 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. +- Bump to solid js 2.0.0-beta.3 ([#6943](https://github.com/TanStack/router/pull/6943)) -- Updated dependencies [[`7e93431`](https://github.com/TanStack/router/commit/7e93431ae9ff58c91c3c5ca10ffcb8414c1d0b13)]: - - @tanstack/router-core@1.171.22 - -## 1.170.24 +## 2.0.0-alpha.3 ### Patch Changes -- Updated dependencies [[`51138a8`](https://github.com/TanStack/router/commit/51138a824cea053738f125c4c95073bd6286ff05)]: - - @tanstack/router-core@1.171.21 - -## 1.170.23 - -### 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.22 - -### Patch Changes - -- Updated dependencies [[`ea3a665`](https://github.com/TanStack/router/commit/ea3a665d81cbb5074c2d77ec953255ab534e7db9)]: - - @tanstack/router-core@1.171.19 - -## 1.170.21 - -### Patch Changes - -- [#7970](https://github.com/TanStack/router/pull/7970) [`2435885`](https://github.com/TanStack/router/commit/2435885fa8b5e31c8c4b74d93920919f27316ebf) - createFileRoute does not rely on FileRoute class - -- [#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) - -- [#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 +- build: bundle packages with rolldown ([#6931](https://github.com/TanStack/router/pull/6931)) -## 1.170.20 +## 2.0.0-alpha.2 ### Patch Changes -- Updated dependencies [[`b2908c6`](https://github.com/TanStack/router/commit/b2908c642ac09aa08e6d965d2a820d7186e42fd5)]: - - @tanstack/router-core@1.171.17 +- Upgrade solid refresh, fix deep equal for promises ([#6910](https://github.com/TanStack/router/pull/6910)) -## 1.170.19 +## 2.0.0-alpha.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`). +- bump to alpha.1 ([`4c5bb71`](https://github.com/TanStack/router/commit/4c5bb71d320df8aa9cb41a67103b671335a1bb7d)) - **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<boolean>` (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 - -- [#7584](https://github.com/TanStack/router/pull/7584) [`41e7a24`](https://github.com/TanStack/router/commit/41e7a24f693b0f58c2bef89a2b8c4d084acbd531) - Remove unnecessary setTimeout from Match components - -## 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 - -- 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 - -- Fix hydration mismatch for ssr='data-only' with pendingComponent ([#7266](https://github.com/TanStack/router/pull/7266)) - -## 1.168.23 - -### Patch Changes - -- Fix for useLoaderData sometimes going undefined ([#7265](https://github.com/TanStack/router/pull/7265)) - -- Fix streaming when using Await component ([#7264](https://github.com/TanStack/router/pull/7264)) - -## 1.168.22 - -### Patch Changes - -- fix server middleware type in solid-router ([#7260](https://github.com/TanStack/router/pull/7260)) - -- Enhanced internal tag comparison logic to optimize stylesheet persistence during route navigation. ([#7250](https://github.com/TanStack/router/pull/7250)) - -## 1.168.21 - -### 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.20 - -### Patch Changes - -- fix: use keyed Show in Outlet to fix child route rendering with useQuery ([#7204](https://github.com/TanStack/router/pull/7204)) - -## 1.168.19 - -### Patch Changes - -- Updated dependencies [[`16f6892`](https://github.com/TanStack/router/commit/16f6892d6b7ceadf606677c5a40e743f29163aa6)]: - - @tanstack/router-core@1.168.15 - -## 1.168.18 - -### 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.17 - -### Patch Changes - -- Updated dependencies [[`0e2c900`](https://github.com/TanStack/router/commit/0e2c9003c18ae07c09969189c028f277ea562a7a)]: - - @tanstack/router-core@1.168.14 - -## 1.168.16 - -### Patch Changes - -- Updated dependencies [[`812792f`](https://github.com/TanStack/router/commit/812792fbda3caf97b300770855cf5641252f413b)]: - - @tanstack/router-core@1.168.13 - -## 1.168.15 - -### Patch Changes - -- Updated dependencies [[`8ec9ca9`](https://github.com/TanStack/router/commit/8ec9ca97b472779de878c2a6510f21deb24d386c)]: - - @tanstack/router-core@1.168.12 - -## 1.168.14 - -### 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.13 - -### 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.12 - -### 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)) - -## 1.168.11 - -### 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.10 - -### 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.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)) - -- Updated dependencies [[`796406d`](https://github.com/TanStack/router/commit/796406da66cfb12b518bb3ca326c9d541368fb06)]: - - @tanstack/router-core@1.168.9 - -## 1.168.8 - -### Patch Changes - -- Updated dependencies [[`2d1ec86`](https://github.com/TanStack/router/commit/2d1ec865a446926f7db6e29dbbde82d265de6d36)]: - - @tanstack/router-core@1.168.8 - -## 1.168.7 - -### Patch Changes - -- Updated dependencies [[`6ee0e79`](https://github.com/TanStack/router/commit/6ee0e795b085651beb2f1ac6503cdbd7eaffedd1)]: - - @tanstack/router-core@1.168.7 - -## 1.168.6 - -### Patch Changes - -- Updated dependencies [[`42c3f3b`](https://github.com/TanStack/router/commit/42c3f3b3a3a478fd6d6894310ef94b2d23794b8e)]: - - @tanstack/router-core@1.168.6 - -## 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 - -- 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 +## 2.0.0-alpha.0 -- Replace tiny-invariant and tiny-warning with in-house solution for bundle-size ([#7007](https://github.com/TanStack/router/pull/7007)) +### Major Changes -- Updated dependencies [[`c9e1855`](https://github.com/TanStack/router/commit/c9e18555f3a5531e96de8f574cfca9edcdb18e5c)]: - - @tanstack/router-core@1.168.2 +- solid v2 pre-release for solid-router and start ([#6904](https://github.com/TanStack/router/pull/6904)) ## 1.168.1 diff --git a/packages/solid-router/README.md b/packages/solid-router/README.md index 3e41f35f1b..94a0f37468 100644 --- a/packages/solid-router/README.md +++ b/packages/solid-router/README.md @@ -2,21 +2,7 @@ # TanStack Solid Router -<picture> - <source - media="(prefers-color-scheme: dark)" - srcset="https://tanstack.com/api/readme/router.png?framework=solid&theme=dark" - /> - <source - media="(prefers-color-scheme: light)" - srcset="https://tanstack.com/api/readme/router.png?framework=solid" - /> - <img - src="https://tanstack.com/api/readme/router.png?framework=solid" - alt="TanStack Solid Router" - width="900" - /> -</picture> +![TanStack Router Header](https://raw.githubusercontent.com/TanStack/router/main/media/header_router.png) 🤖 Type-safe router w/ built-in caching & URL state management for Solid! diff --git a/packages/solid-router/bin/intent.js b/packages/solid-router/bin/intent.js new file mode 100755 index 0000000000..5b08532885 --- /dev/null +++ b/packages/solid-router/bin/intent.js @@ -0,0 +1,25 @@ +#!/usr/bin/env node +// Auto-generated by @tanstack/intent setup +// Exposes the intent end-user CLI for consumers of this library. +// Commit this file, then add to your package.json: +// "bin": { "intent": "./bin/intent.js" } +try { + await import('@tanstack/intent/intent-library') +} catch (e) { + const isModuleNotFound = + e?.code === 'ERR_MODULE_NOT_FOUND' || e?.code === 'MODULE_NOT_FOUND' + const missingIntentLibrary = + typeof e?.message === 'string' && e.message.includes('@tanstack/intent') + + if (isModuleNotFound && missingIntentLibrary) { + console.error('@tanstack/intent is not installed.') + console.error('') + console.error('Install it as a dev dependency:') + console.error(' npm add -D @tanstack/intent') + console.error('') + console.error('Or run directly:') + console.error(' npx @tanstack/intent@latest list') + process.exit(1) + } + throw e +} diff --git a/packages/solid-router/package.json b/packages/solid-router/package.json index 80840069ea..5c1bed81b8 100644 --- a/packages/solid-router/package.json +++ b/packages/solid-router/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/solid-router", - "version": "1.170.43", + "version": "2.0.0-alpha.6", "description": "Modern and scalable routing for Solid applications", "author": "Tanner Linsley", "license": "MIT", @@ -27,12 +27,12 @@ "clean": "rimraf ./dist && rimraf ./coverage", "test:eslint": "eslint", "test:types": "pnpm run \"/^test:types:ts[0-9]{2}$/\"", + "test:types: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": "node ../../node_modules/typescript59/lib/tsc.js -p tsconfig.legacy.json", - "test:types:ts60": "tsc6 -p tsconfig.legacy.json", - "test:types:ts70": "tsc -p tsconfig.legacy.json", + "test:types:ts59": "tsc -p tsconfig.legacy.json", "test:unit": "vitest && vitest --mode server", "test:unit:dev": "pnpm run test:unit --watch --hideSkippedTests", "test:perf": "vitest bench", @@ -104,29 +104,32 @@ "node": ">=20.19" }, "dependencies": { - "@solid-primitives/refs": "^1.0.8", + "@solid-devtools/logger": "^0.9.4", "@solidjs/meta": "^0.29.4", + "@solidjs/web": "2.0.0-beta.4", "@tanstack/history": "workspace:*", "@tanstack/router-core": "workspace:*", - "isbot": "catalog:" + "isbot": "^5.1.22", + "tiny-invariant": "^1.3.3", + "tiny-warning": "^1.0.3" }, "devDependencies": { "@solidjs/testing-library": "^0.8.10", - "@testing-library/jest-dom": "catalog:", - "@types/node": ">=20", - "combinate": "catalog:", - "solid-js": "catalog:", + "@tanstack/intent": "^0.0.14", + "@testing-library/jest-dom": "^6.6.3", + "combinate": "^1.1.11", + "eslint-plugin-solid": "^0.14.5", + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4", "vite": "*", - "vite-plugin-solid": "catalog:", - "zod": "catalog:", - "@tanstack/vite-config": "catalog:", - "vitest": "catalog:", - "jsdom": "catalog:", - "@arethetypeswrong/cli": "catalog:", - "publint": "catalog:", - "rimraf": "catalog:" + "vite-plugin-solid": "3.0.0-next.3", + "zod": "^3.23.8" }, "peerDependencies": { - "solid-js": "^1.9.10" + "solid-js": "2.0.0-beta.4", + "@solidjs/web": "2.0.0-beta.4" + }, + "bin": { + "intent": "./bin/intent.js" } } diff --git a/packages/solid-router/skills/solid-router/SKILL.md b/packages/solid-router/skills/solid-router/SKILL.md index e6bff33a42..75c82805df 100644 --- a/packages/solid-router/skills/solid-router/SKILL.md +++ b/packages/solid-router/skills/solid-router/SKILL.md @@ -8,11 +8,10 @@ description: >- Outlet, CatchBoundary, ErrorComponent. Solid-specific patterns with Accessor<T> returns, createSignal/createMemo/createEffect, Show/Switch/Match/Dynamic, and @solidjs/meta for head management. -metadata: - type: framework - library: tanstack-router - library_version: '1.166.2' - framework: solid +type: framework +library: tanstack-router +library_version: '1.166.2' +framework: solid requires: - router-core sources: @@ -21,7 +20,9 @@ sources: # Solid Router (`@tanstack/solid-router`) -This skill builds on router-core. Read `@tanstack/router-core#router-core` first for foundational concepts. +This skill builds on router-core. Read [router-core](../../../router-core/skills/router-core/SKILL.md) first for foundational concepts. + +This skill covers the Solid-specific bindings, components, hooks, and setup for TanStack Router. > **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. @@ -495,4 +496,4 @@ Must set `target: 'solid'` in the router plugin config. Default is `'react'`. ## Cross-References -- `@tanstack/router-core#router-core` — all sub-skills for domain-specific patterns (search params, data loading, navigation, auth, SSR, etc.) +- [router-core/SKILL.md](../../../router-core/skills/router-core/SKILL.md) — all sub-skills for domain-specific patterns (search params, data loading, navigation, auth, SSR, etc.) diff --git a/packages/solid-router/src/Asset.tsx b/packages/solid-router/src/Asset.tsx index 37c7c97a4e..586d91e2d3 100644 --- a/packages/solid-router/src/Asset.tsx +++ b/packages/solid-router/src/Asset.tsx @@ -1,145 +1,124 @@ -import { Link, Meta, Style, Title } from '@solidjs/meta' -import { onCleanup, onMount } from 'solid-js' import { isServer } from '@tanstack/router-core/isServer' +import { createEffect } from 'solid-js' import { useRouter } from './useRouter' import type { RouterManagedTag } from '@tanstack/router-core' import type { JSX } from 'solid-js' -const INLINE_CSS_HYDRATION_ATTR = 'data-tsr-inline-css' - -export function Asset(asset: RouterManagedTag): JSX.Element | null { - const { tag, attrs, children } = asset - +export function Asset({ + tag, + attrs, + children, +}: RouterManagedTag): JSX.Element | null { switch (tag) { case 'title': - return <Title {...attrs}>{children} + return case 'meta': - return <Meta {...attrs} /> + return <meta {...attrs} /> case 'link': - return <Link {...attrs} /> + return <link {...attrs} /> case 'style': - if ( - asset.inlineCss && - (process.env.TSS_INLINE_CSS_ENABLED === 'true' || - (process.env.TSS_INLINE_CSS_ENABLED === undefined && isServer)) - ) { - return <InlineCssStyle attrs={attrs}>{children}</InlineCssStyle> + if (typeof children === 'string') { + return <style {...attrs} innerHTML={children} /> } - - return <Style {...attrs}>{children}</Style> + return <style {...attrs} /> case 'script': - return <Script attrs={attrs}>{children}</Script> + return <Script attrs={attrs} children={children} /> default: return null } } -function InlineCssStyle({ - attrs, - children, -}: { +function Title(props: { attrs?: Record<string, any> - children?: RouterManagedTag['children'] -}) { - const isInlineCssPlaceholder = children === undefined - const html = isInlineCssPlaceholder - ? typeof document === 'undefined' - ? '' - : (document.querySelector<HTMLStyleElement>( - `style[${INLINE_CSS_HYDRATION_ATTR}]`, - )?.textContent ?? '') - : (children ?? '') - - return ( - <Style {...attrs} {...{ [INLINE_CSS_HYDRATION_ATTR]: '' }}> - {html} - </Style> - ) -} - -interface ScriptAttrs { - [key: string]: string | boolean | undefined - src?: string -} - -function Script({ - attrs, - children, -}: { - attrs?: ScriptAttrs - children?: string + children?: unknown }): JSX.Element | null { const router = useRouter() + const attrs = props.attrs + const children = props.children + + // Server: render <title> normally + if (isServer ?? router.isServer) { + return <title {...attrs}>{children as string} + } + + // Client: imperatively set document.title so it updates during + // client-side navigation (JSX in <head> doesn't reliably + // update the browser's document.title). + createEffect( + () => children, + (titleText) => { + document.title = typeof titleText === 'string' ? titleText : '' + }, + ) + + // Still render the <title> element in the DOM for consistency, + // but the imperative assignment above is what actually drives the update. + return <title {...attrs}>{children as string} +} + +function Script(props: { + attrs?: Record + children?: unknown +}): JSX.Element | null { + const router = useRouter() + const attrs = props.attrs + const children = props.children + const dataScript = typeof attrs?.type === 'string' && attrs.type !== '' && attrs.type !== 'text/javascript' && attrs.type !== 'module' - onMount(() => { - if (dataScript) return - + // --- Server rendering --- + if (isServer ?? router.isServer) { if (attrs?.src) { - const normSrc = (() => { - try { - const base = document.baseURI || window.location.href - return new URL(attrs.src, base).href - } catch { - return attrs.src + return + + + + + `, + { + 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 deleted file mode 100644 index d88ddb60d0..0000000000 --- a/packages/start-plugin-core/src/hydrate-when-transform.ts +++ /dev/null @@ -1,1004 +0,0 @@ -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 deleted file mode 100644 index b79c20ffd3..0000000000 --- a/packages/start-plugin-core/src/hydration-constants.ts +++ /dev/null @@ -1 +0,0 @@ -export const tssHydrate = 'tss-hydrate' diff --git a/packages/start-plugin-core/src/import-protection-plugin/INTERNALS.md b/packages/start-plugin-core/src/import-protection-plugin/INTERNALS.md new file mode 100644 index 0000000000..0143b11161 --- /dev/null +++ b/packages/start-plugin-core/src/import-protection-plugin/INTERNALS.md @@ -0,0 +1,700 @@ +# Import Protection Plugin — Internal Technical Documentation + +## Overview + +The import protection plugin prevents server-only code from leaking into client +bundles (and vice versa). It operates as a Vite plugin that intercepts module +resolution, detects violations, and either errors or replaces the offending +module with a safe mock. + +The plugin must handle **two axes of configuration**: + +| | **Dev** (`vite dev`) | **Build** (`vite build`) | +| --------- | -------------------------------------------------------------------- | -------------------------------------------------------------- | +| **Error** | `ctx.error()` immediately in `resolveId` | Defer to `generateBundle`; error if mock survived tree-shaking | +| **Mock** | Defer to transform-cache; warn if reachable via post-transform graph | Defer to `generateBundle`; warn if mock survived tree-shaking | + +## Plugin Architecture + +`importProtectionPlugin()` returns **two** Vite plugins: + +### 1. `tanstack-start-core:import-protection` (enforce: `'pre'`) + +The main enforcement plugin. Hooks: `applyToEnvironment`, `configResolved`, +`configureServer`, `buildStart`, `hotUpdate`, `resolveId`, `load`, and +`generateBundle`. All violation detection starts in `resolveId`. + +### 2. `tanstack-start-core:import-protection-transform-cache` + +Runs after all `enforce: 'pre'` hooks (including the Start compiler). Caches +transformed code and composed sourcemaps for accurate source-location mapping +in violation messages. Also resolves post-transform imports and triggers +`processPendingViolations()` for the dev mock deferral path. + +In both build and dev modes, this plugin performs **self-denial**: when a file +matches a deny pattern in the current environment (e.g. a `.server.ts` file +transformed in the client environment), its entire content is replaced 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. In dev mode, the +mock imports a `mock-runtime` module for runtime diagnostics; in build mode, +the mock is fully self-contained. + +See the [Self-Denial Transform](#self-denial-transform-in-detail) section below +for a detailed walkthrough with code examples. + +## Violation Types + +| Type | Trigger | Example | +| ----------- | --------------------------------------------------------------------------------------- | ------------------------------------------------------- | +| `file` | Resolved path matches a deny glob (e.g. `**/*.server.*`) | `import './db.server'` in client env | +| `specifier` | Import specifier matches a deny pattern | `import '@tanstack/react-start/server'` in client env | +| `marker` | File imports `'server-only'` or `'client-only'` marker, then is loaded in the wrong env | File with `import 'server-only'` resolved in client env | + +## The False-Positive Problem + +### Barrel re-exports + +A common pattern: + +```text +db/index.ts → export { getUsers } from './db.server' + export { userColumns } from './shared' + +route.tsx → import { getUsers, userColumns } from '../db' + // getUsers used only in createServerFn().handler() + // userColumns used in JSX +``` + +At `resolveId` time, `db/index.ts` imports `./db.server` — the plugin sees a +`.server` file imported in the client environment. But the Start compiler strips +the `getUsers` usage from the client bundle (it's inside a server fn handler), +and Rollup's tree-shaking then eliminates the `./db.server` dependency entirely. + +**No server code actually leaks.** But without deferral, the plugin fires at +`resolveId` time — before tree-shaking — producing a false positive. + +### Pre-transform resolves (server-fn-lookup) + +During dev, Vite's `fetchModule(?SERVER_FN_LOOKUP)` call triggers resolves for +analysing a module's exports. These are tracked via `serverFnLookupModules` and +`isPreTransformResolve`. In dev mock mode, pre-transform violations are +deferred like all other violations (verified via edge-survival and graph +reachability). In dev error mode, they are silenced because no deferred +verification path exists. + +## Violation Handling Flow + +### Central functions + +- **`handleViolation()`**: Formats + reports (or silences) the violation. Returns + a resolve result so `resolveId` can substitute the offending import: for + file-based violations, returns the physical file path (self-denial handles + the rest in transform); for specifier/marker violations, returns a mock-edge + module ID. May also return `undefined` (suppressed by `onViolation` or + silent+error in dev) or throw via `ctx.error()` (dev+error). +- **`reportOrDeferViolation()`**: Dispatch layer. Either defers (stores for later + verification) or reports immediately, depending on `shouldDefer`. + +### `shouldDefer` logic + +```ts +shouldDefer = isBuild || isDevMock +``` + +- **Dev mock**: ALL violations (including pre-transform resolves) are deferred + to `pendingViolations` → verified via edge-survival and post-transform graph + reachability in `processPendingViolations()`. Pre-transform violations are + tagged with `fromPreTransformResolve` so the pending-violation processor + knows to wait for post-transform data before emitting. +- **Build (both mock and error)**: Defer to `deferredBuildViolations` → verify + via tree-shaking survival in `generateBundle`. + +All three violation types (file, specifier, AND marker) are deferred in build +mode. Marker violations through barrels can also be false positives — e.g., if +`foo.ts` has `import 'server-only'` and is re-exported through a barrel but +never used in client code, tree-shaking eliminates `foo.ts` entirely. To enable +`generateBundle` tracking for markers, `resolveId` returns the unique build +mock ID instead of the marker module. This is transparent because marker imports +are bare (`import 'server-only'` — no bindings), and the mock module is equally +side-effect-free. + +## Dev Mode Strategy + +### Dev + Error + +Violations fire immediately via `ctx.error()` in `resolveId`. No tree-shaking +is available, so false positives for barrel patterns are expected and accepted. +(Dev + error is typically used only during explicit validation.) + +Pre-transform resolves (e.g. server-fn-lookup) are silenced in error mode +because they fire before the Start compiler runs — imports inside `.server()` +callbacks haven't been stripped yet, and error mode has no deferred verification +path. + +### Dev + Mock + +1. `resolveId` detects the violation and calls `reportOrDeferViolation()`. +2. For **file-based violations**: `handleViolation()` returns the **physical + file path** (same as build mode). The self-denial transform in the + transform-cache plugin will replace the file's content with a dev mock + module that imports `mock-runtime` for runtime diagnostics. +3. For **specifier/marker violations**: `handleViolation()` returns a mock-edge + module ID so the dev server can serve a Proxy-based mock. +4. The violation is stored in `pendingViolations` keyed by the importer's file + path. +5. The transform-cache plugin, after resolving post-transform imports, calls + `processPendingViolations()`. +6. `processPendingViolations()` first applies **edge-survival**: if + post-transform import data is available for the importer, it checks whether + the denied import survived the Start compiler transform. Imports stripped + by the compiler (e.g. inside `.server()` callbacks) are discarded. For + pre-transform violations (`fromPreTransformResolve`), the function waits + until post-transform data is available before proceeding. +7. After edge-survival, `processPendingViolations()` checks graph reachability + from entry points using only post-transform edges. If the violating + importer is reachable → confirm (warn). If unreachable → discard. If + unknown → keep pending or emit conservatively (warm-start fallback). + +Warm-start stability guardrails: + +- Resolve-time edges discovered through pre-transform paths + (`isPreTransformResolve`, especially `SERVER_FN_LOOKUP`) are **not** recorded + into the reachability graph. +- In `'unknown'` reachability status, pre-transform pending violations are + kept pending (not fallback-emitted) until non-lookup transform evidence is + available. + +This approach can't fully eliminate barrel false-positives in dev because +there's no tree-shaking. The barrel's import of `.server` always resolves, +and the barrel is reachable. This is a known and accepted limitation. + +### Dev mock modules + +Dev violations are handled differently depending on their type: + +- **File-based violations** use **self-denial** (same mechanism as build mode): + the denied file's content is replaced by the transform-cache plugin with a + mock that imports `mock-runtime` for runtime diagnostics. The export list + comes from the **denied file's AST** (what it exports), generated by + `generateDevSelfDenialModule()`. This approach avoids the cold-start problem + where the importer's AST is unavailable at `resolveId` time, and prevents + cross-environment cache contamination from third-party resolver plugins. + +- **Specifier/marker violations** use **mock-edge modules**: each violation + gets a per-importer mock edge module that explicitly exports the names the + importer expects (extracted lazily by `resolveExportsForDeniedSpecifier()` + which parses the importer's AST) and delegates to a **runtime mock module** + that contains a recursive Proxy and optional runtime diagnostics. + +### Mock edge modules (in detail) + +A **mock edge module** is a lightweight, auto-generated virtual module that sits +between an importing file and a base mock module. Its purpose is to provide +**explicit ESM named exports** so that bundlers (Rollup, Rolldown) and Vite's dev +server can correctly resolve `import { foo } from './denied.server'` — even +though the real module has been replaced by a mock. + +#### Why they exist + +The base mock module (`\0tanstack-start-import-protection:mock`) exports only a +`default` export — a recursive Proxy. But consumers of the denied module may use +named imports: + +```typescript +import { getSecret, initDb } from './credentials.server' +``` + +Without explicit named exports, this would fail: the bundler would complain that +`getSecret` and `initDb` don't exist on the mock module. Using +`syntheticNamedExports: true` in Rollup could solve this, but Rolldown (which +Vite can now use) doesn't support it. Mock edge modules solve the problem +portably by generating real ESM export statements. + +#### Structure + +Each mock edge module is identified by a virtual ID: + +```text +\0tanstack-start-import-protection:mock-edge: +``` + +The Base64URL payload encodes two fields: + +- `exports` — the list of named export identifiers the importer needs +- `runtimeId` — the module ID of the backing mock to import from + +When Vite's `load` hook encounters this virtual ID, `loadMockEdgeModule()` +decodes the payload and generates code like this: + +```typescript +// Generated mock edge module for exports: ["getSecret", "initDb"] +import mock from '\0tanstack-start-import-protection:mock' +export const getSecret = mock.getSecret +export const initDb = mock.initDb +export default mock +``` + +Each `mock.getSecret` access returns the Proxy itself (the Proxy's `get` trap +returns `mock` for any property), so the named exports are valid callable/ +constructable values that won't crash at runtime. + +#### How exports are determined + +The export list comes from **parsing the importer's AST** — not the denied +file's AST. The function `resolveExportsForDeniedSpecifier()` performs this: + +1. Gets the importer's code from the transform cache or `getModuleInfo`. +2. Calls `collectMockExportNamesBySource()` to extract which names the + importer uses from each import source (parses the AST internally): + - **Named imports**: `import { getSecret, initDb } from './creds.server'` + → `['getSecret', 'initDb']` + - **Namespace member access**: `import * as creds from './creds.server'` then + `creds.getSecret()` → `['getSecret']` + - **Default import member access**: `import creds from './creds.server'` then + `creds.getSecret` → `['getSecret']` + - **Re-exports**: `export { getSecret } from './creds.server'` + → `['getSecret']` +3. Caches the result per importer so multiple violations from the same file + don't re-parse. + +This "importer-driven" approach means the mock edge module only exports the +names the consumer actually references — not all exports from the denied file. + +#### Dev vs build mock edge modules + +| Aspect | Dev mock edge | Build mock edge | +| ---------------- | ---------------------------------------------------------------- | ---------------------------------------------------------------- | +| **Backing mock** | `mock-runtime:BASE64` (runtime diagnostics) or `mock` (silent) | `mock:build:N` (per-violation unique, silent) | +| **Purpose** | Serve mocks in dev server + runtime warnings | Track tree-shaking survival in `generateBundle` | +| **Created for** | Specifier/marker violations only (file uses self-denial instead) | Specifier/marker violations only (file uses self-denial instead) | +| **Uniqueness** | Per-importer per-specifier | Per-violation (unique counter) | + +In **dev**, the backing `runtimeId` is a `mock-runtime:BASE64` module that +includes diagnostic metadata (environment, import path, trace). When the mock +is accessed in the browser, it logs a console warning or error. For SSR or +when `mockAccess` is `'off'`, the backing mock is the shared silent +`MOCK_MODULE_ID`. + +In **build**, the backing mock uses a unique counter ID +(`mock:build:0`, `mock:build:1`, ...) so `generateBundle` can check whether +each specific violation's mock survived tree-shaking. + +#### Handling non-identifier export names + +ES2022 allows string-keyed exports like `export { x as "foo-bar" }`. Mock edge +modules handle these via an intermediate variable: + +```typescript +import mock from '\0tanstack-start-import-protection:mock' +export const validName = mock.validName +const __tss_str_0 = mock['foo-bar'] +export { __tss_str_0 as 'foo-bar' } +``` + +The `default` export name is always filtered out (handled separately as +`export default mock`). + +### File-based violations: self-denial (dev and build) + +File-based violations (e.g. `import './db.server'` in client env) use +self-denial in **both** dev and build modes. `handleViolation()` returns the +physical file path, and the transform-cache plugin replaces the file's +contents with a mock module. + +- **Build mode**: Uses `generateSelfContainedMockModule()` — a fully + self-contained mock with an inlined Proxy factory (no `import` statements). + This is important because build-mode mocks must be tree-shakeable. + +- **Dev mode**: Uses `generateDevSelfDenialModule()` — a mock that imports + `mock-runtime` for runtime diagnostics (console warnings/errors when the + mock is accessed in the browser). The `mock-runtime` module ID encodes + violation metadata (environment, import path, trace). + +Self-denial avoids creating virtual mock-edge module IDs that could +contaminate third-party resolver caches across Vite environments. + +### Non-file violations: mock-edge modules (dev and build) + +Specifier and marker violations use **mock-edge modules** because the denied +specifier doesn't resolve to a physical file that could be "self-denied." + +- **Build mode**: Each violation gets a **per-violation mock edge module** + wrapping a unique base mock module + (`\0tanstack-start-import-protection:mock:build:N`). The edge module + re-exports the named exports the importer expects, ensuring compatibility + with both Rollup and Rolldown (which doesn't support + `syntheticNamedExports`). + +- **Dev mode**: Each violation gets a **per-importer mock edge module** + wrapping a `mock-runtime` module for runtime diagnostics. + +## Build Mode Strategy + +### The "mock first, verify later" pattern + +Both mock and error build modes follow the same pattern: + +1. **`resolveId`**: Call `handleViolation({ silent: true })`. + - For **file-based violations**: Returns the physical file path. The + self-denial transform will replace its content. + - For **specifier/marker violations**: Generates a **unique per-violation + mock-edge module** wrapping a base mock module + (`\0tanstack-start-import-protection:mock:build:N`). Stores the violation + + mock-edge ID in `env.deferredBuildViolations`. Returns the mock-edge ID. + +2. **`transform`** (self-denial): For file-based violations, the transform-cache + plugin detects that the current file is denied in this environment and + replaces its content with a self-contained mock module + (`generateSelfContainedMockModule()`). + +3. **`load`**: For base mock modules, returns a silent Proxy-based mock. For + mock-edge modules, returns code that imports from the base mock and + re-exports the expected named bindings (e.g. `export const Foo = mock.Foo`). + +4. **Tree-shaking**: The bundler processes the bundle normally. If no binding from + the mock module is actually used at runtime, the modules are eliminated. + +5. **`generateBundle`**: Inspect the output chunks. For each deferred violation, + check whether its unique mock module ID appears in any chunk's `modules`. + - **Survived** → real violation (the import wasn't tree-shaken away). + - Error mode: `ctx.error()` — fail the build. + - Mock mode: `ctx.warn()` — emit a warning. + - **Eliminated** → false positive (tree-shaking removed it). Suppress + silently. + +### Why unique mock IDs per violation? + +The original `RESOLVED_MOCK_MODULE_ID` is a single shared virtual module used +for all mock-mode violations. If multiple violations are deferred, we need to +know _which specific ones_ survived tree-shaking. A shared ID would tell us +"something survived" but not which violation it corresponds to. Each violation +gets a unique mock-edge module (wrapping a unique base mock +`...mock:build:0`, `...mock:build:1`, etc.) to provide this granularity. + +### Why mocking doesn't affect tree-shaking + +From the consumer's perspective, the import bindings are identical whether they +point to the real module or the mock. The bundler tree-shakes based on binding +usage, not module content. If a binding from the barrel's re-export of `.server` +is unused after the Start compiler strips server fn handlers, tree-shaking +eliminates it regardless of whether it points to real DB code or a Proxy mock. + +### Per-environment operation + +`generateBundle` runs once per Vite environment (client, SSR, etc.). Each +environment has its own `EnvState` with its own `deferredBuildViolations` array. +The check only inspects chunks from THAT environment's bundle, ensuring correct +per-environment verification. + +## Marker violations vs. file/specifier violations + +| | Marker | Specifier | File | +| ----------------------------- | --------------------------------------------------- | -------------------------------------------- | --------------------------------------------- | +| **What triggers it** | The _importer_ has a conflicting directive | The _import specifier_ matches a deny rule | The _resolved path_ matches a deny glob | +| **resolveId returns (dev)** | Marker module ID (`RESOLVED_MARKER_*`) \* | Mock edge module ID (per-importer) | Physical file path (self-denial in transform) | +| **resolveId returns (build)** | Unique build mock ID | Unique build mock ID | Physical file path (self-denial in transform) | +| **Can be tree-shaken away?** | Yes — if the importer is eliminated by tree-shaking | Yes — if no binding from the target survives | Yes — if no binding from the target survives | +| **Deferred in build?** | Yes — deferred to `generateBundle` | Yes — deferred to `generateBundle` | Yes — deferred to `generateBundle` | +| **Deferred in dev mock?** | Yes — deferred to pending graph | Yes — deferred to pending graph | Yes — deferred to pending graph | + +\* In dev mock, `handleViolation` internally returns the physical file path +(stored as the deferred result in `pendingViolations`), but `resolveId` ignores +it for markers and falls through to return the marker module ID. The file path +is only used for deferral bookkeeping, not for module resolution. + +## State Management + +### `EnvState` (per Vite environment) + +Key fields for violation handling: + +- `seenViolations: Set` — deduplication of logged violations. +- `pendingViolations: Map>` — dev mock + deferral. Keyed by importer file path. +- `deferredBuildViolations: Array` — build mode + deferral. Each entry has `{ info, mockModuleId }`. + +Per-build/watch iteration, `buildStart` clears `pendingViolations` and resets +`deferredBuildViolations` so deferred entries don't leak across rebuilds. + +- `graph: ImportGraph` — import dependency graph for reachability checks. +- `serverFnLookupModules: Set` — modules transitively loaded during + server-fn analysis (false-positive suppression). + +### `SharedState` (cross-environment) + +- `fileMarkerKind: Map` — cached per-file marker + detection. A file's directive is inherent to the file, not the environment. + +## Virtual Module IDs + +| ID Pattern | Usage | +| -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | +| `\0tanstack-start-import-protection:mock` | Shared silent mock (dev mock only) | +| `\0tanstack-start-import-protection:mock:build:N` | Per-violation build mock (unique counter) | +| `\0tanstack-start-import-protection:mock-edge:BASE64` | Per-importer mock with explicit named exports (specifier/marker violations, dev + build) | +| `\0tanstack-start-import-protection:mock-runtime:BASE64` | Runtime diagnostic mock (dev client, console warnings) | +| `\0tanstack-start-import-protection:marker:*` | Marker module (empty `export {}`). Suffixed `server-only` or `client-only`; derived from `MARKER_PREFIX` in `virtualModules.ts` | + +## Key Design Decisions + +### Why not just skip `.server` resolves in barrels? + +The plugin doesn't know at `resolveId` time whether the barrel's re-export will +survive tree-shaking. It can't inspect the consumer's usage — it only sees the +barrel importing `.server`. Skipping it would miss real violations where the +barrel's `.server` re-export IS used in client code. + +### How marker violations are deferred in build + +Marker violations normally resolve to `RESOLVED_MARKER_*` (empty `export {}`), +not a mock. To enable `generateBundle` tracking, in build mode `resolveId` +returns the unique build mock ID instead of the marker module. This works +because: + +1. The marker import is bare (`import 'server-only'` — no bindings), so + swapping the resolution to a mock module is transparent. +2. The mock module is side-effect-free, just like the marker module. +3. If the importer file survives tree-shaking, the mock module survives → + `generateBundle` fires the violation. If the importer is tree-shaken away + (e.g., barrel re-export of a marker-protected file that's never used), the + mock is eliminated → violation suppressed. + +### Why accept false positives in dev? + +Dev mode uses Vite's ESM dev server — no bundling, no tree-shaking. The barrel +file's import of `.server` always resolves and is always reachable from entry +points. The graph-reachability check in `processPendingViolations` can only +eliminate violations where the _importer_ becomes unreachable after the Start +compiler transforms it, not where individual bindings are unused. + +This is an accepted trade-off: dev mock mode warns about potential issues, +build mode provides definitive answers via tree-shaking. + +## E2E Test Structure + +Tests live in `e2e/react-start/import-protection/` and +`e2e/react-start/import-protection-custom-config/`: + +### Main test suite (`import-protection/`) + +- **Mock mode** (default): `globalSetup` builds the app, captures build warnings + to `violations.build.json`, starts a dev server capturing to + `violations.dev.json`. Tests read these JSON files and assert. +- **Error mode** (`BEHAVIOR=error`): `globalSetup` runs the build expecting + failure, captures exit code + output. Tests assert the build failed with the + expected violation. +- **False-positive test**: The `barrel-reexport` test case verifies that a barrel + re-exporting from both a `.server` file and a marker-protected file (`foo.ts` + with `import 'server-only'`), where all server-only bindings are tree-shaken + away, produces **zero** violations in the build log. + +### Custom-config test suite (`import-protection-custom-config/`) + +Uses non-default deny patterns (`**/*.backend.*` / `**/*.frontend.*`) to verify +that import protection works with user-configured file patterns. This ensures +the plugin doesn't hardcode any assumption about `.server`/`.client` naming +conventions. The `vite.config.ts` provides custom `client.files` and +`server.files` arrays; no `vite-tsconfig-paths` is used. + +## Self-Denial Transform (In Detail) + +The self-denial transform is the mechanism by which the plugin prevents cross- +environment contamination without creating virtual module IDs that could leak +through third-party resolver caches. It applies to **file-based violations in +both dev and build modes**. + +### The problem it solves + +In Vite 7+, client and SSR environments run within the same Vite process. Some +plugins (e.g. `vite-tsconfig-paths`) maintain a global resolution cache shared +across environments. If the import-protection plugin resolves a specifier to a +virtual mock module ID (e.g. +`\0tanstack-start-import-protection:mock-edge:...`) in the client environment, +that virtual ID can leak into the SSR environment's cache. When the SSR +environment later resolves the same specifier, it finds the cached virtual ID +instead of the real file — breaking the server. + +In dev mode, self-denial also solves a **cold-start problem**: on cold start +(no `.vite` cache), the importer's AST is unavailable when `resolveId` runs +(neither the transform cache nor `getModuleInfo` have content yet). If mock-edge +module IDs were generated at `resolveId` time, the export list would be empty +(since it's derived from parsing the importer), producing a mock with no named +exports — causing runtime errors like +`does not provide an export named: 'getSecret'`. + +### How it works + +Instead of returning a virtual module ID from `resolveId`, the self-denial +transform works at the **transform** stage: + +1. **`resolveId`**: For file-based violations, `handleViolation()` returns the + **physical file path**. The import resolves normally. No virtual ID is + created. + +2. **transform-cache plugin**: When the transform-cache hook processes a file, + it checks whether the file matches any deny pattern for the current + environment using `checkFileDenial()`. If the file is denied, the plugin: + + a. Extracts the file's named exports using `collectNamedExports()` (parses + the AST internally). + b. **Build mode**: Generates a self-contained mock module via + `generateSelfContainedMockModule()` — no imports, inlined Proxy factory. + c. **Dev mode**: Generates a dev mock module via + `generateDevSelfDenialModule()` — imports `mock-runtime` for runtime + diagnostics (console warnings/errors when the mock is accessed). + d. Returns the mock code as the transform result, completely replacing the + original file content. + +3. **Fallback**: If AST parsing fails (e.g. due to syntax errors in the denied + file), `exportNames` defaults to `[]` (empty) and the mock module has no + named exports: + - Build: `generateSelfContainedMockModule([])`. + - Dev: `generateDevSelfDenialModule([], runtimeId)` where `runtimeId` is + computed via `mockRuntimeModuleIdFromViolation()` (which may internally + fall back to the shared silent `MOCK_MODULE_ID` for SSR or when + `mockAccess` is `'off'`). + +### Code transformation example + +**Original file** (`src/lib/credentials.server.ts`): + +```typescript +import { db } from './database' + +export function getSecret(): string { + return db.query('SELECT secret FROM config LIMIT 1') +} + +export const API_KEY = process.env.API_KEY! + +export default { getSecret, API_KEY } +``` + +**After self-denial transform in build mode** (client environment): + +```typescript +/* @__NO_SIDE_EFFECTS__ */ +function createMock() { + const handler = { + get: (_, prop) => { + if (prop === Symbol.toPrimitive) return () => 'MOCK' + if (typeof prop === 'symbol') return undefined + return mock + }, + apply: () => mock, + construct: () => mock, + } + const mock = /* @__PURE__ */ new Proxy(function () {}, handler) + return mock +} +const mock = /* @__PURE__ */ createMock() +export const getSecret = mock.getSecret +export const API_KEY = mock.API_KEY +export default mock +``` + +**After self-denial transform in dev mode** (client environment): + +```typescript +import mock from '\0tanstack-start-import-protection:mock-runtime:eyJ...' +export const getSecret = mock.getSecret +export const API_KEY = mock.API_KEY +export default mock +``` + +The `mock-runtime` module ID encodes violation metadata (environment, importer, +specifier, trace) as a Base64URL payload. When the mock is accessed in the +browser, it logs a console warning or error with this metadata. + +### Key properties + +**Build-mode mock** (`generateSelfContainedMockModule`): + +- **Self-contained**: No `import` statements — the Proxy factory is inlined. +- **Tree-shakeable**: All exports are marked pure (`@__NO_SIDE_EFFECTS__`, + `@__PURE__`), so the bundler can eliminate unused exports. + +**Dev-mode mock** (`generateDevSelfDenialModule`): + +- **Runtime diagnostics**: Imports `mock-runtime` which provides console + warnings/errors when the mock is accessed in the browser. +- **Lightweight**: No inlined Proxy factory — delegates to the mock-runtime + virtual module. + +**Both modes**: + +- **Same export interface**: Named exports match the original file's exports, + so consumers' import bindings remain valid. +- **Safe at runtime**: Every access returns the same Proxy, which is callable, + constructable, and returns "MOCK" when coerced to a string. +- **Export accuracy from denied file**: Unlike mock-edge modules (which parse + the importer's AST), self-denial parses the **denied file's own AST**. + This provides a safe over-approximation — all exports the file offers — and + avoids the cold-start problem where the importer hasn't been transformed yet. + +### Why self-denial instead of virtual modules for file-based violations + +| Approach | Virtual mock ID | Self-denial | +| ------------------ | -------------------------------------------------------------- | -------------------------------------------------------------- | +| `resolveId` return | `\0mock-edge:BASE64` (virtual) | Physical file path (resolves normally) | +| Cache risk | Virtual ID stored in shared resolver cache → leaks to SSR | Physical path cached → correct in both environments | +| Module identity | New virtual module per violation | Same physical file, different content per environment | +| Export accuracy | From importer's AST (what it imports) | From denied file's AST (what it exports) | +| Cold-start safety | Fails — importer AST unavailable on cold start → empty exports | Safe — denied file's source code always available in transform | + +### When self-denial is NOT used + +Self-denial only applies to **file-based** violations. + +- **Specifier violations** (e.g. `import '@tanstack/react-start/server'`): + These are bare specifiers, not file paths. They use virtual mock-edge module + IDs because the specifier doesn't resolve to a physical file that could be + "self-denied." +- **Marker violations**: Use virtual mock IDs in build mode for + `generateBundle` tracking (see marker section above). In dev mode, markers + resolve to the marker module ID directly. + +## Module Dependency Architecture + +The import-protection plugin is structured to avoid heavy transitive +dependencies in its utility modules: + +```text +constants.ts ← lightweight (no heavy imports) +├── IMPORT_PROTECTION_DEBUG +├── KNOWN_SOURCE_EXTENSIONS +├── SERVER_FN_LOOKUP_QUERY ← imports SERVER_FN_LOOKUP from parent constants.ts +└── VITE_BROWSER_VIRTUAL_PREFIX + +defaults.ts ← lightweight (type-only imports) +├── getDefaultImportProtectionRules +└── getMarkerSpecifiers + +matchers.ts ← picomatch only +├── compileMatcher +├── compileMatchers +└── matchesAny + +utils.ts ← vite + node:path + local constants +├── normalizeFilePath, stripViteQuery, ... +└── extractImportSources, dedupePatterns, ... + +trace.ts ← imports from utils only +├── ImportGraph +├── buildTrace +└── formatViolation + +virtualModules.ts ← imports ../utils (parent), ../constants (parent) +├── generateSelfContainedMockModule, generateDevSelfDenialModule +├── loadMockEdgeModule, loadMockRuntimeModule +└── MOCK_MODULE_ID, MOCK_EDGE_PREFIX, ... + +plugin.ts ← main plugin, imports everything above +``` + +The `SERVER_FN_LOOKUP` constant lives in the shared parent `constants.ts` +(not in `start-compiler-plugin/plugin.ts`) to avoid pulling in +`@tanstack/start-server-core` when unit-testing import-protection modules. diff --git a/packages/start-plugin-core/src/import-protection-plugin/ast.ts b/packages/start-plugin-core/src/import-protection-plugin/ast.ts new file mode 100644 index 0000000000..2c8a4b73ed --- /dev/null +++ b/packages/start-plugin-core/src/import-protection-plugin/ast.ts @@ -0,0 +1,7 @@ +import { parseAst } from '@tanstack/router-utils' + +export type ParsedAst = ReturnType + +export function parseImportProtectionAst(code: string): ParsedAst { + return parseAst({ code }) +} diff --git a/packages/start-plugin-core/src/import-protection-plugin/constants.ts b/packages/start-plugin-core/src/import-protection-plugin/constants.ts new file mode 100644 index 0000000000..9c3b596550 --- /dev/null +++ b/packages/start-plugin-core/src/import-protection-plugin/constants.ts @@ -0,0 +1,25 @@ +import { SERVER_FN_LOOKUP } from '../constants' + +export const SERVER_FN_LOOKUP_QUERY = `?${SERVER_FN_LOOKUP}` + +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-plugin/defaults.ts similarity index 100% rename from packages/start-plugin-core/src/import-protection/defaults.ts rename to packages/start-plugin-core/src/import-protection-plugin/defaults.ts diff --git a/packages/start-plugin-core/src/import-protection/extensionlessAbsoluteIdResolver.ts b/packages/start-plugin-core/src/import-protection-plugin/extensionlessAbsoluteIdResolver.ts similarity index 100% rename from packages/start-plugin-core/src/import-protection/extensionlessAbsoluteIdResolver.ts rename to packages/start-plugin-core/src/import-protection-plugin/extensionlessAbsoluteIdResolver.ts diff --git a/packages/start-plugin-core/src/import-protection/matchers.ts b/packages/start-plugin-core/src/import-protection-plugin/matchers.ts similarity index 78% rename from packages/start-plugin-core/src/import-protection/matchers.ts rename to packages/start-plugin-core/src/import-protection-plugin/matchers.ts index a5dc23a957..65a33078e4 100644 --- a/packages/start-plugin-core/src/import-protection/matchers.ts +++ b/packages/start-plugin-core/src/import-protection-plugin/matchers.ts @@ -4,16 +4,9 @@ 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.). @@ -32,14 +25,6 @@ export function compileMatcher(pattern: Pattern): CompiledMatcher { } } - if (isLiteralMatcherPattern(pattern)) { - return { - pattern, - literal: pattern, - test: (value: string) => value === pattern, - } - } - const isMatch = picomatch(pattern, { dot: true }) return { pattern, test: isMatch } } diff --git a/packages/start-plugin-core/src/import-protection-plugin/plugin.ts b/packages/start-plugin-core/src/import-protection-plugin/plugin.ts new file mode 100644 index 0000000000..ed3bad7e73 --- /dev/null +++ b/packages/start-plugin-core/src/import-protection-plugin/plugin.ts @@ -0,0 +1,2150 @@ +import { normalizePath } from 'vite' + +import { resolveViteId } from '../utils' +import { VITE_ENVIRONMENT_NAMES } from '../constants' +import { ImportGraph, buildTrace, formatViolation } from './trace' +import { + getDefaultImportProtectionRules, + getMarkerSpecifiers, +} from './defaults' +import { compileMatchers, matchesAny } from './matchers' +import { + buildResolutionCandidates, + buildSourceCandidates, + canonicalizeResolvedId, + clearNormalizeFilePathCache, + debugLog, + dedupePatterns, + escapeRegExp, + extractImportSources, + getOrCreate, + isInsideDirectory, + matchesDebugFilter, + normalizeFilePath, + relativizePath, + shouldDeferViolation, +} from './utils' +import { + collectMockExportNamesBySource, + collectNamedExports, + rewriteDeniedImports, +} from './rewriteDeniedImports' +import { + MOCK_BUILD_PREFIX, + generateDevSelfDenialModule, + generateSelfContainedMockModule, + getResolvedVirtualModuleMatchers, + loadResolvedVirtualModule, + makeMockEdgeModuleId, + mockRuntimeModuleIdFromViolation, + resolveInternalVirtualModuleId, + resolvedMarkerVirtualModuleId, +} from './virtualModules' +import { ExtensionlessAbsoluteIdResolver } from './extensionlessAbsoluteIdResolver' +import { + IMPORT_PROTECTION_DEBUG, + SERVER_FN_LOOKUP_QUERY, + VITE_BROWSER_VIRTUAL_PREFIX, +} from './constants' +import { + ImportLocCache, + addTraceImportLocations, + buildCodeSnippet, + buildLineIndex, + findImportStatementLocationFromTransformed, + findPostCompileUsageLocation, + pickOriginalCodeFromSourcesContent, +} from './sourceLocation' +import type { PluginOption, ViteDevServer } from 'vite' +import type { CompiledMatcher } from './matchers' +import type { Loc, TraceStep, ViolationInfo } from './trace' +import type { + SourceMapLike, + TransformResult, + TransformResultProvider, +} from './sourceLocation' +import type { ImportProtectionOptions } from '../schema' +import type { + EnvRules, + EnvState, + HandleViolationResult, + ImportProtectionPluginOptions, + ModuleGraphNode, + PendingViolation, + PluginConfig, + SharedState, + ViolationReporter, +} from './types' + +export type { ImportProtectionPluginOptions } from './types' + +export function importProtectionPlugin( + opts: ImportProtectionPluginOptions, +): PluginOption { + let devServer: ViteDevServer | null = null + const extensionlessIdResolver = new ExtensionlessAbsoluteIdResolver() + const resolveExtensionlessAbsoluteId = (id: string) => + extensionlessIdResolver.resolve(id) + + const importPatternCache = new Map>() + + function findFirstImportSpecifierIndex(code: string, source: string): number { + let patterns = importPatternCache.get(source) + if (!patterns) { + const escaped = escapeRegExp(source) + patterns = [ + new RegExp(`\\bimport\\s+(['"])${escaped}\\1`), + new RegExp(`\\bfrom\\s+(['"])${escaped}\\1`), + new RegExp(`\\bimport\\s*\\(\\s*(['"])${escaped}\\1\\s*\\)`), + ] + importPatternCache.set(source, patterns) + } + + let best = -1 + for (const re of patterns) { + const m = re.exec(code) + if (!m) continue + const idx = m.index + m[0].indexOf(source) + if (idx === -1) continue + if (best === -1 || idx < best) best = idx + } + return best + } + + /** + * 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', + 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() } + + /** + * Build the best available trace for a module and enrich each step with + * line/column locations. Tries the plugin's own ImportGraph first, then + * Vite's moduleGraph (authoritative on warm start), keeping whichever is + * longer. Annotates the last step with the denied specifier + location. + * + * 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, + findFirstImportSpecifierIndex, + ) + + 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 complete {@link ViolationInfo} with trace, location, and snippet. + * + * This is the single path that all violation types go through: specifier, + * file, and marker. + */ + async function buildViolationInfo( + provider: TransformResultProvider, + env: EnvState, + envName: string, + envType: 'client' | 'server', + importer: string, + normalizedImporter: string, + source: string, + overrides: Omit< + ViolationInfo, + | 'env' + | 'envType' + | 'behavior' + | 'specifier' + | 'importer' + | 'trace' + | 'snippet' + | 'importerLoc' + >, + traceOverride?: Array, + ): Promise { + const sourceCandidates = buildSourceCandidates( + source, + 'resolved' in overrides && typeof overrides.resolved === 'string' + ? overrides.resolved + : undefined, + config.root, + ) + + const loc = await resolveImporterLocation( + provider, + env, + importer, + sourceCandidates, + ) + + const trace = await rebuildAndAnnotateTrace( + provider, + env, + envName, + normalizedImporter, + source, + loc, + traceOverride, + ) + + const snippet = loc ? buildCodeSnippet(provider, importer, loc) : undefined + + return { + env: envName, + envType, + behavior: config.effectiveBehavior, + specifier: source, + importer: normalizedImporter, + ...(loc ? { importerLoc: loc } : {}), + trace, + snippet, + ...overrides, + } + } + + async function resolveImporterLocation( + provider: TransformResultProvider, + env: EnvState, + importer: string, + sourceCandidates: Iterable, + ): Promise { + for (const candidate of sourceCandidates) { + const loc = + (await findPostCompileUsageLocation(provider, importer, candidate)) || + (await findImportStatementLocationFromTransformed( + provider, + importer, + candidate, + env.importLocCache, + findFirstImportSpecifierIndex, + )) + if (loc) return loc + } + return undefined + } + + /** + * 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. + */ + async function buildMarkerViolationFromResolvedImport( + provider: TransformResultProvider, + env: EnvState, + envName: string, + envType: 'client' | 'server', + importer: string, + source: string, + resolvedId: string, + relativePath: string, + traceOverride?: Array, + ): Promise { + 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( + provider, + env, + envName, + envType, + importer, + normalizedImporter, + source, + { + type: 'marker', + resolved: normalizedResolvedId, + message: buildMarkerViolationMessage(relativePath, markerKind), + }, + traceOverride, + ) + } + + function buildMarkerViolationMessage( + relativePath: string, + markerKind: 'server' | 'client' | undefined, + ): string { + return markerKind === 'server' + ? `Module "${relativePath}" is marked server-only but is imported in the client environment` + : `Module "${relativePath}" is marked client-only but is imported in the server environment` + } + + async function buildFileViolationInfo( + provider: TransformResultProvider, + env: EnvState, + envName: string, + envType: 'client' | 'server', + importer: string, + normalizedImporter: string, + source: string, + resolvedPath: string, + pattern: string | RegExp, + traceOverride?: Array, + ): Promise { + const relativePath = getRelativePath(resolvedPath) + + return buildViolationInfo( + provider, + env, + envName, + envType, + importer, + normalizedImporter, + source, + { + type: 'file', + pattern, + resolved: resolvedPath, + message: `Import "${source}" (resolved to "${relativePath}") is denied in the ${envType} environment`, + }, + traceOverride, + ) + } + + function getEnvType(envName: string): 'client' | 'server' { + return config.envTypeMap.get(envName) ?? 'server' + } + + function getRulesForEnvironment(envName: string): EnvRules { + const type = getEnvType(envName) + return type === 'client' + ? config.compiledRules.client + : config.compiledRules.server + } + + /** + * Check if a relative path matches any denied file pattern for the given + * environment, respecting `excludeFiles`. Returns the matching pattern + * or `undefined` if the file is not denied. + */ + function checkFileDenial( + relativePath: string, + matchers: { + files: Array + excludeFiles: Array + }, + ): CompiledMatcher | undefined { + if ( + matchers.excludeFiles.length > 0 && + matchesAny(relativePath, matchers.excludeFiles) + ) { + return undefined + } + return matchers.files.length > 0 + ? matchesAny(relativePath, matchers.files) + : undefined + } + + 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 = collectMockExportNamesBySource(importerCode) + + // 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 + + for (const [source, names] of namesBySource) { + try { + const resolvedId = await resolveSource(source) + if (!resolvedId) continue + + namesBySource.set(normalizeFilePath(resolvedId), names) + namesBySource.set(resolveExtensionlessAbsoluteId(resolvedId), names) + } catch { + // Best-effort only + } + } + + 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 { + let result = shouldCheckImporterCache.get(importer) + if (result !== undefined) return result + + const relativePath = relativizePath(importer, config.root) + + // Excluded or ignored importers are never checked. + const excluded = + (config.excludeMatchers.length > 0 && + matchesAny(relativePath, config.excludeMatchers)) || + (config.ignoreImporterMatchers.length > 0 && + matchesAny(relativePath, config.ignoreImporterMatchers)) + + if (excluded) { + result = false + } else if (config.includeMatchers.length > 0) { + result = !!matchesAny(relativePath, config.includeMatchers) + } else if (config.srcDirectory) { + result = isInsideDirectory(importer, config.srcDirectory) + } else { + result = true + } + + shouldCheckImporterCache.set(importer, result) + return result + } + + function dedupeKey(info: ViolationInfo): string { + return `${info.type}:${info.importer}:${info.specifier}:${info.resolved ?? ''}` + } + + 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 relativizePath(normalizePath(absolutePath), config.root) + } + + /** 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 (k.includes(SERVER_FN_LOOKUP_QUERY)) 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 (k.includes(SERVER_FN_LOOKUP_QUERY)) 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 + + // Wait for entries before running reachability. registerEntries() + // populates entries at buildStart; resolveId(!importer) may add more. + const status = + env.graph.entries.size > 0 + ? checkPostTransformReachability(env, file) + : 'unknown' + + if (status === 'reachable') { + for (const pv of active) { + await emitPendingViolation(env, warnFn, pv) + } + toDelete.push(file) + } else if (status === 'unreachable') { + 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 (!pv.info.importerLoc) { + const sourceCandidates = buildSourceCandidates( + pv.info.specifier, + pv.info.resolved, + config.root, + ) + const loc = await resolveImporterLocation( + env.transformResultProvider, + env, + pv.info.importer, + sourceCandidates, + ) + + if (loc) { + pv.info.importerLoc = loc + pv.info.snippet = buildCodeSnippet( + env.transformResultProvider, + pv.info.importer, + loc, + ) + } + } + + if (hasSeen(env, dedupeKey(pv.info))) { + return false + } + + const freshTrace = await rebuildAndAnnotateTrace( + env.transformResultProvider, + env, + pv.info.env, + pv.info.importer, + pv.info.specifier, + pv.info.importerLoc, + ) + if (freshTrace.length > pv.info.trace.length) { + pv.info.trace = freshTrace + } + + 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) { + 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 + + 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() + importPatternCache.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) + } + } + } + }, + + async resolveId(source, importer, _options) { + const envName = this.environment.name + const env = getEnv(envName) + const envType = getEnvType(envName) + const provider = env.transformResultProvider + 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) { + 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 = importer.includes(SERVER_FN_LOOKUP_QUERY) + + if (isDirectLookup) { + env.serverFnLookupModules.add(normalizedImporter) + } + + const isPreTransformResolve = + isDirectLookup || + env.serverFnLookupModules.has(normalizedImporter) || + isScanResolve + + // 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 }) + + const resolveAgainstImporter = async (): Promise => { + const primary = await this.resolve(source, importer, { + skipSelf: true, + }) + if (primary) { + return canonicalizeResolvedId( + primary.id, + config.root, + resolveExtensionlessAbsoluteId, + ) + } + + 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 = await buildViolationInfo( + provider, + env, + envName, + envType, + importer, + normalizedImporter, + source, + { + type: 'marker', + message: buildMarkerViolationMessage( + getRelativePath(normalizedImporter), + markerKind, + ), + }, + ) + 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 = await buildMarkerViolationFromResolvedImport( + provider, + env, + envName, + envType, + importerFile, + specifier, + normalizedImporter, + getRelativePath(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 (!isPreTransformResolve) { + env.graph.addEdge(source, normalizedImporter, source) + } + const info = await buildViolationInfo( + provider, + env, + envName, + envType, + importer, + normalizedImporter, + source, + { + type: 'specifier', + pattern: specifierMatch.pattern, + message: `Import "${source}" is denied in the ${envType} environment`, + }, + ) + + // 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 + } 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 + + if (env.resolveCache.has(cacheKey)) { + resolved = env.resolveCache.get(cacheKey) ?? null + } else { + resolved = await resolveAgainstImporter() + + // 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 (isPreTransformResolve && !isScanResolve) { + env.serverFnLookupModules.add(resolved) + } + + if (!isPreTransformResolve) { + 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 = + matchers.excludeFiles.length > 0 && + matchesAny(relativePath, matchers.excludeFiles) + + if (!isExcludedFile) { + const fileMatch = + matchers.files.length > 0 + ? matchesAny(relativePath, matchers.files) + : undefined + + if (fileMatch) { + const info = await buildFileViolationInfo( + provider, + env, + envName, + envType, + importer, + normalizedImporter, + source, + resolved, + fileMatch.pattern, + ) + return reportOrDeferViolation( + this, + env, + normalizedImporter, + importer, + info, + shouldDefer, + isPreTransformResolve, + ) + } + + const markerInfo = await buildMarkerViolationFromResolvedImport( + provider, + env, + envName, + envType, + importer, + source, + resolved, + relativePath, + ) + if (markerInfo) { + return reportOrDeferViolation( + this, + env, + normalizedImporter, + importer, + markerInfo, + shouldDefer, + isPreTransformResolve, + ) + } + } + } + + 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 || 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 + + 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)) + } + } + } + }, + }, + { + // 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) { + const envName = this.environment.name + const file = normalizeFilePath(id) + const envType = getEnvType(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 = collectNamedExports(code) + } 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, + message: `File "${relativizePath(file, config.root)}" is denied in the ${envType} environment`, + trace: [], + }, + config.mockAccess, + config.root, + ) + return generateDevSelfDenialModule(exportNames, runtimeId) + } + + // getCombinedSourcemap() returns the composed sourcemap + let map: SourceMapLike | undefined + try { + map = this.getCombinedSourcemap() + } catch { + map = undefined + } + + let originalCode: string | undefined + if (map?.sourcesContent) { + originalCode = pickOriginalCodeFromSourcesContent( + map, + file, + config.root, + ) + } + + const lineIndex = buildLineIndex(code) + const cacheKey = normalizePath(id) + + const envState = getEnv(envName) + const isServerFnLookup = id.includes(SERVER_FN_LOOKUP_QUERY) + + // Propagate SERVER_FN_LOOKUP status before import-analysis + if (isServerFnLookup) { + envState.serverFnLookupModules.add(file) + } + + const result: TransformResult = { + code, + map, + originalCode, + lineIndex, + } + 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 importSources = extractImportSources(code) + const resolvedChildren = new Set() + const deniedSourceReplacements = new Map() + for (const src of importSources) { + try { + const resolved = await this.resolve(src, id, { skipSelf: true }) + 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) { + const info = await buildFileViolationInfo( + envState.transformResultProvider, + envState, + envName, + envType, + id, + 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 + } + } + envState.postTransformImports.set(cacheKey, resolvedChildren) + if (cacheKey !== file && !isServerFnLookup) { + envState.postTransformImports.set(file, 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 + ? { + ...rewritten.map, + version: Number(rewritten.map.version), + sourcesContent: + rewritten.map.sourcesContent?.map( + (s: string | null) => s ?? '', + ) ?? [], + } + : { + 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/import-protection-plugin/postCompileUsage.ts b/packages/start-plugin-core/src/import-protection-plugin/postCompileUsage.ts new file mode 100644 index 0000000000..adc4a98e29 --- /dev/null +++ b/packages/start-plugin-core/src/import-protection-plugin/postCompileUsage.ts @@ -0,0 +1,100 @@ +import babel from '@babel/core' +import * as t from '@babel/types' +import { parseImportProtectionAst } from './ast' +import type { ParsedAst } from './ast' + +type UsagePos = { line: number; column0: number } + +/** + * Given transformed code, returns the first "meaningful" usage position for an + * import from `source` that survives compilation. + * + * "Preferred" positions (call, new, member-access) take priority over bare + * identifier references. The returned column is 0-based (Babel loc semantics). + */ +export function findPostCompileUsagePos( + code: string, + source: string, +): UsagePos | undefined { + return findPostCompileUsagePosFromAst(parseImportProtectionAst(code), source) +} + +function findPostCompileUsagePosFromAst( + ast: ParsedAst, + source: string, +): UsagePos | undefined { + // Collect local names bound from this specifier + const imported = new Set() + for (const node of ast.program.body) { + if (t.isImportDeclaration(node) && node.source.value === source) { + if (node.importKind === 'type') continue + for (const s of node.specifiers) { + if (t.isImportSpecifier(s) && s.importKind === 'type') continue + imported.add(s.local.name) + } + } + } + if (imported.size === 0) return undefined + + let preferred: UsagePos | undefined + let anyUsage: UsagePos | undefined + + // babel.traverse can throw on malformed scopes (e.g. duplicate bindings from + // import + const re-declaration) because parseAst doesn't attach a hub + try { + babel.traverse(ast, { + ImportDeclaration(path) { + path.skip() + }, + + Identifier(path: babel.NodePath) { + if (preferred && anyUsage) { + path.stop() + return + } + + const { node, parent, scope } = path + if (!imported.has(node.name)) return + + // Skip binding positions (declarations, import specifiers, etc.) + if (path.isBindingIdentifier()) return + + // Skip non-shorthand object property keys — they don't reference the import + if ( + t.isObjectProperty(parent) && + parent.key === node && + !parent.computed && + !parent.shorthand + ) + return + if (t.isObjectMethod(parent) && parent.key === node && !parent.computed) + return + if (t.isExportSpecifier(parent) && parent.exported === node) return + + // Skip if shadowed by a closer binding + const binding = scope.getBinding(node.name) + if (binding && binding.kind !== 'module') return + + const loc = node.loc?.start + if (!loc) return + 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) && parent.object === node) + + if (isPreferred) { + preferred ||= pos + } else { + anyUsage ||= pos + } + }, + }) + } catch { + // Scope analysis failed — cannot determine usage positions reliably + return undefined + } + + return preferred ?? anyUsage +} diff --git a/packages/start-plugin-core/src/import-protection-plugin/rewriteDeniedImports.ts b/packages/start-plugin-core/src/import-protection-plugin/rewriteDeniedImports.ts new file mode 100644 index 0000000000..c9739396a3 --- /dev/null +++ b/packages/start-plugin-core/src/import-protection-plugin/rewriteDeniedImports.ts @@ -0,0 +1,379 @@ +import * as t from '@babel/types' +import { generateFromAst } from '@tanstack/router-utils' + +import { MOCK_MODULE_ID } from './virtualModules' +import { getOrCreate } from './utils' +import { parseImportProtectionAst } from './ast' +import type { SourceMapLike } from './sourceLocation' +import type { ParsedAst } from './ast' + +export function isValidExportName(name: string): boolean { + if (name === 'default' || name.length === 0) return false + const first = name.charCodeAt(0) + // First char: A-Z (65-90), a-z (97-122), _ (95), $ (36) + 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) + // Subsequent: A-Z, a-z, 0-9 (48-57), _, $ + if ( + !( + (ch >= 65 && ch <= 90) || + (ch >= 97 && ch <= 122) || + (ch >= 48 && ch <= 57) || + ch === 95 || + ch === 36 + ) + ) + return false + } + return true +} + +export function collectMockExportNamesBySource( + code: string, +): Map> { + return collectMockExportNamesBySourceFromAst(parseImportProtectionAst(code)) +} + +function collectMockExportNamesBySourceFromAst( + ast: ParsedAst, +): Map> { + const namesBySource = new Map>() + const memberBindingToSource = new Map() + const add = (source: string, name: string) => { + if (name === 'default' || name.length === 0) return + getOrCreate(namesBySource, source, () => new Set()).add(name) + } + + for (const node of ast.program.body) { + if (t.isImportDeclaration(node)) { + if (node.importKind === 'type') continue + const source = node.source.value + for (const s of node.specifiers) { + if (t.isImportNamespaceSpecifier(s)) { + memberBindingToSource.set(s.local.name, source) + continue + } + if (t.isImportDefaultSpecifier(s)) { + memberBindingToSource.set(s.local.name, source) + continue + } + if (!t.isImportSpecifier(s)) continue + if (s.importKind === 'type') continue + const importedName = t.isIdentifier(s.imported) + ? s.imported.name + : s.imported.value + // `import { default as x } from 'm'` only requires a default export. + if (importedName === 'default') continue + add(source, importedName) + } + } + + if (t.isExportNamedDeclaration(node) && node.source?.value) { + if (node.exportKind === 'type') continue + const source = node.source.value + for (const s of node.specifiers) { + if (!t.isExportSpecifier(s)) continue + if (s.exportKind === 'type') continue + add(source, s.local.name) + } + } + } + + // For namespace/default imports, collect property names used as + // `binding.foo`/`binding?.foo` so mock-edge modules can expose explicit ESM + // named exports required by Rolldown/native ESM. + if (memberBindingToSource.size > 0) { + const visit = (node: t.Node): void => { + if (t.isMemberExpression(node)) { + const object = node.object + if (t.isIdentifier(object)) { + const source = memberBindingToSource.get(object.name) + if (source) { + const property = node.property + if (!node.computed && t.isIdentifier(property)) { + add(source, property.name) + } else if (node.computed && t.isStringLiteral(property)) { + add(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 out = new Map>() + for (const [source, set] of namesBySource) { + out.set(source, Array.from(set).sort()) + } + return out +} + +/** Collect all valid named export identifiers from the given code. */ +export function collectNamedExports(code: string): Array { + return collectNamedExportsFromAst(parseImportProtectionAst(code)) +} + +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) + } +} + +function collectNamedExportsFromAst(ast: ParsedAst): Array { + const names = new Set() + const add = (name: string) => { + if (isValidExportName(name)) names.add(name) + } + + for (const node of ast.program.body) { + if (t.isExportNamedDeclaration(node)) { + if (node.exportKind === 'type') continue + + if (node.declaration) { + const decl = node.declaration + if (t.isFunctionDeclaration(decl) || t.isClassDeclaration(decl)) { + if (decl.id?.name) add(decl.id.name) + } else if (t.isVariableDeclaration(decl)) { + for (const d of decl.declarations) { + collectIdentifiersFromPattern(d.id as t.LVal, add) + } + } + } + + for (const s of node.specifiers) { + if (!t.isExportSpecifier(s)) continue + if (s.exportKind === 'type') continue + const exportedName = t.isIdentifier(s.exported) + ? s.exported.name + : s.exported.value + add(exportedName) + } + } + } + + return Array.from(names).sort() +} + +/** + * 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( + parseImportProtectionAst(code), + id, + deniedSources, + getMockModuleId, + ) +} + +function rewriteDeniedImportsFromAst( + ast: ParsedAst, + 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 = t.isIdentifier(specifier.imported) + ? specifier.imported.name + : specifier.imported.value + replacements.push( + t.variableDeclaration('const', [ + t.variableDeclarator( + t.identifier(specifier.local.name), + t.memberExpression( + t.identifier(mockVar), + t.identifier(importedName), + ), + ), + ]), + ) + } + } + + 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 mockVar = `__tss_deny_${mockCounter++}` + const replacements: Array = [] + + replacements.push( + t.importDeclaration( + [t.importDefaultSpecifier(t.identifier(mockVar))], + t.stringLiteral(getMockModuleId(node.source.value)), + ), + ) + const exportSpecifiers: Array<{ + localName: string + exportedName: string + }> = [] + for (const specifier of node.specifiers) { + if (t.isExportSpecifier(specifier)) { + if (specifier.exportKind === 'type') continue + const localName = specifier.local.name + const exportedName = t.isIdentifier(specifier.exported) + ? specifier.exported.name + : specifier.exported.value + + const internalVar = `__tss_reexport_${localName}` + replacements.push( + t.variableDeclaration('const', [ + t.variableDeclarator( + t.identifier(internalVar), + t.memberExpression( + t.identifier(mockVar), + t.identifier(localName), + ), + ), + ]), + ) + exportSpecifiers.push({ localName: internalVar, exportedName }) + } + } + + if (exportSpecifiers.length > 0) { + replacements.push( + t.exportNamedDeclaration( + null, + exportSpecifiers.map((s) => + t.exportSpecifier( + t.identifier(s.localName), + t.identifier(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-plugin/sourceLocation.ts b/packages/start-plugin-core/src/import-protection-plugin/sourceLocation.ts new file mode 100644 index 0000000000..5a0bef5350 --- /dev/null +++ b/packages/start-plugin-core/src/import-protection-plugin/sourceLocation.ts @@ -0,0 +1,453 @@ +import { SourceMapConsumer } from 'source-map' +import * as path from 'pathe' + +import { findPostCompileUsagePos } from './postCompileUsage' +import { getOrCreate, normalizeFilePath } from './utils' +import type { Loc } from './trace' +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 +} + +// Transform result provider (replaces ctx.load() which doesn't work in dev) +export interface TransformResult { + code: string + map: SourceMapLike | undefined + originalCode: string | undefined + /** Precomputed line index for `code` (index → line/col). */ + lineIndex?: LineIndex +} + +/** + * 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 +} + +// 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) } +} + +/** + * 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 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 FindImportSpecifierIndex = (code: string, source: string) => number + +/** + * 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, + findImportSpecifierIndex: FindImportSpecifierIndex, +): 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 { code, map } = res + + const lineIndex = res.lineIndex ?? buildLineIndex(code) + + const idx = findImportSpecifierIndex(code, 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 = findPostCompileUsagePos(code, source) + if (!pos) return undefined + + return await mapGeneratedToOriginal(map, pos, importerFile) + } 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, + findImportSpecifierIndex: FindImportSpecifierIndex, +): 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, + findImportSpecifierIndex, + ) + 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, +): CodeSnippet | undefined { + try { + const importerFile = normalizeFilePath(moduleId) + const res = provider.getTransformResult(moduleId) + if (!res) return undefined + + const sourceCode = res.originalCode ?? 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-plugin/trace.ts similarity index 99% rename from packages/start-plugin-core/src/import-protection/trace.ts rename to packages/start-plugin-core/src/import-protection-plugin/trace.ts index d0c807ea03..053b98d2e0 100644 --- a/packages/start-plugin-core/src/import-protection/trace.ts +++ b/packages/start-plugin-core/src/import-protection-plugin/trace.ts @@ -166,6 +166,7 @@ export interface ViolationInfo { importerLoc?: Loc resolved?: string trace: Array + message: string /** Vitest-style code snippet showing the offending usage in the leaf module. */ snippet?: { lines: Array diff --git a/packages/start-plugin-core/src/import-protection-plugin/types.ts b/packages/start-plugin-core/src/import-protection-plugin/types.ts new file mode 100644 index 0000000000..e5058c9e00 --- /dev/null +++ b/packages/start-plugin-core/src/import-protection-plugin/types.ts @@ -0,0 +1,103 @@ +import type { CompileStartFrameworkOptions, GetConfigFn } from '../types' +import type { ImportProtectionBehavior } from '../schema' +import type { CompiledMatcher } from './matchers' +import type { ImportGraph, ViolationInfo } from './trace' +import type { + ImportLocCache, + TransformResult, + TransformResultProvider, +} from './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' + 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/import-protection-plugin/utils.ts b/packages/start-plugin-core/src/import-protection-plugin/utils.ts new file mode 100644 index 0000000000..ee9f9acdaa --- /dev/null +++ b/packages/start-plugin-core/src/import-protection-plugin/utils.ts @@ -0,0 +1,212 @@ +import { + extname, + isAbsolute, + relative, + resolve as resolvePath, +} from 'node:path' +import { normalizePath } from 'vite' + +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 +} + +/** 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() +} + +/** + * Lightweight regex to extract all import/re-export source strings from + * post-transform code. Matches: + * - `from "..."` / `from '...'` (static import/export) + * - `import("...")` / `import('...')` (dynamic import) + */ +const importSourceRe = + /\bfrom\s+(?:"([^"]+)"|'([^']+)')|import\s*\(\s*(?:"([^"]+)"|'([^']+)')\s*\)/g + +export function escapeRegExp(s: string): string { + return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') +} + +/** 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) +} + +export function extractImportSources(code: string): Array { + const sources: Array = [] + let m: RegExpExecArray | null + importSourceRe.lastIndex = 0 + while ((m = importSourceRe.exec(code)) !== null) { + const src = m[1] ?? m[2] ?? m[3] ?? m[4] + if (src) sources.push(src) + } + return sources +} + +/** 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-plugin/virtualModules.ts b/packages/start-plugin-core/src/import-protection-plugin/virtualModules.ts new file mode 100644 index 0000000000..de2e407a81 --- /dev/null +++ b/packages/start-plugin-core/src/import-protection-plugin/virtualModules.ts @@ -0,0 +1,452 @@ +import { resolveViteId } from '../utils' +import { VITE_ENVIRONMENT_NAMES } from '../constants' +import { isValidExportName } from './rewriteDeniedImports' +import { CLIENT_ENV_SUGGESTIONS } from './trace' +import { VITE_BROWSER_VIRTUAL_PREFIX } from './constants' +import { relativizePath } from './utils' +import type { ViolationInfo } from './trace' + +export const MOCK_MODULE_ID = 'tanstack-start-import-protection:mock' +const RESOLVED_MOCK_MODULE_ID = resolveViteId(MOCK_MODULE_ID) + +/** + * Per-violation mock prefix used in build+error mode. + * Each deferred violation gets a unique ID so we can check which ones + * survived tree-shaking in `generateBundle`. + */ +export const MOCK_BUILD_PREFIX = 'tanstack-start-import-protection:mock:build:' +const RESOLVED_MOCK_BUILD_PREFIX = resolveViteId(MOCK_BUILD_PREFIX) + +export const MOCK_EDGE_PREFIX = 'tanstack-start-import-protection:mock-edge:' +const RESOLVED_MOCK_EDGE_PREFIX = resolveViteId(MOCK_EDGE_PREFIX) + +export const MOCK_RUNTIME_PREFIX = + 'tanstack-start-import-protection:mock-runtime:' +const RESOLVED_MOCK_RUNTIME_PREFIX = resolveViteId(MOCK_RUNTIME_PREFIX) + +const MARKER_PREFIX = 'tanstack-start-import-protection:marker:' +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 +} + +/** + * Convenience list for plugin `load` filters/handlers. + * + * Vite/Rollup call `load(id)` with the *resolved* virtual id (prefixed by `\0`). + * `resolveId(source)` sees the *unresolved* id/prefix (without `\0`). + */ +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 + +/** + * Resolve import-protection's internal virtual module IDs. + * + * `resolveId(source)` sees *unresolved* ids/prefixes (no `\0`). + * Returning a resolved id (with `\0`) ensures Vite/Rollup route it to `load`. + */ +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 +} + +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' + +/** + * Compact runtime suggestion text for browser console, derived from + * {@link CLIENT_ENV_SUGGESTIONS} so there's a single source of truth. + */ +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 !== VITE_ENVIRONMENT_NAMES.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))}` +} + +/** + * Generate a recursive Proxy-based mock module. + * + * When `diagnostics` is provided, the generated code includes a `__report` + * function that logs runtime warnings/errors when the mock is actually used + * (property access for primitive coercion, calls, construction, sets). + * + * When `diagnostics` is omitted, the mock is completely silent — suitable + * for base mock modules (e.g. `MOCK_MODULE_ID` or per-violation build mocks) + * that are consumed by mock-edge modules providing explicit named exports. + */ +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); + } +} +` + : '' + + // Diagnostic-only traps for primitive coercion, set + const diagGetTraps = hasDiag + ? ` + if (prop === Symbol.toPrimitive) { + return () => { + __report('toPrimitive', name); + return '[import-protection mock]'; + }; + } + if (prop === 'toString' || prop === 'valueOf' || prop === 'toJSON') { + return () => { + __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); };${diagGetTraps} + 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() } +} + +/** + * Filter export names to valid, non-default names. + */ +function filterExportNames(exports: ReadonlyArray): Array { + return exports.filter((n) => n.length > 0 && n !== 'default') +} + +/** + * Generate ESM export lines that re-export named properties from `mock`. + * + * Produces `export const foo = mock.foo;` for valid identifiers and + * string-keyed re-exports for non-identifier names. + */ +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 +} + +/** + * Generate a self-contained mock module with explicit named exports. + * + * Used by the transform hook's "self-denial" check: when a denied file + * (e.g. `.server.ts` in the client environment) is transformed, its entire + * content is replaced with this mock module. This avoids returning virtual + * module IDs from `resolveId`, which prevents cross-environment cache + * contamination from third-party resolver plugins. + * + * The generated code is side-effect-free and tree-shakeable. + */ +export function generateSelfContainedMockModule(exportNames: Array): { + code: string +} { + const mockCode = generateMockCode() + const exportLines = generateExportLines(filterExportNames(exportNames)) + + return { + code: `${mockCode} +${exportLines.join('\n')} +`, + } +} + +/** + * Generate a dev-mode mock module for self-denial transforms. + * + * Similar to `loadMockEdgeModule` but takes export names and a runtime ID + * directly (instead of parsing them from a base64url-encoded payload). + * Used by the transform hook when a denied file (e.g. `.server.ts` in + * the client environment) is replaced in dev mode. + * + * The generated module imports mock-runtime for runtime diagnostics + * (error/warn on property access) and re-exports explicit named exports + * so that `import { foo } from './denied.server'` works. + */ +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: string = + 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' + + const meta = { + env: String(payload.env ?? ''), + importer: String(payload.importer ?? ''), + specifier: String(payload.specifier ?? ''), + trace: Array.isArray(payload.trace) ? payload.trace : [], + } + + return { code: generateMockCode({ meta, mode }) } +} + +const MARKER_MODULE_RESULT = { code: 'export {}' } as const + +export function loadMarkerModule(): { code: string } { + return MARKER_MODULE_RESULT +} + +export function loadResolvedVirtualModule( + id: string, +): { code: string } | undefined { + if (id === RESOLVED_MOCK_MODULE_ID) { + return loadSilentMockModule() + } + + // Per-violation build mock modules — same silent mock code + 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 +} diff --git a/packages/start-plugin-core/src/import-protection/INTERNALS.md b/packages/start-plugin-core/src/import-protection/INTERNALS.md deleted file mode 100644 index 4f19e4bd7e..0000000000 --- a/packages/start-plugin-core/src/import-protection/INTERNALS.md +++ /dev/null @@ -1,266 +0,0 @@ -# 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 deleted file mode 100644 index 4893c504e4..0000000000 --- a/packages/start-plugin-core/src/import-protection/adapterUtils.ts +++ /dev/null @@ -1,94 +0,0 @@ -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 deleted file mode 100644 index 85f90b0a87..0000000000 --- a/packages/start-plugin-core/src/import-protection/analysis.ts +++ /dev/null @@ -1,935 +0,0 @@ -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 deleted file mode 100644 index 4186f6af49..0000000000 --- a/packages/start-plugin-core/src/import-protection/constants.ts +++ /dev/null @@ -1,28 +0,0 @@ -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/rewrite.ts b/packages/start-plugin-core/src/import-protection/rewrite.ts deleted file mode 100644 index fb7e190476..0000000000 --- a/packages/start-plugin-core/src/import-protection/rewrite.ts +++ /dev/null @@ -1,228 +0,0 @@ -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 deleted file mode 100644 index ee346b327b..0000000000 --- a/packages/start-plugin-core/src/import-protection/sourceLocation.ts +++ /dev/null @@ -1,610 +0,0 @@ -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/utils.ts b/packages/start-plugin-core/src/import-protection/utils.ts deleted file mode 100644 index 811539bd78..0000000000 --- a/packages/start-plugin-core/src/import-protection/utils.ts +++ /dev/null @@ -1,223 +0,0 @@ -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 deleted file mode 100644 index 29b6878927..0000000000 --- a/packages/start-plugin-core/src/import-protection/virtualModules.ts +++ /dev/null @@ -1,303 +0,0 @@ -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 a6ee23a345..df946192ae 100644 --- a/packages/start-plugin-core/src/index.ts +++ b/packages/start-plugin-core/src/index.ts @@ -1,8 +1,6 @@ export type { TanStackStartInputConfig } from './schema' -export type { - StartCompilerImportTransform, - StartCompilerTransformCandidate, - StartCompilerTransformContext, - TanStackStartCoreOptions, -} from './types' -export { START_ENVIRONMENT_NAMES } from './constants' + +export { TanStackStartVitePluginCore } from './plugin' +export { resolveViteId } from './utils' + +export { VITE_ENVIRONMENT_NAMES } from './constants' diff --git a/packages/start-plugin-core/src/vite/load-env-plugin/plugin.ts b/packages/start-plugin-core/src/load-env-plugin/plugin.ts similarity index 100% rename from packages/start-plugin-core/src/vite/load-env-plugin/plugin.ts rename to packages/start-plugin-core/src/load-env-plugin/plugin.ts diff --git a/packages/start-plugin-core/src/vite/output-directory.ts b/packages/start-plugin-core/src/output-directory.ts similarity index 87% rename from packages/start-plugin-core/src/vite/output-directory.ts rename to packages/start-plugin-core/src/output-directory.ts index ea215d4841..aa1655433f 100644 --- a/packages/start-plugin-core/src/vite/output-directory.ts +++ b/packages/start-plugin-core/src/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/planning.ts b/packages/start-plugin-core/src/planning.ts deleted file mode 100644 index 11f25d14d3..0000000000 --- a/packages/start-plugin-core/src/planning.ts +++ /dev/null @@ -1,142 +0,0 @@ -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 new file mode 100644 index 0000000000..deec1ab199 --- /dev/null +++ b/packages/start-plugin-core/src/plugin.ts @@ -0,0 +1,471 @@ +import { joinPaths } from '@tanstack/router-core' +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 { ENTRY_POINTS, VITE_ENVIRONMENT_NAMES } from './constants' +import { getBundlerOptions } from './utils' +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 { startCompilerPlugin } from './start-compiler-plugin/plugin' +import { importProtectionPlugin } from './import-protection-plugin/plugin' +import type { + GetConfigFn, + ResolvedStartConfig, + TanStackStartVitePluginCoreOptions, +} from './types' +import type { ViteEnvironmentNames } from './constants' +import type { + TanStackStartInputConfig, + TanStackStartOutputConfig, +} from './schema' +import type { PluginOption } from 'vite' + +function isFullUrl(str: string): boolean { + try { + new URL(str) + return true + } catch { + return false + } +} + +export function TanStackStartVitePluginCore( + corePluginOpts: TanStackStartVitePluginCoreOptions, + startPluginOpts: TanStackStartInputConfig, +): Array { + // Determine the provider environment for server functions + // If providerEnv is set, use that; otherwise default to SSR as the provider + const serverFnProviderEnv = + corePluginOpts.serverFn?.providerEnv || VITE_ENVIRONMENT_NAMES.server + const ssrIsProvider = serverFnProviderEnv === VITE_ENVIRONMENT_NAMES.server + + const resolvedStartConfig: ResolvedStartConfig = { + root: '', + startFilePath: undefined, + routerFilePath: '', + srcDirectory: '', + viteAppBase: '', + serverFnProviderEnv, + } + + 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, corePluginOpts } + } + + // When the router basepath and vite base are misaligned during dev, + // we install a URL rewrite middleware instead of erroring. + let needsDevBaseRewrite = false + + 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, '/']), + ) + ) { + // 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 = 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: (() => { + // Use the same object reference for both keys to avoid + // Vite 8's deprecation warning when both are present. + // Vite 7 reads rollupOptions, Vite 8 reads rolldownOptions. + const bundlerOptions = { + input: { + main: ENTRY_POINTS.client, + }, + } + return { + rollupOptions: bundlerOptions, + rolldownOptions: bundlerOptions, + 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, + ...(() => { + const bundlerOptions = { + input: + getBundlerOptions( + viteConfig.environments?.[VITE_ENVIRONMENT_NAMES.server] + ?.build, + )?.input ?? serverAlias, + } + return { + rollupOptions: bundlerOptions, + rolldownOptions: bundlerOptions, + } + })(), + 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_ROUTER_BASEPATH', startConfig.router.basepath), + ...(command === 'serve' ? defineReplaceEnv('TSS_SHELL', startConfig.spa?.enabled ? 'true' : 'false') : {}), + ...defineReplaceEnv('TSS_DEV_SERVER', command === 'serve' ? 'true' : 'false'), + // Dev SSR styles: enabled flag and basepath (defaults to vite base for asset URL alignment) + ...defineReplaceEnv('TSS_DEV_SSR_STYLES_ENABLED', startConfig.dev.ssrStyles.enabled ? 'true' : 'false'), + ...defineReplaceEnv('TSS_DEV_SSR_STYLES_BASEPATH', startConfig.dev.ssrStyles.basepath ?? resolvedStartConfig.viteAppBase), + // Replace NODE_ENV during build (unless opted out) for dead code elimination in server bundles + ...(command === 'build' && startConfig.server.build.staticNodeEnv ? { + 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || viteConfig.mode || 'production'), + } : {}), + }, + 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) + } + + // If a custom provider environment is configured (not SSR), + // build it last so the manifest includes functions from all environments + if (!ssrIsProvider) { + const providerEnv = builder.environments[serverFnProviderEnv] + if (!providerEnv) { + throw new Error( + `Provider environment "${serverFnProviderEnv}" not found`, + ) + } + if (!providerEnv.isBuilt) { + // Build the provider environment last + // This ensures all server functions are discovered from client/ssr builds + await builder.build(providerEnv) + } + } + }, + }, + } + }, + }, + // Separate plugin for buildApp hook with enforce: 'post' + // This ensures proper ordering with other plugins that also have + // buildApp hooks with order: 'post'. The enforce: 'post' ensures this + // runs after other plugins (like Nitro) complete their builds. + { + name: 'tanstack-start-core:post-build', + enforce: 'post', + buildApp: { + order: 'post', + async handler(builder) { + const { startConfig } = getConfig() + await postServerBuild({ builder, startConfig }) + }, + }, + }, + // 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: startPluginOpts?.serverFns?.generateFunctionId, + providerEnvName: serverFnProviderEnv, + }), + importProtectionPlugin({ + getConfig, + framework: corePluginOpts.framework, + environments, + providerEnvName: serverFnProviderEnv, + }), + tanStackStartRouter(startPluginOpts, getConfig, corePluginOpts), + loadEnvPlugin(), + startManifestPlugin({ + getClientBundle: () => getBundle(VITE_ENVIRONMENT_NAMES.client), + 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. + { + name: 'tanstack-start-core:dev-base-rewrite', + configureServer(server) { + if (!needsDevBaseRewrite) { + return + } + const basePrefix = resolvedStartConfig.viteAppBase.replace(/\/$/, '') + server.middlewares.use((req, _res, next) => { + if (req.url && !req.url.startsWith(basePrefix)) { + req.url = basePrefix + req.url + } + next() + }) + }, + }, + devServerPlugin({ + getConfig, + devSsrStylesEnabled: startPluginOpts?.dev?.ssrStyles?.enabled ?? true, + }), + 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 deleted file mode 100644 index d81a49bcab..0000000000 --- a/packages/start-plugin-core/src/post-build.ts +++ /dev/null @@ -1,64 +0,0 @@ -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 new file mode 100644 index 0000000000..478b2ef210 --- /dev/null +++ b/packages/start-plugin-core/src/post-server-build.ts @@ -0,0 +1,73 @@ +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') + 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, + }, + }) + } + + // Run the prerendering process + if (startConfig.prerender.enabled) { + await prerender({ + startConfig, + builder, + }) + } + + // Run the sitemap build process + if (startConfig.sitemap?.enabled) { + 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 9510a9ab37..af68e5167a 100644 --- a/packages/start-plugin-core/src/prerender.ts +++ b/packages/start-plugin-core/src/prerender.ts @@ -2,33 +2,29 @@ import { promises as fsp } from 'node:fs' import os from 'node:os' import path from 'pathe' import { joinURL, withBase, withTrailingSlash, withoutBase } from 'ufo' +import { VITE_ENVIRONMENT_NAMES } from './constants' 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, - handler, + builder, }: { startConfig: TanStackStartOutputConfig - handler: PrerenderHandler + builder: ViteBuilder }) { 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 || [] @@ -45,20 +41,66 @@ export async function prerender({ } const routerBasePath = joinURL('/', startConfig.router.basepath ?? '') - const routerBaseUrl = new URL( - routerBasePath, - handler.getOrigin?.() ?? 'http://localhost', - ) + const routerBaseUrl = new URL(routerBasePath, 'http://localhost') + // Enforce that prerender page paths are relative/path-based (no protocol/host) startConfig.pages = validateAndNormalizePrerenderPages( startConfig.pages, routerBaseUrl, ) + 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 + + // 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 + } + try { - const pages = await prerenderPages({ - outputDir: handler.getClientOutputDirectory(), - }) + // Crawl all pages + const pages = await prerenderPages({ outputDir }) logger.info(`Prerendered ${pages.length} pages:`) pages.forEach((page) => { @@ -66,15 +108,14 @@ export async function prerender({ }) } catch (error) { logger.error(error) - throw error } finally { - await handler.close?.() + await previewServer.close() } function extractLinks(html: string): Array { const linkRegex = /]+href=["']([^"']+)["'][^>]*>/g const links: Array = [] - let match: RegExpExecArray | null + let match while ((match = linkRegex.exec(html)) !== null) { const href = match[1] @@ -93,7 +134,10 @@ 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 ?? '') + // Normalize discovered pages and enforce path-only entries + const routerBaseUrl = new URL(routerBasePath, 'http://localhost') startConfig.pages = validateAndNormalizePrerenderPages( startConfig.pages, routerBaseUrl, @@ -111,34 +155,37 @@ export async function prerender({ 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 ( - startConfig.prerender?.filter && - !startConfig.prerender.filter(page) - ) { + // If there is a filter link, check if the page should be prerendered + 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 { - const res = await requestWithRedirects( + // Fetch the route + + const res = await localFetch( withTrailingSlash(withBase(page.path, routerBasePath)), { headers: { @@ -152,7 +199,6 @@ 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, }) @@ -162,6 +208,7 @@ 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') @@ -175,14 +222,17 @@ 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 { - htmlPath = cleanPagePath + '.html' + if ( + cleanPagePath.endsWith('/') || + (prerenderOptions.autoSubfolderIndex ?? true) + ) { + htmlPath = joinURL(cleanPagePath, 'index.html') + } else { + htmlPath = cleanPagePath + '.html' + } } const filename = withoutBase( @@ -191,19 +241,8 @@ export async function prerender({ ) const html = await res.text() - 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}`, - ) - } + + const filepath = path.join(outputDir, filename) await fsp.mkdir(path.dirname(filepath), { recursive: true, @@ -219,6 +258,7 @@ export async function prerender({ Object.assign(page, newPage) } + // Find new links if (prerenderOptions.crawlLinks ?? true) { const links = extractLinks(html) for (const link of links) { @@ -227,112 +267,62 @@ export async function prerender({ } } catch (error) { if (retries < (prerenderOptions.retryCount ?? 0)) { - const retryDelay = normalizeRetryDelay(prerenderOptions.retryDelay) - logger.warn( - `Encountered error, retrying: ${page.path} in ${retryDelay}ms`, + logger.warn(`Encountered error, retrying: ${page.path} in 500ms`) + await new Promise((resolve) => + setTimeout(resolve, prerenderOptions.retryDelay), ) - 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 + } } } }) } } - - function normalizeRetryDelay(value: number | undefined): number { - const retryDelay = Number(value) - - 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', - }) - - 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() - ) -} +async function startPreviewServer( + viteConfig: ResolvedConfig, +): Promise { + const vite = await import('vite') -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 + 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 toPreviewPath(url: URL, routerBaseUrl: URL): string | undefined { - const basepath = routerBaseUrl.pathname.replace(/\/$/, '') - if ( - basepath && - url.pathname !== basepath && - !url.pathname.startsWith(basepath + '/') - ) { - return undefined +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') } - if (url.pathname.startsWith('//')) { - return url.href - } - return url.pathname + url.search + + return new URL(baseUrl) } -export function validateAndNormalizePrerenderPages( +/** + * Validates and normalizes prerender page paths to ensure they are relative + * (no protocol/host) and returns normalized Page objects with cleaned paths. + * Preserves unicode characters by decoding the pathname after URL validation. + */ +function validateAndNormalizePrerenderPages( pages: Array, routerBaseUrl: URL, ): Array { @@ -346,29 +336,18 @@ export function validateAndNormalizePrerenderPages( }) } - if ( - url.protocol !== routerBaseUrl.protocol || - url.origin !== routerBaseUrl.origin || - url.username || - url.password - ) { + if (url.origin !== 'http://localhost') { throw new Error(`prerender page path must be relative: ${page.path}`) } + // Decode the pathname to preserve unicode characters (e.g., /대한민국) + // The URL constructor encodes non-ASCII characters, but we want to keep + // the original unicode form for filesystem paths 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}`) - } return { ...page, - path: normalizedPath, + path: decodedPathname + url.search + url.hash, } }) } diff --git a/packages/start-plugin-core/src/preview-server-plugin/plugin.ts b/packages/start-plugin-core/src/preview-server-plugin/plugin.ts new file mode 100644 index 0000000000..0943d11c88 --- /dev/null +++ b/packages/start-plugin-core/src/preview-server-plugin/plugin.ts @@ -0,0 +1,69 @@ +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) + + // 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 23eb4c651c..dd28815fa0 100644 --- a/packages/start-plugin-core/src/resolve-entries.ts +++ b/packages/start-plugin-core/src/resolve-entries.ts @@ -13,10 +13,6 @@ 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 deleted file mode 100644 index a97c500b0d..0000000000 --- a/packages/start-plugin-core/src/rsbuild/COMPILER_ARCHITECTURE.md +++ /dev/null @@ -1,199 +0,0 @@ -# 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 deleted file mode 100644 index eca4051281..0000000000 --- a/packages/start-plugin-core/src/rsbuild/INTERNALS-import-protection.md +++ /dev/null @@ -1,203 +0,0 @@ -# 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 deleted file mode 100644 index eba703f121..0000000000 --- a/packages/start-plugin-core/src/rsbuild/import-protection-loader.ts +++ /dev/null @@ -1,342 +0,0 @@ -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 deleted file mode 100644 index f9d46505e3..0000000000 --- a/packages/start-plugin-core/src/rsbuild/import-protection.ts +++ /dev/null @@ -1,1726 +0,0 @@ -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 deleted file mode 100644 index 46d1f1b58b..0000000000 --- a/packages/start-plugin-core/src/rsbuild/index.ts +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index a7dae0c379..0000000000 --- a/packages/start-plugin-core/src/rsbuild/normalized-client-build.ts +++ /dev/null @@ -1,543 +0,0 @@ -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 deleted file mode 100644 index 5461213194..0000000000 --- a/packages/start-plugin-core/src/rsbuild/planning.ts +++ /dev/null @@ -1,269 +0,0 @@ -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 deleted file mode 100644 index c4660728b4..0000000000 --- a/packages/start-plugin-core/src/rsbuild/plugin.ts +++ /dev/null @@ -1,890 +0,0 @@ -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 deleted file mode 100644 index 2590ec9931..0000000000 --- a/packages/start-plugin-core/src/rsbuild/post-build.ts +++ /dev/null @@ -1,96 +0,0 @@ -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 deleted file mode 100644 index 86194e309c..0000000000 --- a/packages/start-plugin-core/src/rsbuild/schema.ts +++ /dev/null @@ -1,54 +0,0 @@ -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 deleted file mode 100644 index 75c54ecf93..0000000000 --- a/packages/start-plugin-core/src/rsbuild/server-fn-resolver-rebuild.ts +++ /dev/null @@ -1,53 +0,0 @@ -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 deleted file mode 100644 index 70e2f234ce..0000000000 --- a/packages/start-plugin-core/src/rsbuild/server-middleware.ts +++ /dev/null @@ -1,217 +0,0 @@ -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 deleted file mode 100644 index 3cd1725fa0..0000000000 --- a/packages/start-plugin-core/src/rsbuild/start-compiler-host.ts +++ /dev/null @@ -1,502 +0,0 @@ -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 deleted file mode 100644 index 89a22d82cd..0000000000 --- a/packages/start-plugin-core/src/rsbuild/start-compiler-metadata-loader.ts +++ /dev/null @@ -1,22 +0,0 @@ -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 deleted file mode 100644 index dfa6119246..0000000000 --- a/packages/start-plugin-core/src/rsbuild/start-compiler-metadata.ts +++ /dev/null @@ -1,20 +0,0 @@ -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 deleted file mode 100644 index 7c3106be28..0000000000 --- a/packages/start-plugin-core/src/rsbuild/start-router-plugin.ts +++ /dev/null @@ -1,70 +0,0 @@ -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 deleted file mode 100644 index 534a7860bb..0000000000 --- a/packages/start-plugin-core/src/rsbuild/swc-rsc.ts +++ /dev/null @@ -1,174 +0,0 @@ -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 deleted file mode 100644 index fa10d65f64..0000000000 --- a/packages/start-plugin-core/src/rsbuild/types.ts +++ /dev/null @@ -1,20 +0,0 @@ -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 deleted file mode 100644 index c5e28e96c7..0000000000 --- a/packages/start-plugin-core/src/rsbuild/virtual-modules.ts +++ /dev/null @@ -1,642 +0,0 @@ -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 deleted file mode 100644 index e5b85f5e04..0000000000 --- a/packages/start-plugin-core/src/rsbuild/watch-ignored.ts +++ /dev/null @@ -1,24 +0,0 @@ -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 413ac4673f..53b671b477 100644 --- a/packages/start-plugin-core/src/schema.ts +++ b/packages/start-plugin-core/src/schema.ts @@ -1,10 +1,10 @@ import path from 'node:path' import { z } from 'zod' import { configSchema, getConfig } from '@tanstack/router-plugin' -import type { CompileStartFrameworkOptions } from './types' +import type { TanStackStartVitePluginCoreOptions } from './types' const tsrConfig = configSchema - .omit({ autoCodeSplitting: true, target: true }) + .omit({ autoCodeSplitting: true, target: true, verboseFileRoutes: true }) .partial() // --- Import Protection Schema --- @@ -41,9 +41,15 @@ const importProtectionOptionsSchema = z */ mockAccess: z.enum(['error', 'warn', 'off']).optional(), onViolation: z - .custom< - (violation: unknown) => boolean | void | Promise - >((value) => typeof value === 'function') + .function() + .args(z.any()) + .returns( + z.union([ + z.boolean(), + z.void(), + z.promise(z.union([z.boolean(), z.void()])), + ]), + ) .optional(), include: z.array(patternSchema).optional(), exclude: z.array(patternSchema).optional(), @@ -57,11 +63,9 @@ const importProtectionOptionsSchema = z export function parseStartConfig( opts: z.input, - corePluginOpts: { framework: CompileStartFrameworkOptions }, + corePluginOpts: TanStackStartVitePluginCoreOptions, root: string, ) { - const rawOptions = opts ?? {} - const rawRouterOptions = rawOptions.router ?? {} const options = tanstackStartOptionsSchema.parse(opts) const srcDirectory = options.srcDirectory @@ -69,13 +73,13 @@ export function parseStartConfig( const routesDirectory = path.resolve( root, srcDirectory, - rawRouterOptions.routesDirectory ?? 'routes', + options.router.routesDirectory ?? 'routes', ) const generatedRouteTree = path.resolve( root, srcDirectory, - rawRouterOptions.generatedRouteTree ?? 'routeTree.gen.ts', + options.router.generatedRouteTree ?? 'routeTree.gen.ts', ) return { @@ -131,7 +135,7 @@ const pageSitemapOptionsSchema = z.object({ .optional(), }) -export const pageBaseSchema = z.object({ +const pageBaseSchema = z.object({ path: z.string(), sitemap: pageSitemapOptionsSchema.optional(), fromCrawl: z.boolean().optional(), @@ -145,12 +149,14 @@ const pagePrerenderOptionsSchema = z.object({ retryCount: z.number().optional(), retryDelay: z.number().optional(), onSuccess: z - .custom< - (result: { - page: z.infer - html: string - }) => unknown - >((value) => typeof value === 'function') + .function() + .args( + z.object({ + page: pageBaseSchema, + html: z.string(), + }), + ) + .returns(z.any()) .optional(), headers: z.record(z.string(), z.string()).optional(), }) @@ -160,7 +166,7 @@ const spaSchema = z.object({ maskPath: z.string().optional().default('/'), prerender: pagePrerenderOptionsSchema .optional() - .prefault({}) + .default({}) .transform((opts) => ({ outputPath: opts.outputPath ?? '/_shell', crawlLinks: false, @@ -170,146 +176,107 @@ 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(), }) -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 +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(), + build: z + .object({ + staticNodeEnv: z.boolean().optional().default(true), + }) + .optional() + .default({}), + }) + .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(), + dev: z + .object({ + ssrStyles: z + .object({ + enabled: z.boolean().optional().default(true), + basepath: z.string().optional(), + }) + .optional() + .default({}), + }) + .optional() + .default({}), + spa: spaSchema.optional(), + vite: z + .object({ installDevServerMiddleware: z.boolean().optional() }) + .optional(), + importProtection: importProtectionOptionsSchema, + }) .optional() - .prefault({}) + .default({}) -export type PageBase = z.infer export type Page = z.infer -type TanStackStartOptionsInput = NonNullable< - z.input +export type TanStackStartInputConfig = z.input< + typeof tanstackStartOptionsSchema > - -export type TanStackStartInputConfig = TanStackStartOptionsInput export type TanStackStartOutputConfig = ReturnType export type ImportProtectionBehavior = z.infer< diff --git a/packages/start-plugin-core/src/serialization-adapters-module.ts b/packages/start-plugin-core/src/serialization-adapters-module.ts deleted file mode 100644 index 39813b3e02..0000000000 --- a/packages/start-plugin-core/src/serialization-adapters-module.ts +++ /dev/null @@ -1,82 +0,0 @@ -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/compiler.ts b/packages/start-plugin-core/src/start-compiler-plugin/compiler.ts new file mode 100644 index 0000000000..62f530d510 --- /dev/null +++ b/packages/start-plugin-core/src/start-compiler-plugin/compiler.ts @@ -0,0 +1,1348 @@ +/* eslint-disable import/no-commonjs */ +import crypto from 'node:crypto' +import * as t from '@babel/types' +import { + deadCodeElimination, + findReferencedIdentifiers, + generateFromAst, + parseAst, +} 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 type { + CompilationContext, + MethodChainPaths, + RewriteCandidate, + ServerFn, +} from './types' +import type { CompileStartFrameworkOptions } from '../types' + +type Binding = + | { + type: 'import' + source: string + importedName: string + resolvedKind?: Kind + } + | { + type: 'var' + init: t.Expression | null + resolvedKind?: Kind + } + +type Kind = 'None' | `Root` | `Builder` | LookupKind + +export type LookupKind = + | 'ServerFn' + | 'Middleware' + | 'IsomorphicFn' + | 'ServerOnlyFn' + | 'ClientOnlyFn' + | 'ClientOnlyJSX' + +// 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') + factoryName: string +} +type JSXSetup = { type: 'jsx'; componentName: string } + +function isLookupKind(kind: Kind): kind is LookupKind { + return kind in LookupSetup +} + +const LookupSetup: Record< + LookupKind, + 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', factoryName: 'createServerOnlyFn' }, + ClientOnlyFn: { type: 'directCall', factoryName: '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), +} + +/** + * 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: LookupKind, +) => void + +/** + * Registry mapping each LookupKind to its handler function. + * When adding a new kind, add its handler here. + */ +const KindHandlers: Record< + Exclude, + KindHandler +> = { + ServerFn: handleCreateServerFn, + Middleware: handleCreateMiddleware, + IsomorphicFn: handleCreateIsomorphicFn, + ServerOnlyFn: handleEnvOnlyFn, + ClientOnlyFn: handleEnvOnlyFn, + // ClientOnlyJSX is handled separately via JSX traversal, not here +} + +// All lookup kinds as an array for iteration with proper typing +const AllLookupKinds = Object.keys(LookupSetup) 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', +): Set { + const detected = new Set() + const validForEnv = LookupKindsPerEnv[env] + + for (const kind of AllLookupKinds) { + if (validForEnv.has(kind) && KindDetectionPatterns[kind].test(code)) { + detected.add(kind) + } + } + + 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 AllLookupKinds) { + const setup = LookupSetup[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) + } + } +} + +// Factory function names for direct call patterns. +// Used to filter nested candidates - we only want to include actual factory calls, +// not invocations of already-created functions (e.g., `myServerFn()` should NOT be a candidate) +const DirectCallFactoryNames = new Set() +for (const kind of AllLookupKinds) { + const setup = LookupSetup[kind] + if (setup.type === 'directCall') { + DirectCallFactoryNames.add(setup.factoryName) + } +} + +export type LookupConfig = { + libName: string + rootExport: string + kind: LookupKind | 'Root' // 'Root' for builder pattern, LookupKind for direct call +} + +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 +} + +/** + * Computes whether any file kinds need direct-call candidate detection. + * This applies to directCall types (ServerOnlyFn, ClientOnlyFn). + */ +function needsDirectCallDetection(kinds: Set): boolean { + for (const kind of kinds) { + if (LookupSetup[kind].type === 'directCall') { + return true + } + } + return false +} + +/** + * 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): boolean { + for (const kind of kinds) { + if (LookupSetup[kind].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): 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 + } + return calleeName !== undefined && DirectCallFactoryNames.has(calleeName) +} + +/** + * 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 + const isSimpleCall = + t.isIdentifier(node.callee) || + (t.isMemberExpression(node.callee) && + t.isIdentifier(node.callee.object) && + t.isIdentifier(node.callee.property)) + + if (!isSimpleCall) { + return false + } + + // Must be top-level: VariableDeclarator -> VariableDeclaration -> Program + const parent = path.parent + if (!t.isVariableDeclarator(parent) || parent.init !== node) { + return false + } + const grandParent = path.parentPath.parent + if (!t.isVariableDeclaration(grandParent)) { + return false + } + return t.isProgram(path.parentPath.parentPath?.parent) +} + +export class StartCompiler { + private moduleCache = new Map() + private initialized = false + private validLookupKinds: Set + 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() + + // Cached root path with trailing slash for dev mode function ID generation + private _rootWithTrailingSlash: string | undefined + + 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 + /** + * Returns the currently known server functions from previous builds. + * Used by server callers to look up canonical extracted filenames. + */ + getKnownServerFns?: () => Record + }, + ) { + this.validLookupKinds = options.lookupKinds + } + + /** + * 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 + extractedFilename: string + }): string { + if (this.mode === 'dev') { + // In dev, encode the file path and export name for direct lookup + let file = opts.extractedFilename + if (opts.extractedFilename.startsWith(this.rootWithTrailingSlash)) { + file = opts.extractedFilename.slice(this.rootWithTrailingSlash.length) + } + file = `/@id/${file}` + + 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) { + if (this.options.generateFunctionId) { + functionId = this.options.generateFunctionId({ + filename: opts.filename, + functionName: opts.functionName, + }) + } + 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 get rootWithTrailingSlash(): string { + if (this._rootWithTrailingSlash === undefined) { + this._rootWithTrailingSlash = this.options.root.endsWith('/') + ? this.options.root + : `${this.options.root}/` + } + return this._rootWithTrailingSlash + } + + 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 async 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'], + ]), + ) + + await Promise.all( + this.options.lookupConfigurations.map(async (config) => { + // 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 module resolution which may fail if + // the package isn't a direct dependency (e.g., @tanstack/react-router from + // within start-plugin-core). + if (config.kind !== 'Root') { + const setup = LookupSetup[config.kind] + if (setup.type === 'jsx') { + return + } + } + + const libId = await this.resolveIdCached(config.libName) + if (!libId) { + throw new Error(`could not resolve "${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. + * This is the core logic shared by ingestModule and ingestModuleFromAst. + */ + private extractModuleInfo( + ast: ReturnType, + id: string, + ): ModuleInfo { + const bindings = new Map() + const exports = new Map() + const reExportAllSources: Array = [] + + // 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, 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, sp.exported.name) + } + // 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, local) + + // When re-exporting from another module (export { foo } from './module'), + // create an import binding so the server function can be resolved + if (node.source) { + bindings.set(local, { + type: 'import', + source: node.source.value, + importedName: local, + }) + } + } + } + } else if (t.isExportDefaultDeclaration(node)) { + const d = node.declaration + if (t.isIdentifier(d)) { + exports.set('default', d.name) + } else { + const synth = '__default_export__' + bindings.set(synth, { type: 'var', init: d as t.Expression }) + exports.set('default', synth) + } + } else if (t.isExportAllDeclaration(node)) { + // Handle `export * from './module'` syntax + // Track the source so we can look up exports from it when needed + reExportAllSources.push(node.source.value) + } + } + + const info: ModuleInfo = { + id, + bindings, + exports, + reExportAllSources, + } + this.moduleCache.set(id, info) + return info + } + + public ingestModule({ code, id }: { code: string; id: string }) { + const ast = parseAst({ code }) + const info = this.extractModuleInfo(ast, id) + return { info, ast } + } + + public invalidateModule(id: string) { + // Note: Resolution caches (resolveIdCache, exportResolutionCache) are only + // used in build mode where there's no HMR. In dev mode, caching is disabled, + // so we only need to invalidate the moduleCache here. + return this.moduleCache.delete(id) + } + + public async compile({ + code, + id, + detectedKinds, + }: { + code: string + id: string + /** Pre-detected kinds present in this file. If not provided, all valid kinds are checked. */ + detectedKinds?: Set + }) { + 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 + + // Early exit if no kinds to process + if (fileKinds.size === 0) { + return null + } + + const checkDirectCalls = needsDirectCallDetection(fileKinds) + // 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) + + // 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 }) + + // 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) + // Get module info that was just cached by ingestModule + const moduleInfo = this.moduleCache.get(id)! + + 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) { + if (decl.init && t.isCallExpression(decl.init)) { + if (isMethodChainCandidate(decl.init, fileKinds)) { + candidateIndices.push(i) + break // Only need to mark this statement once + } + } + } + } + } + + // Early exit: no potential candidates found at top level + if (candidateIndices.length === 0) { + return null + } + + // 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) + } + }, + }) + } + // 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 + } + + // Pattern 2: Direct call pattern + if (checkDirectCalls) { + if (isTopLevelDirectCallCandidate(path)) { + candidatePaths.push(path) + } else if (isNestedDirectCallCandidate(node)) { + candidatePaths.push(path) + } + } + }, + // 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) { + return null + } + + // Resolve all candidates in parallel to determine their kinds + const resolvedCandidates = await Promise.all( + candidatePaths.map(async (path) => ({ + path, + kind: await this.resolveExprKind(path.node, id), + })), + ) + + // Filter to valid candidates + const validCandidates = resolvedCandidates.filter(({ kind }) => + this.validLookupKinds.has(kind as Exclude), + ) as Array<{ + path: babel.NodePath + kind: Exclude + }> + + if (validCandidates.length === 0 && jsxCandidatePaths.length === 0) { + return null + } + + // 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, + inputValidator: 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, + root: this.options.root, + framework: this.options.framework, + providerEnvName: this.options.providerEnvName, + + generateFunctionId: (opts) => this.generateFunctionId(opts), + getKnownServerFns: () => this.options.getKnownServerFns?.() ?? {}, + 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]) + } + } + + // Process each kind using its registered handler + for (const [kind, candidates] of candidatesByKind) { + const handler = KindHandlers[kind] + handler(candidates, context, kind) + } + + // 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) + + 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 + // (e.g. import-protection snippet display) to fall back to the shorter + // compiled output and fail to resolve original line numbers. + if (result.map) { + result.map.sourcesContent = [code] + } + + return result + } + + 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<{ moduleInfo: ModuleInfo; binding: Binding } | undefined> { + 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, 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 resolveBindingKind( + binding: Binding, + fileId: string, + visited = new Set(), + ): Promise { + if (binding.resolvedKind) { + return binding.resolvedKind + } + if (binding.type === 'import') { + // Fast path: check if this is a direct import from a known library + // (e.g., import { createServerFn } from '@tanstack/react-start') + // This avoids async resolveId calls for the common case + const knownExports = this.knownRootImports.get(binding.source) + if (knownExports) { + const kind = knownExports.get(binding.importedName) + if (kind) { + binding.resolvedKind = kind + return kind + } + } + + // Slow path: resolve through the module graph + const target = await this.resolveIdCached(binding.source, fileId) + if (!target) { + return 'None' + } + + const importedModule = await this.getModuleInfo(target) + + // Find the export, recursively searching through export * from chains + const found = await this.findExportInModule( + importedModule, + binding.importedName, + ) + + if (!found) { + return 'None' + } + + const { moduleInfo: foundModule, binding: foundBinding } = found + + if (foundBinding.resolvedKind) { + return foundBinding.resolvedKind + } + + const resolvedKind = await this.resolveBindingKind( + foundBinding, + foundModule.id, + visited, + ) + foundBinding.resolvedKind = resolvedKind + return resolvedKind + } + + 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) && + LookupSetup[resolvedKind].type === 'directCall' && + binding.init && + t.isCallExpression(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' + } + + // Unwrap common TypeScript/parenthesized wrappers first for efficiency + while ( + t.isTSAsExpression(expr) || + t.isTSNonNullExpression(expr) || + t.isParenthesizedExpression(expr) + ) { + expr = expr.expression + } + + 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 === '*' + ) { + // resolve the property from the target module + const targetModuleId = await this.resolveIdCached( + binding.source, + fileId, + ) + if (targetModuleId) { + const targetModule = await this.getModuleInfo(targetModuleId) + const localBindingName = targetModule.exports.get( + callee.property.name, + ) + if (localBindingName) { + const exportedBinding = + targetModule.bindings.get(localBindingName) + 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 + } +} + +/** + * 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/handleClientOnlyJSX.ts b/packages/start-plugin-core/src/start-compiler-plugin/handleClientOnlyJSX.ts similarity index 100% rename from packages/start-plugin-core/src/start-compiler/handleClientOnlyJSX.ts rename to packages/start-plugin-core/src/start-compiler-plugin/handleClientOnlyJSX.ts diff --git a/packages/start-plugin-core/src/start-compiler/handleCreateIsomorphicFn.ts b/packages/start-plugin-core/src/start-compiler-plugin/handleCreateIsomorphicFn.ts similarity index 100% rename from packages/start-plugin-core/src/start-compiler/handleCreateIsomorphicFn.ts rename to packages/start-plugin-core/src/start-compiler-plugin/handleCreateIsomorphicFn.ts diff --git a/packages/start-plugin-core/src/start-compiler-plugin/handleCreateMiddleware.ts b/packages/start-plugin-core/src/start-compiler-plugin/handleCreateMiddleware.ts new file mode 100644 index 0000000000..5428ce1a88 --- /dev/null +++ b/packages/start-plugin-core/src/start-compiler-plugin/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 { inputValidator, server } = candidate.methodChain + + if (inputValidator) { + const innerInputExpression = inputValidator.callPath.node.arguments[0] + + if (!innerInputExpression) { + throw new Error( + 'createMiddleware().inputValidator() must be called with a validator!', + ) + } + + // remove the validator call expression + stripMethodCall(inputValidator.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-plugin/handleCreateServerFn.ts similarity index 84% rename from packages/start-plugin-core/src/start-compiler/handleCreateServerFn.ts rename to packages/start-plugin-core/src/start-compiler-plugin/handleCreateServerFn.ts index dd152bdaa4..ddad1cf061 100644 --- a/packages/start-plugin-core/src/start-compiler/handleCreateServerFn.ts +++ b/packages/start-plugin-core/src/start-compiler-plugin/handleCreateServerFn.ts @@ -1,28 +1,13 @@ 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 { VITE_ENVIRONMENT_NAMES } from '../constants' 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) // ============================================================================ @@ -37,11 +22,16 @@ const clientRpcTemplate = babel.template.expression( `createClientRpc(%%functionId%%)`, ) -// Template for SSR caller files: createSsrRpc(functionId) +// Template for SSR caller files (manifest lookup): createSsrRpc(functionId) const ssrRpcManifestTemplate = babel.template.expression( `createSsrRpc(%%functionId%%)`, ) +// Template for SSR caller files (with importer): createSsrRpc(functionId, () => import(...).then(m => m['name'])) +const ssrRpcImporterTemplate = babel.template.expression( + `createSsrRpc(%%functionId%%, () => import(%%extractedFilename%%).then(m => m[%%functionName%%]))`, +) + // ============================================================================ // Runtime code cache (cached per framework to avoid repeated AST generation) // ============================================================================ @@ -85,6 +75,8 @@ function getCachedRuntimeCode( interface EnvConfig { /** Whether this environment is a client environment */ isClientEnvironment: boolean + /** Whether SSR is the provider environment */ + ssrIsProvider: boolean /** The runtime code type to use for imports */ runtimeCodeType: RuntimeCodeType } @@ -96,11 +88,15 @@ function getEnvConfig( context: CompilationContext, isProviderFile: boolean, ): EnvConfig { - const { env } = context + const { providerEnvName, env } = context + + // SSR is the provider when the provider environment is the default server environment + const ssrIsProvider = providerEnvName === VITE_ENVIRONMENT_NAMES.server if (isProviderFile) { return { isClientEnvironment: false, + ssrIsProvider, runtimeCodeType: 'provider', } } @@ -108,6 +104,7 @@ function getEnvConfig( if (env === 'client') { return { isClientEnvironment: true, + ssrIsProvider, runtimeCodeType: 'client', } } @@ -115,6 +112,7 @@ function getEnvConfig( // Server caller (SSR) return { isClientEnvironment: false, + ssrIsProvider, runtimeCodeType: 'ssr', } } @@ -156,6 +154,9 @@ function generateProviderRpcStub( */ function generateCallerRpcStub( functionId: string, + functionName: string, + extractedFilename: string, + isClientReferenced: boolean, envConfig: EnvConfig, ): t.Expression { const functionIdLiteral = t.stringLiteral(functionId) @@ -166,8 +167,20 @@ function generateCallerRpcStub( }) } - return ssrRpcManifestTemplate({ + // SSR caller + // When the function is client-referenced, it's in the manifest - use manifest lookup + // When SSR is NOT the provider, always use manifest lookup (no import() for different env) + // Otherwise, use the importer for functions only referenced on the server when SSR is the provider + if (isClientReferenced || !envConfig.ssrIsProvider) { + return ssrRpcManifestTemplate({ + functionId: functionIdLiteral, + }) + } + + return ssrRpcImporterTemplate({ functionId: functionIdLiteral, + extractedFilename: t.stringLiteral(extractedFilename), + functionName: t.stringLiteral(functionName), }) } @@ -197,13 +210,6 @@ export function handleCreateServerFn( } 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) @@ -221,19 +227,15 @@ export function handleCreateServerFn( for (const candidate of candidates) { const { path: candidatePath, methodChain } = candidate - const { validator, handler } = methodChain - - const candidateVariableDeclarator = getVariableDeclaratorForExpressionPath( - candidatePath as babel.NodePath, - ) + const { inputValidator, handler } = methodChain // Check if the call is assigned to a variable - if (!candidateVariableDeclarator) { + if (!candidatePath.parentPath.isVariableDeclarator()) { throw new Error('createServerFn must be assigned to a variable!') } // Get the identifier name of the variable - const variableDeclarator = candidateVariableDeclarator.node + const variableDeclarator = candidatePath.parentPath.node if (!t.isIdentifier(variableDeclarator.id)) { throw codeFrameError( context.code, @@ -255,39 +257,30 @@ export function handleCreateServerFn( 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' + const isClientReferenced = envConfig.isClientEnvironment || !!knownFn // 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] + // Handle input validator - remove on client + if (inputValidator) { + const innerInputExpression = inputValidator.callPath.node.arguments[0] if (!innerInputExpression) { throw new Error( - 'createServerFn().validator() must be called with a validator!', + 'createServerFn().inputValidator() must be called with a validator!', ) } // If we're on the client, remove the validator call expression if (context.env === 'client') { - stripMethodCall(validator.callPath) + stripMethodCall(inputValidator.callPath) } } @@ -367,7 +360,7 @@ export function handleCreateServerFn( ]) // Find the variable declaration statement containing our createServerFn - const variableDeclaration = candidateVariableDeclarator.parentPath + const variableDeclaration = candidatePath.parentPath.parentPath if (!variableDeclaration.isVariableDeclaration()) { throw new Error( 'Expected createServerFn to be in a VariableDeclaration', @@ -402,11 +395,26 @@ export function handleCreateServerFn( // Expected output format: // const myFn = createServerFn().handler(createClientRpc("id")) // or - // const myFn = createServerFn().handler(createSsrRpc("id")) + // const myFn = createServerFn().handler(createSsrRpc("id", () => import(...))) + + // If the handler function is an identifier, we need to remove the bound function + // from the file since it won't be needed + if (t.isIdentifier(handlerFn)) { + const binding = handlerFnPath.scope.getBinding(handlerFn.name) + if (binding) { + binding.path.remove() + } + } // Generate the RPC stub using pre-compiled templates // Note: Caller files only pass functionId, not the full serverFnMeta - const rpcStub = generateCallerRpcStub(functionId, envConfig) + const rpcStub = generateCallerRpcStub( + functionId, + functionName, + canonicalExtractedFilename, + isClientReferenced, + envConfig, + ) // Replace ONLY the handler argument with the RPC stub // Keep the createServerFn().handler() wrapper intact for client middleware @@ -433,14 +441,14 @@ export function handleCreateServerFn( ), ) } - - 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) { + if ( + !isProviderFile && + Object.keys(serverFnsById).length > 0 && + context.onServerFnsById + ) { context.onServerFnsById(serverFnsById) } @@ -508,25 +516,3 @@ function safeRemoveExports(ast: t.File): void { 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-plugin/handleEnvOnly.ts similarity index 100% rename from packages/start-plugin-core/src/start-compiler/handleEnvOnly.ts rename to packages/start-plugin-core/src/start-compiler-plugin/handleEnvOnly.ts diff --git a/packages/start-plugin-core/src/start-compiler-plugin/plugin.ts b/packages/start-plugin-core/src/start-compiler-plugin/plugin.ts new file mode 100644 index 0000000000..ef53af07e5 --- /dev/null +++ b/packages/start-plugin-core/src/start-compiler-plugin/plugin.ts @@ -0,0 +1,478 @@ +import assert from 'node:assert' +import { VIRTUAL_MODULES } from '@tanstack/start-server-core' +import { resolve as resolvePath } from 'pathe' +import { + SERVER_FN_LOOKUP, + TRANSFORM_ID_REGEX, + VITE_ENVIRONMENT_NAMES, +} from '../constants' +import { + KindDetectionPatterns, + LookupKindsPerEnv, + StartCompiler, + detectKindsInCode, +} from './compiler' +import { cleanId } from './utils' +import type { CompileStartFrameworkOptions } from '../types' +import type { LookupConfig, LookupKind } from './compiler' +import type { GenerateFunctionIdFnOptional, ServerFn } from './types' +import type { PluginOption } from 'vite' + +// Derive transform code filter from KindDetectionPatterns (single source of truth) +function getTransformCodeFilterForEnv(env: 'client' | 'server'): Array { + const validKinds = LookupKindsPerEnv[env] + const patterns: Array = [] + for (const [kind, pattern] of Object.entries(KindDetectionPatterns) as Array< + [LookupKind, RegExp] + >) { + if (validKinds.has(kind)) { + patterns.push(pattern) + } + } + return patterns +} + +const getLookupConfigurationsForEnv = ( + env: 'client' | 'server', + framework: CompileStartFrameworkOptions, +): Array => { + // Common configs for all environments + 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', + }, + ] + + if (env === 'client') { + return [ + { + libName: `@tanstack/${framework}-start`, + rootExport: 'createMiddleware', + kind: 'Root', + }, + { + libName: `@tanstack/${framework}-start`, + rootExport: 'createStart', + kind: 'Root', + }, + ...commonConfigs, + ] + } else { + // Server-only: add ClientOnly JSX component lookup + return [ + ...commonConfigs, + { + libName: `@tanstack/${framework}-router`, + rootExport: 'ClientOnly', + kind: 'ClientOnlyJSX', + }, + ] + } +} +// Re-export from shared constants for backwards compatibility +export { SERVER_FN_LOOKUP } + +function resolveViteId(id: string) { + return `\0${id}` +} + +const validateServerFnIdVirtualModule = `virtual:tanstack-start-validate-server-fn-id` + +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 } +} + +/** + * Generates the manifest module code for server functions. + * @param serverFnsById - Map of function IDs to their server function info + * @param includeClientReferencedCheck - Whether to include isClientReferenced flag and runtime check. + * This is needed when SSR is NOT the provider, so server-only-referenced functions in the manifest + * can be blocked from client HTTP requests. + */ +function generateManifestModule( + serverFnsById: Record, + includeClientReferencedCheck: boolean, +): string { + const manifestEntries = Object.entries(serverFnsById) + .map(([id, fn]) => { + const baseEntry = `'${id}': { + functionName: '${fn.functionName}', + importer: () => import(${JSON.stringify(fn.extractedFilename)})${ + includeClientReferencedCheck + ? `, + isClientReferenced: ${fn.isClientReferenced ?? true}` + : '' + } + }` + return baseEntry + }) + .join(',') + + const getServerFnByIdParams = includeClientReferencedCheck ? 'id, opts' : 'id' + const clientReferencedCheck = includeClientReferencedCheck + ? ` + // If called from client, only allow client-referenced functions + if (opts?.fromClient && !serverFnInfo.isClientReferenced) { + throw new Error('Server function not accessible from client: ' + id) + } +` + : '' + + return ` + const manifest = {${manifestEntries}} + + export async function getServerFnById(${getServerFnByIdParams}) { + const serverFnInfo = manifest[id] + if (!serverFnInfo) { + throw new Error('Server function info not found for ' + id) + } +${clientReferencedCheck} + const fnModule = await serverFnInfo.importer() + + if (!fnModule) { + console.info('serverFnInfo', serverFnInfo) + throw new Error('Server function module not resolved for ' + id) + } + + const action = fnModule[serverFnInfo.functionName] + + if (!action) { + console.info('serverFnInfo', serverFnInfo) + console.info('fnModule', fnModule) + + throw new Error( + \`Server function module export not resolved for serverFn ID: \${id}\`, + ) + } + return action + } + ` +} + +export interface StartCompilerPluginOptions { + framework: CompileStartFrameworkOptions + environments: Array<{ name: string; type: 'client' | 'server' }> + /** + * Custom function ID generator (optional). + */ + generateFunctionId?: GenerateFunctionIdFnOptional + /** + * The Vite environment name for the server function provider. + */ + providerEnvName: string +} + +export function startCompilerPlugin( + opts: StartCompilerPluginOptions, +): PluginOption { + const compilers: Record = {} + + // Shared registry of server functions across all environments + const serverFnsById: Record = {} + + const onServerFnsById = (d: Record) => { + Object.assign(serverFnsById, d) + } + + let root = process.cwd() + let _command: 'build' | 'serve' = 'build' + + const resolvedResolverVirtualImportId = resolveViteId( + VIRTUAL_MODULES.serverFnResolver, + ) + + // 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 { + // Derive transform code filter from KindDetectionPatterns (single source of truth) + const transformCodeFilter = getTransformCodeFilterForEnv(environment.type) + + return { + name: `tanstack-start-core::server-fn:${environment.name}`, + enforce: 'pre', + applyToEnvironment(env) { + return env.name === environment.name + }, + configResolved(config) { + root = config.root + _command = config.command + }, + 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) { + // Default to 'dev' mode for unknown environments (conservative: no caching) + const mode = this.environment.mode === 'build' ? 'build' : 'dev' + compiler = new StartCompiler({ + env: environment.type, + envName: environment.name, + root, + lookupKinds: LookupKindsPerEnv[environment.type], + lookupConfigurations: getLookupConfigurationsForEnv( + environment.type, + opts.framework, + ), + mode, + framework: opts.framework, + providerEnvName: opts.providerEnvName, + generateFunctionId: opts.generateFunctionId, + onServerFnsById, + getKnownServerFns: () => serverFnsById, + loadModule: async (id: string) => { + if (this.environment.mode === 'build') { + const loaded = await this.load({ id }) + // Handle modules with no runtime code (e.g., type-only exports). + // After TypeScript compilation, these become empty modules. + // Create an empty module info instead of throwing. + const code = loaded.code ?? '' + compiler!.ingestModule({ 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 + } + + // Detect which kinds are present in this file before parsing + const detectedKinds = detectKindsInCode(code, environment.type) + + const result = await compiler.compile({ + id, + code, + detectedKinds, + }) + 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) }) + }, + }, + }, + // 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' + ) { + // decoded.file looks like "/@id/src/foo.ts?tss-serverfn-split" + // Strip the /@id/ prefix and ?tss-serverfn-split suffix to + // get the original source file path that needs transforming. + let sourceFile = decoded.file + if (sourceFile.startsWith('/@id/')) { + sourceFile = sourceFile.slice('/@id/'.length) + } + const qIdx = sourceFile.indexOf('?') + if (qIdx !== -1) { + sourceFile = sourceFile.slice(0, qIdx) + } + + // 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. + // This plugin only runs in dev (apply: 'serve'), so mode + // must be 'dev' — assert to narrow to DevEnvironment. + assert(this.environment.mode === 'dev') + await this.environment.fetchModule(absPath) + + // 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 + { + name: 'tanstack-start-core:server-fn-resolver', + enforce: 'pre', + applyToEnvironment: (env) => { + return appliedResolverEnvironments.has(env.name) + }, + configResolved(config) { + root = config.root + _command = config.command + }, + resolveId: { + filter: { id: new RegExp(VIRTUAL_MODULES.serverFnResolver) }, + handler() { + return resolvedResolverVirtualImportId + }, + }, + load: { + filter: { id: new RegExp(resolvedResolverVirtualImportId) }, + handler() { + // When SSR is not the provider, SSR callers need to use HTTP to call server functions + // since they can't directly import from the provider environment + if (this.environment.name !== opts.providerEnvName) { + // SSR caller: use HTTP-based getServerFnById + // This re-exports from the start-server-core package which handles HTTP calls + return `export { getServerFnById } from '@tanstack/start-server-core/server-fn-ssr-caller'` + } + + if (this.environment.mode !== 'build') { + const mod = ` + export async function getServerFnById(id) { + 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] + } + ` + return mod + } + + // 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. + const includeClientReferencedCheck = !ssrIsProvider + return generateManifestModule( + serverFnsById, + includeClientReferencedCheck, + ) + }, + }, + }, + ] +} diff --git a/packages/start-plugin-core/src/start-compiler-plugin/types.ts b/packages/start-plugin-core/src/start-compiler-plugin/types.ts new file mode 100644 index 0000000000..141cb4e28f --- /dev/null +++ b/packages/start-plugin-core/src/start-compiler-plugin/types.ts @@ -0,0 +1,133 @@ +import type * as babel from '@babel/core' +import type * as t from '@babel/types' +import type { CompileStartFrameworkOptions } 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 { + readonly ast: t.File + readonly code: string + readonly id: string + readonly env: 'client' | 'server' + readonly envName: string + readonly root: string + /** The framework being used (e.g., 'react', 'solid') */ + readonly framework: CompileStartFrameworkOptions + /** The Vite environment name for the server function provider */ + readonly providerEnvName: string + + /** Generate a unique function ID */ + generateFunctionId: GenerateFunctionIdFn + /** Get known server functions from previous builds (e.g., client build) */ + getKnownServerFns: () => Record + + /** + * 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 + inputValidator: 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 + extractedFilename: string +}) => string + +/** + * Optional version that allows returning undefined to use default ID generation. + */ +export type GenerateFunctionIdFnOptional = ( + opts: Omit[0], 'extractedFilename'>, +) => string | undefined + +/** + * Function type for generating replacement code for server functions. + * Used internally by handleCreateServerFn. + */ +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-plugin/utils.ts b/packages/start-plugin-core/src/start-compiler-plugin/utils.ts new file mode 100644 index 0000000000..afc763627f --- /dev/null +++ b/packages/start-plugin-core/src/start-compiler-plugin/utils.ts @@ -0,0 +1,52 @@ +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) +} + +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 .inputValidator() 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-compiler/compiler.ts b/packages/start-plugin-core/src/start-compiler/compiler.ts deleted file mode 100644 index 13193f7249..0000000000 --- a/packages/start-plugin-core/src/start-compiler/compiler.ts +++ /dev/null @@ -1,2044 +0,0 @@ -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 deleted file mode 100644 index 387343bad9..0000000000 --- a/packages/start-plugin-core/src/start-compiler/config.ts +++ /dev/null @@ -1,119 +0,0 @@ -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/handleCreateMiddleware.ts b/packages/start-plugin-core/src/start-compiler/handleCreateMiddleware.ts deleted file mode 100644 index 22575ccc50..0000000000 --- a/packages/start-plugin-core/src/start-compiler/handleCreateMiddleware.ts +++ /dev/null @@ -1,39 +0,0 @@ -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/host.ts b/packages/start-plugin-core/src/start-compiler/host.ts deleted file mode 100644 index d6953f51f9..0000000000 --- a/packages/start-plugin-core/src/start-compiler/host.ts +++ /dev/null @@ -1,138 +0,0 @@ -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 deleted file mode 100644 index 7ddaafce5b..0000000000 --- a/packages/start-plugin-core/src/start-compiler/server-fn-id-check.ts +++ /dev/null @@ -1,75 +0,0 @@ -/** - * 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 deleted file mode 100644 index 2d50376a39..0000000000 --- a/packages/start-plugin-core/src/start-compiler/server-fn-resolver-module.ts +++ /dev/null @@ -1,79 +0,0 @@ -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 deleted file mode 100644 index 91b39f5f8a..0000000000 --- a/packages/start-plugin-core/src/start-compiler/types.ts +++ /dev/null @@ -1,135 +0,0 @@ -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 deleted file mode 100644 index 384a13113d..0000000000 --- a/packages/start-plugin-core/src/start-compiler/utils.ts +++ /dev/null @@ -1,59 +0,0 @@ -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 deleted file mode 100644 index bf87de9bfe..0000000000 --- a/packages/start-plugin-core/src/start-manifest-plugin/inlineCss.ts +++ /dev/null @@ -1,203 +0,0 @@ -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 index d5339f2983..df5c6dbae2 100644 --- a/packages/start-plugin-core/src/start-manifest-plugin/manifestBuilder.ts +++ b/packages/start-plugin-core/src/start-manifest-plugin/manifestBuilder.ts @@ -1,73 +1,34 @@ /* 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' +import { rootRouteId } from '@tanstack/router-core' +import { tsrSplit } from '@tanstack/router-plugin' +import type { RouterManagedTag } from '@tanstack/router-core' +import type { Rollup } from 'vite' + +const ROUTER_MANAGED_MODE = 1 +const NON_ROUTE_DYNAMIC_MODE = 2 +const VISITING_CHUNK = 1 type RouteTreeRoute = { filePath?: string preloads?: Array - scripts?: Array - css?: Array + assets?: Array children?: Array } type RouteTreeRoutes = Record -type AdditionalRouteManifestEntry = ManifestCssLink | ManifestScript - interface ScannedClientChunks { - entryChunk: NormalizedClientChunk - chunksByFileName: ReadonlyMap - routeChunksByFilePath: ReadonlyMap> + entryChunk: Rollup.OutputChunk + chunksByFileName: Map + routeChunksByFilePath: Map> + routeEntryChunks: Set } 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 + getChunkPreloads: (chunk: Rollup.OutputChunk) => Array + getStylesheetAsset: (cssFile: string) => RouterManagedTag } export function appendUniqueStrings( @@ -103,10 +64,12 @@ export function appendUniqueStrings( return result ?? target } -function appendUniqueStylesheets( - target: Array | undefined, - source: Array, +export function appendUniqueAssets( + target: Array | undefined, + source: Array, ) { + // Same semantics as appendUniqueStrings, but uniqueness is based on the + // serialized asset identity instead of object reference. if (source.length === 0) { return target } @@ -115,11 +78,11 @@ function appendUniqueStylesheets( return source } - const seen = new Set(target.map(getStylesheetIdentity)) - let result: Array | undefined + const seen = new Set(target.map(getAssetIdentity)) + let result: Array | undefined - for (const stylesheet of source) { - const identity = getStylesheetIdentity(stylesheet) + for (const asset of source) { + const identity = getAssetIdentity(asset) if (seen.has(identity)) { continue } @@ -128,153 +91,59 @@ function appendUniqueStylesheets( if (!result) { result = target.slice() } - result.push(stylesheet) + result.push(asset) } 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 +function getAssetIdentity(asset: RouterManagedTag) { + if (asset.tag === 'link' || asset.tag === 'script') { + const attrs = asset.attrs ?? {} + return [ + asset.tag, + 'href' in attrs ? String(attrs.href) : '', + 'src' in attrs ? String(attrs.src) : '', + 'rel' in attrs ? String(attrs.rel) : '', + 'type' in attrs ? String(attrs.type) : '', + asset.children ?? '', + ].join('|') } - const entries = Object.entries(attrs) - if (entries.length === 0) { - return null - } - - entries.sort(([left], [right]) => left.localeCompare(right)) - return Object.fromEntries(entries) + return JSON.stringify(asset) } function mergeRouteChunkData(options: { route: RouteTreeRoute - chunk: NormalizedClientChunk - getChunkCssAssets: (chunk: NormalizedClientChunk) => Array - getChunkPreloads: (chunk: NormalizedClientChunk) => Array + chunk: Rollup.OutputChunk + getChunkCssAssets: (chunk: Rollup.OutputChunk) => Array + getChunkPreloads: (chunk: Rollup.OutputChunk) => Array }) { - const stylesheets = options.getChunkCssAssets(options.chunk) + const chunkAssets = options.getChunkCssAssets(options.chunk) const chunkPreloads = options.getChunkPreloads(options.chunk) - appendRouteStylesheets(options.route, stylesheets) + options.route.assets = appendUniqueAssets(options.route.assets, chunkAssets) 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 + clientBundle: Rollup.OutputBundle routeTreeRoutes: RouteTreeRoutes basePath: string - inlineCss?: InlineCssOptions - scriptFormat?: ScriptFormat - additionalRouteAssets?: Partial< - Record> - > -}): StartManifest { - const scannedChunks = scanClientChunks(options.clientBuild) - const assetResolvers = createManifestAssetResolvers( - options.basePath, +}) { + const scannedChunks = scanClientChunks(options.clientBundle) + const hashedCssFiles = collectDynamicImportCss( + scannedChunks.routeEntryChunks, scannedChunks.chunksByFileName, + scannedChunks.entryChunk, ) + const assetResolvers = createManifestAssetResolvers({ + basePath: options.basePath, + hashedCssFiles, + }) const routes = buildRouteManifestRoutes({ routeTreeRoutes: options.routeTreeRoutes, @@ -282,98 +151,206 @@ export function buildStartManifest(options: { chunksByFileName: scannedChunks.chunksByFileName, entryChunk: scannedChunks.entryChunk, assetResolvers, - additionalRouteAssets: options.additionalRouteAssets, }) - appendEntryChunkScripts({ - route: routes[rootRouteId]!, - chunk: scannedChunks.entryChunk, - scriptFormat: options.scriptFormat ?? 'module', - getAssetPath: assetResolvers.getAssetPath, - }) + dedupeNestedRoutePreloads(routes[rootRouteId]!, routes) - dedupeNestedRouteManifestEntries(rootRouteId, routes[rootRouteId]!, routes) - - // Prune routes with no manifest data - for (const routeId in routes) { + // Prune routes with no assets or preloads from the manifest + for (const routeId of Object.keys(routes)) { const route = routes[routeId]! - const hasScripts = route.scripts && route.scripts.length > 0 - const hasCssLinks = route.css && route.css.length > 0 + const hasAssets = route.assets && route.assets.length > 0 const hasPreloads = route.preloads && route.preloads.length > 0 - if (!hasScripts && !hasCssLinks && !hasPreloads) { + if (!hasAssets && !hasPreloads) { delete routes[routeId] } } - const result: StartManifest = { + return { routes, + clientEntry: assetResolvers.getAssetPath(scannedChunks.entryChunk.fileName), } - - 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, + clientBundle: Rollup.OutputBundle, ): ScannedClientChunks { - const entryChunk = clientBuild.chunksByFileName.get( - clientBuild.entryChunkFileName, - ) + let entryChunk: Rollup.OutputChunk | undefined + const chunksByFileName = new Map() + const routeChunksByFilePath = new Map>() + const routeEntryChunks = new Set() - if (!entryChunk) { - throw new Error(`Missing entry chunk: ${clientBuild.entryChunkFileName}`) + for (const fileName in clientBundle) { + const bundleEntry = clientBundle[fileName]! + if (bundleEntry.type !== 'chunk') { + continue + } + + chunksByFileName.set(bundleEntry.fileName, bundleEntry) + + if (bundleEntry.isEntry) { + if (entryChunk) { + throw new Error( + `multiple entries detected: ${entryChunk.fileName} ${bundleEntry.fileName}`, + ) + } + entryChunk = bundleEntry + } + + const routeFilePaths = getRouteFilePathsFromModuleIds(bundleEntry.moduleIds) + if (routeFilePaths.length === 0) { + continue + } + + routeEntryChunks.add(bundleEntry) + + for (let i = 0; i < routeFilePaths.length; i++) { + const routeFilePath = routeFilePaths[i]! + let chunks = routeChunksByFilePath.get(routeFilePath) + if (chunks === undefined) { + chunks = [] + routeChunksByFilePath.set(routeFilePath, chunks) + } + chunks.push(bundleEntry) + } } - 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) - } - } + if (!entryChunk) { + throw new Error('No entry file found') } return { entryChunk, - chunksByFileName: clientBuild.chunksByFileName, + chunksByFileName, routeChunksByFilePath, + routeEntryChunks, } } -export function createManifestAssetResolvers( - basePath: string, - chunksByFileName: ReadonlyMap, -): ManifestAssetResolvers { +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) + + // Fast check before allocating URLSearchParams + 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) { + routeFilePaths = [] + seenRouteFilePaths = new Set() + } + + routeFilePaths.push(routeFilePath) + seenRouteFilePaths!.add(routeFilePath) + } + + return routeFilePaths ?? [] +} + +export function collectDynamicImportCss( + routeEntryChunks: Set, + chunksByFileName: Map, + entryChunk?: Rollup.OutputChunk, +) { + const routerManagedCssFiles = new Set() + const nonRouteDynamicCssFiles = new Set() + const hashedCssFiles = new Set() + const visitedByChunk = new Map() + const chunkStack: Array = [] + const modeStack: Array = [] + + for (const routeEntryChunk of routeEntryChunks) { + chunkStack.push(routeEntryChunk) + modeStack.push(ROUTER_MANAGED_MODE) + } + + if (entryChunk) { + chunkStack.push(entryChunk) + modeStack.push(ROUTER_MANAGED_MODE) + } + + while (chunkStack.length > 0) { + const chunk = chunkStack.pop()! + const mode = modeStack.pop()! + const previousMode = visitedByChunk.get(chunk) ?? 0 + + if ((previousMode & mode) === mode) { + continue + } + + visitedByChunk.set(chunk, previousMode | mode) + + if ((mode & ROUTER_MANAGED_MODE) !== 0) { + for (const cssFile of chunk.viteMetadata?.importedCss ?? []) { + routerManagedCssFiles.add(cssFile) + } + } + + if ((mode & NON_ROUTE_DYNAMIC_MODE) !== 0) { + for (const cssFile of chunk.viteMetadata?.importedCss ?? []) { + nonRouteDynamicCssFiles.add(cssFile) + } + } + + for (let i = 0; i < chunk.imports.length; i++) { + const importedChunk = chunksByFileName.get(chunk.imports[i]!) + if (importedChunk) { + chunkStack.push(importedChunk) + modeStack.push(mode) + } + } + + for (let i = 0; i < chunk.dynamicImports.length; i++) { + const dynamicImportedChunk = chunksByFileName.get( + chunk.dynamicImports[i]!, + ) + if (dynamicImportedChunk) { + chunkStack.push(dynamicImportedChunk) + modeStack.push( + (mode & NON_ROUTE_DYNAMIC_MODE) !== 0 || + !routeEntryChunks.has(dynamicImportedChunk) + ? NON_ROUTE_DYNAMIC_MODE + : ROUTER_MANAGED_MODE, + ) + } + } + } + + for (const cssFile of routerManagedCssFiles) { + if (nonRouteDynamicCssFiles.has(cssFile)) { + hashedCssFiles.add(cssFile) + } + } + + return hashedCssFiles +} + +export function createManifestAssetResolvers(options: { + basePath: string + hashedCssFiles?: Set +}): ManifestAssetResolvers { const assetPathByFileName = new Map() - const stylesheetLinkByFileName = new Map() - const closureByChunk = new Map() - const preloadsByChunk = new Map>() - const cssAssetsByChunk = new Map< - NormalizedClientChunk, - Array - >() + const stylesheetAssetByFileName = new Map() + const preloadsByChunk = new Map>() const getAssetPath = (fileName: string) => { const cachedPath = assetPathByFileName.get(fileName) @@ -381,202 +358,117 @@ export function createManifestAssetResolvers( return cachedPath } - const assetPath = joinURL(basePath, fileName) + const assetPath = joinURL(options.basePath, fileName) assetPathByFileName.set(fileName, assetPath) return assetPath } - const getStylesheetLink = (cssFile: string) => { - const cachedLink = stylesheetLinkByFileName.get(cssFile) - if (cachedLink) { - return cachedLink + const getStylesheetAsset = (cssFile: string) => { + const cachedAsset = stylesheetAssetByFileName.get(cssFile) + if (cachedAsset) { + return cachedAsset } const href = getAssetPath(cssFile) - const link = href satisfies ManifestCssLink + const asset = { + tag: 'link', + attrs: { + rel: 'stylesheet', + href: options.hashedCssFiles?.has(cssFile) ? `${href}#` : href, + type: 'text/css', + }, + } satisfies RouterManagedTag - stylesheetLinkByFileName.set(cssFile, link) - return link + stylesheetAssetByFileName.set(cssFile, asset) + return asset } - // 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 getChunkPreloads = (chunk: Rollup.OutputChunk) => { 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]!)) + for (let i = 0; i < chunk.imports.length; i++) { + preloads.push(getAssetPath(chunk.imports[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, + getStylesheetAsset, } } -function buildInlineCssManifestData(options: { - routes: Record - basePath: string - cssContentByFileName: ReadonlyMap | undefined - transformAssets: boolean -}): StartManifest['inlineCss'] { - const stylesheetHrefs = new Set() +export function createChunkCssAssetCollector(options: { + chunksByFileName: Map + getStylesheetAsset: (cssFile: string) => RouterManagedTag +}) { + const assetsByChunk = new Map>() + const stateByChunk = new Map() - 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 getChunkCssAssets = ( + chunk: Rollup.OutputChunk, + ): Array => { + const cachedAssets = assetsByChunk.get(chunk) + if (cachedAssets) { + return cachedAssets } - const result = processInlineCssUrls({ - css, - cssHref, - templates: options.transformAssets, - }) - - styles[cssHref] = result.css - if (result.template) { - templates ||= {} - templates[cssHref] = result.template + if (stateByChunk.get(chunk) === VISITING_CHUNK) { + return [] } - missingHrefs.delete(cssHref) + stateByChunk.set(chunk, VISITING_CHUNK) + + const assets: Array = [] + + for (const cssFile of chunk.viteMetadata?.importedCss ?? []) { + assets.push(options.getStylesheetAsset(cssFile)) + } + + for (let i = 0; i < chunk.imports.length; i++) { + const importedChunk = options.chunksByFileName.get(chunk.imports[i]!) + if (!importedChunk) { + continue + } + + const importedAssets = getChunkCssAssets(importedChunk) + for (let j = 0; j < importedAssets.length; j++) { + assets.push(importedAssets[j]!) + } + } + + stateByChunk.delete(chunk) + assetsByChunk.set(chunk, assets) + return assets } - if (missingHrefs.size > 0) { - throw new Error( - `TanStack Start inlineCss could not find CSS content for: ${Array.from( - missingHrefs, - ).join(', ')}`, - ) - } - - return { - styles, - ...(templates ? { templates } : {}), - } + return { getChunkCssAssets } } export function buildRouteManifestRoutes(options: { routeTreeRoutes: RouteTreeRoutes - routeChunksByFilePath: ReadonlyMap< - string, - ReadonlyArray - > - chunksByFileName: ReadonlyMap - entryChunk: NormalizedClientChunk + routeChunksByFilePath: Map> + chunksByFileName: Map + entryChunk: Rollup.OutputChunk assetResolvers: ManifestAssetResolvers - additionalRouteAssets?: Partial< - Record> - > }) { const routes: Record = {} - const getChunkCssAssets = options.assetResolvers.getChunkCssAssets + const getChunkCssAssets = createChunkCssAssetCollector({ + chunksByFileName: options.chunksByFileName, + getStylesheetAsset: options.assetResolvers.getStylesheetAsset, + }).getChunkCssAssets for (const [routeId, route] of Object.entries(options.routeTreeRoutes)) { if (!route.filePath) { if (routeId === rootRouteId) { - routes[routeId] = { ...route } + routes[routeId] = route continue } @@ -585,7 +477,7 @@ export function buildRouteManifestRoutes(options: { const chunks = options.routeChunksByFilePath.get(route.filePath) if (!chunks) { - routes[routeId] = { ...route } + routes[routeId] = route continue } @@ -599,35 +491,10 @@ export function buildRouteManifestRoutes(options: { 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, @@ -635,104 +502,29 @@ export function buildRouteManifestRoutes(options: { 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, +export function dedupeNestedRoutePreloads( + route: { preloads?: Array; children?: Array }, + 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 + 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 (seenPreloads.has(preload)) { if (dedupedPreloads === undefined) { dedupedPreloads = routePreloads.slice(0, i) } continue } - seenPreloads.add(preloadHref) + seenPreloads.add(preload) if (dedupedPreloads) { dedupedPreloads.push(preload) @@ -745,104 +537,19 @@ function dedupeNestedRouteManifestEntries( } } - 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, + dedupeNestedRoutePreloads( + routesById[childRouteId]!, 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]!)) + seenPreloads.delete(routePreloads[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 new file mode 100644 index 0000000000..97adf931fe --- /dev/null +++ b/packages/start-plugin-core/src/start-manifest-plugin/plugin.ts @@ -0,0 +1,61 @@ +import { joinURL } from 'ufo' +import { VIRTUAL_MODULES } from '@tanstack/start-server-core' +import { resolveViteId } from '../utils' +import { ENTRY_POINTS } from '../constants' +import { buildStartManifest } from './manifestBuilder' +import type { GetConfigFn } from '../types' +import type { PluginOption, Rollup } from 'vite' + +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.name !== resolvedStartConfig.serverFnProviderEnv + ) { + return `export default {}` + } + + if (this.environment.config.command === 'serve') { + return `export const tsrStartManifest = () => ({ + routes: {}, + clientEntry: '${joinURL(resolvedStartConfig.viteAppBase, '@id', ENTRY_POINTS.client)}', + })` + } + + const routeTreeRoutes = globalThis.TSS_ROUTES_MANIFEST + const startManifest = buildStartManifest({ + clientBundle: opts.getClientBundle(), + routeTreeRoutes, + basePath: resolvedStartConfig.viteAppBase, + }) + + 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 deleted file mode 100644 index 3d3e5ea086..0000000000 --- a/packages/start-plugin-core/src/start-router-plugin/generator-config.ts +++ /dev/null @@ -1,41 +0,0 @@ -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 new file mode 100644 index 0000000000..1536d19c91 --- /dev/null +++ b/packages/start-plugin-core/src/start-router-plugin/plugin.ts @@ -0,0 +1,253 @@ +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 { GetConfigFn, 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 + ) +} + +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 deleted file mode 100644 index c56ffbf90d..0000000000 --- a/packages/start-plugin-core/src/start-router-plugin/route-tree-footer.ts +++ /dev/null @@ -1,99 +0,0 @@ -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 index db94e343d5..e2273d1a12 100644 --- a/packages/start-plugin-core/src/types.ts +++ b/packages/start-plugin-core/src/types.ts @@ -1,145 +1,20 @@ -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 { +export interface TanStackStartVitePluginCoreOptions { framework: CompileStartFrameworkOptions defaultEntryPaths: { client: string server: string start: string } - providerEnvironmentName: string - ssrIsProvider: boolean - serializationAdapters?: Array | undefined - compilerTransforms?: Array | undefined - serverFnProviderModuleDirectives?: ReadonlyArray | undefined + serverFn?: { + ssr?: { + getServerFnById?: string + } + providerEnv?: string + } } export interface ResolvedStartConfig { @@ -147,11 +22,12 @@ export interface ResolvedStartConfig { startFilePath: string | undefined routerFilePath: string srcDirectory: string - basePaths: NormalizedBasePaths - outputDirectories: NormalizedOutputDirectories + viteAppBase: string + serverFnProviderEnv: string } export type GetConfigFn = () => { startConfig: TanStackStartOutputConfig resolvedStartConfig: ResolvedStartConfig + corePluginOpts: TanStackStartVitePluginCoreOptions } diff --git a/packages/start-plugin-core/src/utils.ts b/packages/start-plugin-core/src/utils.ts index 2fb1bb5b69..5b0950604b 100644 --- a/packages/start-plugin-core/src/utils.ts +++ b/packages/start-plugin-core/src/utils.ts @@ -1,14 +1,4 @@ -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. - */ +/** Read `build.rollupOptions` or `build.rolldownOptions` from a build config. */ export function getBundlerOptions(build: any): any { return build?.rolldownOptions ?? build?.rollupOptions } @@ -17,14 +7,6 @@ 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 { @@ -35,11 +17,3 @@ 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 deleted file mode 100644 index a60be55efb..0000000000 --- a/packages/start-plugin-core/src/vite/bundled-dev.ts +++ /dev/null @@ -1,7 +0,0 @@ -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 deleted file mode 100644 index 1c076a3c7c..0000000000 --- a/packages/start-plugin-core/src/vite/createVirtualModule.ts +++ /dev/null @@ -1,50 +0,0 @@ -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 deleted file mode 100644 index 0470d8c1e4..0000000000 --- a/packages/start-plugin-core/src/vite/dev-server-plugin/dev-styles.ts +++ /dev/null @@ -1,402 +0,0 @@ -/** - * 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 deleted file mode 100644 index 4f0b2e632a..0000000000 --- a/packages/start-plugin-core/src/vite/dev-server-plugin/plugin.ts +++ /dev/null @@ -1,323 +0,0 @@ -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 deleted file mode 100644 index ec3abd7f18..0000000000 --- a/packages/start-plugin-core/src/vite/import-protection-plugin/INTERNALS.md +++ /dev/null @@ -1,580 +0,0 @@ -# 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 deleted file mode 100644 index dcbec56655..0000000000 --- a/packages/start-plugin-core/src/vite/import-protection-plugin/plugin.ts +++ /dev/null @@ -1,2380 +0,0 @@ -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 deleted file mode 100644 index 21691783ea..0000000000 --- a/packages/start-plugin-core/src/vite/import-protection-plugin/types.ts +++ /dev/null @@ -1,104 +0,0 @@ -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 deleted file mode 100644 index d27612c38b..0000000000 --- a/packages/start-plugin-core/src/vite/import-protection-plugin/virtualModules.ts +++ /dev/null @@ -1,122 +0,0 @@ -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 deleted file mode 100644 index d50bb40981..0000000000 --- a/packages/start-plugin-core/src/vite/index.ts +++ /dev/null @@ -1,13 +0,0 @@ -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/vite/module-id.ts b/packages/start-plugin-core/src/vite/module-id.ts deleted file mode 100644 index ef2ad98f10..0000000000 --- a/packages/start-plugin-core/src/vite/module-id.ts +++ /dev/null @@ -1,31 +0,0 @@ -/** 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/vite/planning.ts b/packages/start-plugin-core/src/vite/planning.ts deleted file mode 100644 index fa11b98c47..0000000000 --- a/packages/start-plugin-core/src/vite/planning.ts +++ /dev/null @@ -1,242 +0,0 @@ -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 deleted file mode 100644 index 5e5bca4a2e..0000000000 --- a/packages/start-plugin-core/src/vite/plugin.ts +++ /dev/null @@ -1,282 +0,0 @@ -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 deleted file mode 100644 index 59b6d1a580..0000000000 --- a/packages/start-plugin-core/src/vite/plugins.ts +++ /dev/null @@ -1,137 +0,0 @@ -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 deleted file mode 100644 index 2e74b7635d..0000000000 --- a/packages/start-plugin-core/src/vite/post-server-build.ts +++ /dev/null @@ -1,28 +0,0 @@ -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 deleted file mode 100644 index 5d1838e43a..0000000000 --- a/packages/start-plugin-core/src/vite/prerender.ts +++ /dev/null @@ -1,93 +0,0 @@ -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 deleted file mode 100644 index 1541d9edfb..0000000000 --- a/packages/start-plugin-core/src/vite/preview-server-plugin/plugin.ts +++ /dev/null @@ -1,73 +0,0 @@ -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 deleted file mode 100644 index c142245fc0..0000000000 --- a/packages/start-plugin-core/src/vite/schema.ts +++ /dev/null @@ -1,37 +0,0 @@ -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 deleted file mode 100644 index 26eb92c5ca..0000000000 --- a/packages/start-plugin-core/src/vite/serialization-adapters-plugin.ts +++ /dev/null @@ -1,86 +0,0 @@ -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 deleted file mode 100644 index 5ff7e04773..0000000000 --- a/packages/start-plugin-core/src/vite/start-compiler-plugin/hot-update.ts +++ /dev/null @@ -1,24 +0,0 @@ -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 deleted file mode 100644 index 1324894f68..0000000000 --- a/packages/start-plugin-core/src/vite/start-compiler-plugin/module-specifier.ts +++ /dev/null @@ -1,41 +0,0 @@ -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 deleted file mode 100644 index 3a93e286d1..0000000000 --- a/packages/start-plugin-core/src/vite/start-compiler-plugin/plugin.ts +++ /dev/null @@ -1,690 +0,0 @@ -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 deleted file mode 100644 index 0c85fe2eb5..0000000000 --- a/packages/start-plugin-core/src/vite/start-manifest-plugin/normalized-client-build.ts +++ /dev/null @@ -1,160 +0,0 @@ -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 deleted file mode 100644 index 03e84c32c2..0000000000 --- a/packages/start-plugin-core/src/vite/start-manifest-plugin/plugin.ts +++ /dev/null @@ -1,191 +0,0 @@ -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 deleted file mode 100644 index 8df06af4f5..0000000000 --- a/packages/start-plugin-core/src/vite/start-router-plugin/plugin.ts +++ /dev/null @@ -1,179 +0,0 @@ -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 deleted file mode 100644 index 4b98551268..0000000000 --- a/packages/start-plugin-core/src/vite/types.ts +++ /dev/null @@ -1,18 +0,0 @@ -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 index fa48668a38..fedb3851f0 100644 --- a/packages/start-plugin-core/tests/clientOnlyJSX/clientOnlyJSX.test.ts +++ b/packages/start-plugin-core/tests/clientOnlyJSX/clientOnlyJSX.test.ts @@ -5,8 +5,7 @@ import { describe, expect, test } from 'vitest' import { detectKindsInCode, StartCompiler, -} from '../../src/start-compiler/compiler' -import { formatSnapshot } from '../format-snapshot' +} from '../../src/start-compiler-plugin/compiler' // Default test options for StartCompiler function getDefaultTestOptions(env: 'client' | 'server') { @@ -39,7 +38,6 @@ async function compile(opts: { kind: 'ClientOnlyJSX', }, ], - getKnownServerFns: () => ({}), resolveId: async (id) => { return id }, @@ -73,9 +71,9 @@ describe('ClientOnlyJSX compiles correctly', async () => { }) if (compiledResult) { - await expect( - await formatSnapshot(compiledResult.code, filename), - ).toMatchFileSnapshot(`./snapshots/server/${filename}`) + await expect(compiledResult.code).toMatchFileSnapshot( + `./snapshots/server/${filename}`, + ) } else { // No transformation - for files where ClientOnly is not from TanStack await expect('no-transform').toMatchFileSnapshot( diff --git a/packages/start-plugin-core/tests/clientOnlyJSX/snapshots/server/clientOnlyBasic.tsx b/packages/start-plugin-core/tests/clientOnlyJSX/snapshots/server/clientOnlyBasic.tsx index 96de7844f6..82195ff739 100644 --- a/packages/start-plugin-core/tests/clientOnlyJSX/snapshots/server/clientOnlyBasic.tsx +++ b/packages/start-plugin-core/tests/clientOnlyJSX/snapshots/server/clientOnlyBasic.tsx @@ -1,8 +1,6 @@ -import { ClientOnly } from '@tanstack/react-router' +import { ClientOnly } from '@tanstack/react-router'; export function MyComponent() { - return ( -
+ return
Loading...
} /> -
- ) -} +
; +} \ No newline at end of file diff --git a/packages/start-plugin-core/tests/clientOnlyJSX/snapshots/server/clientOnlyMultiple.tsx b/packages/start-plugin-core/tests/clientOnlyJSX/snapshots/server/clientOnlyMultiple.tsx index 6b95090d3f..f437f41b05 100644 --- a/packages/start-plugin-core/tests/clientOnlyJSX/snapshots/server/clientOnlyMultiple.tsx +++ b/packages/start-plugin-core/tests/clientOnlyJSX/snapshots/server/clientOnlyMultiple.tsx @@ -1,10 +1,8 @@ -import { ClientOnly } from '@tanstack/react-router' +import { ClientOnly } from '@tanstack/react-router'; export function MyComponent() { - return ( -
+ return
Loading video...} />

Some server content

Loading audio...} /> -
- ) -} +
; +} \ No newline at end of file diff --git a/packages/start-plugin-core/tests/clientOnlyJSX/snapshots/server/clientOnlyNested.tsx b/packages/start-plugin-core/tests/clientOnlyJSX/snapshots/server/clientOnlyNested.tsx index f3d5d3b526..9d48d6577d 100644 --- a/packages/start-plugin-core/tests/clientOnlyJSX/snapshots/server/clientOnlyNested.tsx +++ b/packages/start-plugin-core/tests/clientOnlyJSX/snapshots/server/clientOnlyNested.tsx @@ -1,8 +1,6 @@ -import { ClientOnly } from '@tanstack/react-router' +import { ClientOnly } from '@tanstack/react-router'; export function MyComponent() { - return ( -
+ return
Outer loading
} /> -
- ) -} +
; +} \ No newline at end of file diff --git a/packages/start-plugin-core/tests/clientOnlyJSX/snapshots/server/clientOnlyNoFallback.tsx b/packages/start-plugin-core/tests/clientOnlyJSX/snapshots/server/clientOnlyNoFallback.tsx index 40551a6dad..9224aeb1cf 100644 --- a/packages/start-plugin-core/tests/clientOnlyJSX/snapshots/server/clientOnlyNoFallback.tsx +++ b/packages/start-plugin-core/tests/clientOnlyJSX/snapshots/server/clientOnlyNoFallback.tsx @@ -1,8 +1,6 @@ -import { ClientOnly } from '@tanstack/react-router' +import { ClientOnly } from '@tanstack/react-router'; export function MyComponent() { - return ( -
+ return
-
- ) -} +
; +} \ 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 index 9a537448b0..de9e376b63 100644 --- a/packages/start-plugin-core/tests/clientOnlyJSX/snapshots/server/clientOnlyRenamed.tsx +++ b/packages/start-plugin-core/tests/clientOnlyJSX/snapshots/server/clientOnlyRenamed.tsx @@ -1,9 +1,7 @@ // Test: ClientOnly imported with an alias should still be transformed -import { ClientOnly as CO } from '@tanstack/react-router' +import { ClientOnly as CO } from '@tanstack/react-router'; export function MyComponent() { - return ( -
+ return
Loading...
} /> -
- ) -} +
; +} \ No newline at end of file diff --git a/packages/start-plugin-core/tests/compiler.test.ts b/packages/start-plugin-core/tests/compiler.test.ts index 68e193204f..a063ea3ffe 100644 --- a/packages/start-plugin-core/tests/compiler.test.ts +++ b/packages/start-plugin-core/tests/compiler.test.ts @@ -2,11 +2,11 @@ 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' +} from '../src/start-compiler-plugin/compiler' +import type { + LookupConfig, + LookupKind, +} from '../src/start-compiler-plugin/compiler' // Default test options for StartCompiler function getDefaultTestOptions(env: 'client' | 'server') { @@ -20,12 +20,7 @@ function getDefaultTestOptions(env: 'client' | 'server') { } // Helper to create a compiler with all kinds enabled -function createFullCompiler( - env: 'client' | 'server', - opts?: { - serverFnProviderModuleDirectives?: ReadonlyArray | undefined - }, -) { +function createFullCompiler(env: 'client' | 'server') { const lookupKinds: Set = env === 'client' ? new Set([ @@ -70,59 +65,8 @@ function createFullCompiler( ...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, }) } @@ -185,29 +129,6 @@ describe('detectKindsInCode', () => { 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', () => { @@ -457,216 +378,6 @@ describe('compiler handles multiple files with different kinds', () => { }) }) -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') @@ -729,7 +440,6 @@ test('ingestModule handles empty code gracefully', () => { ...getDefaultTestOptions('client'), lookupKinds: new Set(['ServerFn']), lookupConfigurations: [], - getKnownServerFns: () => ({}), loadModule: async () => {}, resolveId: async (id) => id, }) @@ -745,53 +455,6 @@ test('ingestModule handles empty code gracefully', () => { }).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 @@ -860,7 +523,6 @@ describe('calling result of createServerOnlyFn/createClientOnlyFn', () => { providerEnvName: 'ssr', lookupKinds: new Set(['ServerOnlyFn', 'ClientOnlyFn']), lookupConfigurations: [], - getKnownServerFns: () => ({}), loadModule: async (id) => { const code = virtualModules[id] if (code) { @@ -953,7 +615,6 @@ describe('re-export chain resolution', () => { providerEnvName: 'ssr', lookupKinds, lookupConfigurations: [], - getKnownServerFns: () => ({}), loadModule: async (id) => { const code = virtualModules[id] if (code) { @@ -1045,7 +706,6 @@ describe('re-export chain resolution', () => { providerEnvName: 'ssr', lookupKinds: new Set(['IsomorphicFn', 'ServerOnlyFn', 'ClientOnlyFn']), lookupConfigurations: [], - getKnownServerFns: () => ({}), loadModule: async (id) => { const code = deeperVirtualModules[id] if (code) { @@ -1066,532 +726,4 @@ describe('re-export chain resolution', () => { 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 0b6a5aa26a..ca29207145 100644 --- a/packages/start-plugin-core/tests/createIsomorphicFn/createIsomorphicFn.test.ts +++ b/packages/start-plugin-core/tests/createIsomorphicFn/createIsomorphicFn.test.ts @@ -2,8 +2,7 @@ import { readFile, readdir } from 'node:fs/promises' import path from 'node:path' import { describe, expect, test } from 'vitest' -import { StartCompiler } from '../../src/start-compiler/compiler' -import { formatSnapshot } from '../format-snapshot' +import { StartCompiler } from '../../src/start-compiler-plugin/compiler' // Default test options for StartCompiler function getDefaultTestOptions(env: 'client' | 'server') { @@ -35,7 +34,6 @@ async function compile(opts: { kind: 'IsomorphicFn', }, ], - getKnownServerFns: () => ({}), resolveId: async (id) => { return id }, @@ -69,9 +67,9 @@ describe('createIsomorphicFn compiles correctly', async () => { id: filename, }) - await expect( - await formatSnapshot(compiledResult!.code, filename), - ).toMatchFileSnapshot(`./snapshots/${env}/${filename}`) + await expect(compiledResult!.code).toMatchFileSnapshot( + `./snapshots/${env}/${filename}`, + ) }, ) }) 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 index 7e8ade3201..efc23cf31b 100644 --- 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 @@ -1,5 +1,5 @@ const getEnvironment = () => { - console.log('[CLIENT] getEnvironment called') - return 'client' -} -const moduleLevel = getEnvironment() + console.log('[CLIENT] getEnvironment called'); + return 'client'; +}; +const moduleLevel = getEnvironment(); \ No newline at end of file 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 20fbb3d4dc..956fe05f98 100644 --- a/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnDestructured.tsx +++ b/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnDestructured.tsx @@ -1,13 +1,13 @@ -import { createIsomorphicFn } from '@tanstack/react-start' -const noImpl = createIsomorphicFn() -const serverOnlyFn = () => {} -const clientOnlyFn = () => 'client' -const serverThenClientFn = () => 'client' -const clientThenServerFn = () => 'client' -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 +const clientOnlyFnAbstracted = abstractedClientFn; +const serverThenClientFnAbstracted = abstractedClientFn; +const clientThenServerFnAbstracted = abstractedClientFn; \ No newline at end of file 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 d8f76d94b0..5e167daeb6 100644 --- a/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnDestructuredRename.tsx +++ b/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnDestructuredRename.tsx @@ -1,13 +1,13 @@ -import { createIsomorphicFn as isomorphicFn } from '@tanstack/react-start' -const noImpl = isomorphicFn() -const serverOnlyFn = () => {} -const clientOnlyFn = () => 'client' -const serverThenClientFn = () => 'client' -const clientThenServerFn = () => 'client' -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 +const clientOnlyFnAbstracted = abstractedClientFn; +const serverThenClientFnAbstracted = abstractedClientFn; +const clientThenServerFnAbstracted = abstractedClientFn; \ No newline at end of file diff --git a/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnFactory.tsx b/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnFactory.tsx index 08772a9178..b54ad664b1 100644 --- a/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnFactory.tsx +++ b/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnFactory.tsx @@ -1,22 +1,27 @@ -import { createIsomorphicFn } from '@tanstack/react-start' +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}` + return () => `client-${platform}`; } + // Arrow function factory with only server implementation export const createServerImplFn = (name: string) => { - return () => {} -} + return () => {}; +}; + // Arrow function factory with only client implementation export const createClientImplFn = (name: string) => { return () => { - console.log(`Client: ${name}`) - return `client-${name}` - } -} + console.log(`Client: ${name}`); + return `client-${name}`; + }; +}; + // Factory returning no-implementation isomorphic fn export function createNoImplFn() { - return createIsomorphicFn() + return createIsomorphicFn(); } + // Top-level isomorphic fn for comparison -export const topLevelIsomorphicFn = () => 'client' +export const topLevelIsomorphicFn = () => 'client'; \ No newline at end of file diff --git a/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnInline.tsx b/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnInline.tsx index 28930701bd..09666623a6 100644 --- a/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnInline.tsx +++ b/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnInline.tsx @@ -1,33 +1,41 @@ // Create and immediately invoke isomorphic fn inside a function export function getPlatformValue() { - const fn = () => 'client-value' - return fn() + const fn = () => 'client-value'; + return fn(); } + // Arrow function that creates and invokes isomorphic fn export const getEnvironment = () => { - const envFn = () => 'running on client' - return envFn() -} + const envFn = () => 'running on client'; + return envFn(); +}; + // Create isomorphic fn inline without assigning to variable export function getDirectValue() { - return (() => 'direct-client')() + 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() } + 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() + 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() -} + console.log('client side effect'); + return 'client-only-value'; + }; + return fn(); +} \ No newline at end of file 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 f8604d9723..070f59d901 100644 --- a/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnStarImport.tsx +++ b/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnStarImport.tsx @@ -1,13 +1,13 @@ -import * as TanStackStart from '@tanstack/react-start' -const noImpl = TanStackStart.createIsomorphicFn() -const serverOnlyFn = () => {} -const clientOnlyFn = () => 'client' -const serverThenClientFn = () => 'client' -const clientThenServerFn = () => 'client' -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 +const clientOnlyFnAbstracted = abstractedClientFn; +const serverThenClientFnAbstracted = abstractedClientFn; +const clientThenServerFnAbstracted = abstractedClientFn; \ No newline at end of file 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 index 66c327f562..2fa99b5686 100644 --- 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 @@ -1,5 +1,5 @@ const getEnvironment = () => { - console.log('[SERVER] getEnvironment called') - return 'server' -} -const moduleLevel = getEnvironment() + console.log('[SERVER] getEnvironment called'); + return 'server'; +}; +const moduleLevel = getEnvironment(); \ No newline at end of file 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 ee54120ca1..195cee12a6 100644 --- a/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnDestructured.tsx +++ b/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnDestructured.tsx @@ -1,13 +1,13 @@ -import { createIsomorphicFn } from '@tanstack/react-start' -const noImpl = createIsomorphicFn() -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 -const clientOnlyFnAbstracted = () => {} -const serverThenClientFnAbstracted = abstractedServerFn -const clientThenServerFnAbstracted = abstractedServerFn +const serverOnlyFnAbstracted = abstractedServerFn; +const clientOnlyFnAbstracted = () => {}; +const serverThenClientFnAbstracted = abstractedServerFn; +const clientThenServerFnAbstracted = abstractedServerFn; \ No newline at end of file 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 11289136e9..c50c274dd6 100644 --- a/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnDestructuredRename.tsx +++ b/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnDestructuredRename.tsx @@ -1,13 +1,13 @@ -import { createIsomorphicFn as isomorphicFn } from '@tanstack/react-start' -const noImpl = isomorphicFn() -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 -const clientOnlyFnAbstracted = () => {} -const serverThenClientFnAbstracted = abstractedServerFn -const clientThenServerFnAbstracted = abstractedServerFn +const serverOnlyFnAbstracted = abstractedServerFn; +const clientOnlyFnAbstracted = () => {}; +const serverThenClientFnAbstracted = abstractedServerFn; +const clientThenServerFnAbstracted = abstractedServerFn; \ No newline at end of file diff --git a/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnFactory.tsx b/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnFactory.tsx index c1ec1e79f5..cce206bc8b 100644 --- a/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnFactory.tsx +++ b/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnFactory.tsx @@ -1,22 +1,27 @@ -import { createIsomorphicFn } from '@tanstack/react-start' +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}` + return () => `server-${platform}`; } + // Arrow function factory with only server implementation export const createServerImplFn = (name: string) => { return () => { - console.log(`Server: ${name}`) - return `server-${name}` - } -} + console.log(`Server: ${name}`); + return `server-${name}`; + }; +}; + // Arrow function factory with only client implementation export const createClientImplFn = (name: string) => { - return () => {} -} + return () => {}; +}; + // Factory returning no-implementation isomorphic fn export function createNoImplFn() { - return createIsomorphicFn() + return createIsomorphicFn(); } + // Top-level isomorphic fn for comparison -export const topLevelIsomorphicFn = () => 'server' +export const topLevelIsomorphicFn = () => 'server'; \ No newline at end of file diff --git a/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnInline.tsx b/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnInline.tsx index c2b0d07284..9c058dfae8 100644 --- a/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnInline.tsx +++ b/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnInline.tsx @@ -1,33 +1,41 @@ // Create and immediately invoke isomorphic fn inside a function export function getPlatformValue() { - const fn = () => 'server-value' - return fn() + const fn = () => 'server-value'; + return fn(); } + // Arrow function that creates and invokes isomorphic fn export const getEnvironment = () => { - const envFn = () => 'running on server' - return envFn() -} + const envFn = () => 'running on server'; + return envFn(); +}; + // Create isomorphic fn inline without assigning to variable export function getDirectValue() { - return (() => 'direct-server')() + 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() } + 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() + 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() -} + const fn = () => {}; + return fn(); +} \ No newline at end of file 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 6a1c429167..65e4fc18b1 100644 --- a/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnStarImport.tsx +++ b/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnStarImport.tsx @@ -1,13 +1,13 @@ -import * as TanStackStart from '@tanstack/react-start' -const noImpl = TanStackStart.createIsomorphicFn() -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 -const clientOnlyFnAbstracted = () => {} -const serverThenClientFnAbstracted = abstractedServerFn -const clientThenServerFnAbstracted = abstractedServerFn +const serverOnlyFnAbstracted = abstractedServerFn; +const clientOnlyFnAbstracted = () => {}; +const serverThenClientFnAbstracted = abstractedServerFn; +const clientThenServerFnAbstracted = abstractedServerFn; \ No newline at end of file diff --git a/packages/start-plugin-core/tests/createMiddleware/createMiddleware.test.ts b/packages/start-plugin-core/tests/createMiddleware/createMiddleware.test.ts index 94af6ed65e..04e6d0d219 100644 --- a/packages/start-plugin-core/tests/createMiddleware/createMiddleware.test.ts +++ b/packages/start-plugin-core/tests/createMiddleware/createMiddleware.test.ts @@ -1,8 +1,7 @@ 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' +import { StartCompiler } from '../../src/start-compiler-plugin/compiler' // Default test options for StartCompiler function getDefaultTestOptions(env: 'client' | 'server') { @@ -43,7 +42,6 @@ async function compile(opts: { kind: 'Root', }, ], - getKnownServerFns: () => ({}), resolveId: async (id) => { return id }, @@ -68,35 +66,12 @@ describe('createMiddleware compiles correctly', async () => { 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}`) + await expect(result!.code).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' @@ -118,7 +93,6 @@ describe('createMiddleware compiles correctly', async () => { kind: 'Root', }, ], - getKnownServerFns: () => ({}), resolveId: resolveIdMock, }) @@ -127,9 +101,15 @@ describe('createMiddleware compiles correctly', async () => { id: 'test.ts', }) - // Direct known-library imports use the knownRootImports fast path, so they - // do not need resolveId. - expect(resolveIdMock).not.toHaveBeenCalled() + // resolveId should only be called once during init() for the library itself + // It should NOT be called again to resolve the import binding because + // the fast path uses knownRootImports map for O(1) lookup + // Note: init() now resolves from project root, not from a specific file + expect(resolveIdMock).toHaveBeenCalledTimes(1) + expect(resolveIdMock).toHaveBeenCalledWith( + '@tanstack/react-start', + undefined, + ) }) test('should use slow path for factory pattern (resolveId called for import resolution)', async () => { @@ -165,7 +145,6 @@ describe('createMiddleware compiles correctly', async () => { kind: 'Root', }, ], - getKnownServerFns: () => ({}), resolveId: resolveIdMock, }) @@ -174,122 +153,18 @@ describe('createMiddleware compiles correctly', async () => { id: 'test.ts', }) - // resolveId should only be called for './factory'. Direct known-library - // imports use the knownRootImports fast path. + // resolveId should be called exactly twice: + // 1. Once during init() for '@tanstack/react-start' (no importer - resolved from project root) + // 2. Once to resolve './factory' import (slow path - not in knownRootImports) // // 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') + expect(resolveIdMock).toHaveBeenCalledTimes(2) + expect(resolveIdMock).toHaveBeenNthCalledWith( + 1, + '@tanstack/react-start', + undefined, + ) + expect(resolveIdMock).toHaveBeenNthCalledWith(2, './factory', 'test.ts') }) }) 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 index 73d5910eef..b37e25e498 100644 --- 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 @@ -1,4 +1,6 @@ -import { createMiddleware } from '@tanstack/react-start' -export const fnMw = createMiddleware({ type: 'function' }).client(() => { - console.log('client') -}) +import { createMiddleware } from '@tanstack/react-start'; +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/snapshots/client/createMiddlewareDestructured.tsx b/packages/start-plugin-core/tests/createMiddleware/snapshots/client/createMiddlewareDestructured.tsx index c3497f072b..b5cf588a1f 100644 --- a/packages/start-plugin-core/tests/createMiddleware/snapshots/client/createMiddlewareDestructured.tsx +++ b/packages/start-plugin-core/tests/createMiddleware/snapshots/client/createMiddlewareDestructured.tsx @@ -1,5 +1,13 @@ -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' }) +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' +}); \ No newline at end of file diff --git a/packages/start-plugin-core/tests/createMiddleware/snapshots/client/createMiddlewareDestructuredRename.tsx b/packages/start-plugin-core/tests/createMiddleware/snapshots/client/createMiddlewareDestructuredRename.tsx index 70d3921bda..ee06179703 100644 --- a/packages/start-plugin-core/tests/createMiddleware/snapshots/client/createMiddlewareDestructuredRename.tsx +++ b/packages/start-plugin-core/tests/createMiddleware/snapshots/client/createMiddlewareDestructuredRename.tsx @@ -1,5 +1,13 @@ -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' }) +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' +}); \ No newline at end of file diff --git a/packages/start-plugin-core/tests/createMiddleware/snapshots/client/createMiddlewareStarImport.tsx b/packages/start-plugin-core/tests/createMiddleware/snapshots/client/createMiddlewareStarImport.tsx index f997f40fe0..6f2f40a2a3 100644 --- a/packages/start-plugin-core/tests/createMiddleware/snapshots/client/createMiddlewareStarImport.tsx +++ b/packages/start-plugin-core/tests/createMiddleware/snapshots/client/createMiddlewareStarImport.tsx @@ -1,5 +1,13 @@ -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' }) +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' +}); \ No newline at end of file diff --git a/packages/start-plugin-core/tests/createMiddleware/snapshots/client/createMiddlewareValidator.tsx b/packages/start-plugin-core/tests/createMiddleware/snapshots/client/createMiddlewareValidator.tsx index 773e990702..3b1beac2c0 100644 --- a/packages/start-plugin-core/tests/createMiddleware/snapshots/client/createMiddlewareValidator.tsx +++ b/packages/start-plugin-core/tests/createMiddleware/snapshots/client/createMiddlewareValidator.tsx @@ -1,2 +1,4 @@ -import { createMiddleware } from '@tanstack/react-start' -export const withUseServer = createMiddleware({ id: 'test' }) +import { createMiddleware } from '@tanstack/react-start'; +export const withUseServer = createMiddleware({ + id: 'test' +}); \ No newline at end of file diff --git a/packages/start-plugin-core/tests/createMiddleware/snapshots/client/createStart.tsx b/packages/start-plugin-core/tests/createMiddleware/snapshots/client/createStart.tsx index b2bde33436..8c3a7fc205 100644 --- a/packages/start-plugin-core/tests/createMiddleware/snapshots/client/createStart.tsx +++ b/packages/start-plugin-core/tests/createMiddleware/snapshots/client/createStart.tsx @@ -1,9 +1,13 @@ -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' }) +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/snapshots/client/middleware-factory.ts b/packages/start-plugin-core/tests/createMiddleware/snapshots/client/middleware-factory.ts index 0e51f2f369..6845bd0ef5 100644 --- a/packages/start-plugin-core/tests/createMiddleware/snapshots/client/middleware-factory.ts +++ b/packages/start-plugin-core/tests/createMiddleware/snapshots/client/middleware-factory.ts @@ -1,11 +1,20 @@ -import { createMiddleware } from '@tanstack/react-start' +import { createMiddleware } from '@tanstack/react-start'; + // Middleware factory function - returns a middleware with .server() call export function createPublicRateLimitMiddleware(keySuffix) { - return createMiddleware({ type: 'function' }) + return createMiddleware({ + type: 'function' + }); } + // Arrow function factory -export const createAuthMiddleware = (requiredRole) => { - return createMiddleware({ type: 'function' }) -} +export const createAuthMiddleware = requiredRole => { + return createMiddleware({ + type: 'function' + }); +}; + // Top-level middleware for comparison -export const topLevelMiddleware = createMiddleware({ id: 'topLevel' }) +export const topLevelMiddleware = createMiddleware({ + id: 'topLevel' +}); \ No newline at end of file diff --git a/packages/start-plugin-core/tests/createMiddleware/test-files/createMiddlewareValidator.tsx b/packages/start-plugin-core/tests/createMiddleware/test-files/createMiddlewareValidator.tsx index 894bf4608f..bed1406646 100644 --- a/packages/start-plugin-core/tests/createMiddleware/test-files/createMiddlewareValidator.tsx +++ b/packages/start-plugin-core/tests/createMiddleware/test-files/createMiddlewareValidator.tsx @@ -4,5 +4,5 @@ import { z } from 'zod' export const withUseServer = createMiddleware({ id: 'test', }) - .validator(z.number()) + .inputValidator(z.number()) .server(({ input }) => input + 1) 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 deleted file mode 100644 index 07c7a2f2cf..0000000000 --- a/packages/start-plugin-core/tests/createServerFn/caller-dead-code.test.ts +++ /dev/null @@ -1,591 +0,0 @@ -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 e80f292891..a99eed371f 100644 --- a/packages/start-plugin-core/tests/createServerFn/createServerFn.test.ts +++ b/packages/start-plugin-core/tests/createServerFn/createServerFn.test.ts @@ -1,9 +1,7 @@ import { readFile, readdir } from 'node:fs/promises' import path from 'node:path' -import { stripVTControlCharacters } from 'node:util' import { describe, expect, test, vi } from 'vitest' -import { StartCompiler } from '../../src/start-compiler/compiler' -import { formatSnapshot } from '../format-snapshot' +import { StartCompiler } from '../../src/start-compiler-plugin/compiler' // Default test options for StartCompiler function getDefaultTestOptions(env: 'client' | 'server') { @@ -25,9 +23,7 @@ const TSS_SERVERFN_SPLIT_PARAM = 'tss-serverfn-split' async function compile(opts: { env: 'client' | 'server' code: string - parserFilename?: string isProviderFile: boolean - mode: 'dev' | 'build' }) { // Use an absolute path inside the test root to ensure consistent filename output let id = '/test/src/test.ts' @@ -50,7 +46,6 @@ async function compile(opts: { kind: 'Root', }, ], - getKnownServerFns: () => ({}), resolveId: async (id) => { return id }, @@ -58,7 +53,6 @@ async function compile(opts: { const result = await compiler.compile({ code: opts.code, id, - parserFilename: opts.parserFilename, }) return result } @@ -81,8 +75,6 @@ describe('createServerFn compiles correctly', async () => { env: env.type, isProviderFile: env.isProviderFile, code, - parserFilename: `/test/src/${filename}`, - mode: 'build', }) const folder = @@ -91,66 +83,11 @@ describe('createServerFn compiles correctly', async () => { : 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\(\)/, + await expect(result!.code).toMatchFileSnapshot( + `./snapshots/${folder}/${filename}`, ) - }, - ) + }) + }) test('should work with identifiers of functions', async () => { const code = ` @@ -164,7 +101,6 @@ describe('createServerFn compiles correctly', async () => { code, env: 'client', isProviderFile: false, - mode: 'build', }) // Server caller (route file - no split param) @@ -173,7 +109,6 @@ describe('createServerFn compiles correctly', async () => { code, env: 'server', isProviderFile: false, - mode: 'build', }) // Server provider (extracted file - has split param) @@ -182,154 +117,36 @@ describe('createServerFn compiles correctly', async () => { code, env: 'server', isProviderFile: true, - 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', - ), - ) - " - `) + expect(compiledResultClient!.code).toMatchInlineSnapshot(` + "import { createClientRpc } from '@tanstack/react-start/client-rpc'; + import { createServerFn } from '@tanstack/react-start'; + const myServerFn = createServerFn().handler(createClientRpc("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJteVNlcnZlckZuX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ"));" + `) // 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', - ), - ) - " - `) + expect(compiledResultServerCaller!.code).toMatchInlineSnapshot(` + "import { createSsrRpc } from '@tanstack/react-start/ssr-rpc'; + import { createServerFn } from '@tanstack/react-start'; + const myServerFn = createServerFn().handler(createSsrRpc("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJteVNlcnZlckZuX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ", () => import("/test/src/test.ts?tss-serverfn-split").then(m => m["myServerFn_createServerFn_handler"])));" + `) // 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') + expect(compiledResultServerProvider!.code).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: "eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJteVNlcnZlckZuX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ", + name: "myServerFn", + filename: "src/test.ts" + }, opts => myServerFn.__executeServer(opts)); + const myServerFn = createServerFn().handler(myServerFn_createServerFn_handler, myFunc); + export { myServerFn_createServerFn_handler };" + `) }) test('should use dce by default', async () => { @@ -349,99 +166,59 @@ describe('createServerFn compiles correctly', async () => { 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 exportedFn = createServerFn().handler( - createClientRpc( - 'c306c96e9256c7604f2a6022c4c94eb89f863274c022bc45b03970f067ea9864', - ), - ) - const nonExportedFn = createServerFn().handler( - createClientRpc( - 'f4403dc0b18e216dfe0a9711cab028bc1b9768175daa9236d7115e29c99d76c2', - ), - ) - " - `) + expect(compiledResult!.code).toMatchInlineSnapshot(` + "import { createClientRpc } from '@tanstack/react-start/client-rpc'; + import { createServerFn } from '@tanstack/react-start'; + export const exportedFn = createServerFn().handler(createClientRpc("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJleHBvcnRlZEZuX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ")); + const nonExportedFn = createServerFn().handler(createClientRpc("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJub25FeHBvcnRlZEZuX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ"));" + `) // Server caller (route file) - no second argument const compiledResultServerCaller = await compile({ code, env: 'server', isProviderFile: false, - mode: 'build', }) - 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', - ), - ) - " - `) + expect(compiledResultServerCaller!.code).toMatchInlineSnapshot(` + "import { createSsrRpc } from '@tanstack/react-start/ssr-rpc'; + import { createServerFn } from '@tanstack/react-start'; + export const exportedFn = createServerFn().handler(createSsrRpc("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJleHBvcnRlZEZuX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ", () => import("/test/src/test.ts?tss-serverfn-split").then(m => m["exportedFn_createServerFn_handler"]))); + const nonExportedFn = createServerFn().handler(createSsrRpc("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJub25FeHBvcnRlZEZuX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ", () => import("/test/src/test.ts?tss-serverfn-split").then(m => m["nonExportedFn_createServerFn_handler"])));" + `) // Server provider (extracted file) - has second argument const compiledResultServerProvider = await compile({ code, env: 'server', isProviderFile: true, - mode: 'build', }) - 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, - } - " - `) + expect(compiledResultServerProvider!.code).toMatchInlineSnapshot(` + "import { createServerRpc } from '@tanstack/react-start/server-rpc'; + import { createServerFn } from '@tanstack/react-start'; + const exportedVar = 'exported'; + const exportedFn_createServerFn_handler = createServerRpc({ + id: "eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJleHBvcnRlZEZuX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ", + 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: "eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJub25FeHBvcnRlZEZuX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ", + 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 () => { @@ -465,9 +242,7 @@ describe('createServerFn compiles correctly', async () => { kind: 'Root', }, ], - getKnownServerFns: () => ({}), resolveId: resolveIdMock, - mode: 'build', }) await compiler.compile({ @@ -475,9 +250,14 @@ describe('createServerFn compiles correctly', async () => { id: '/test/src/test.ts', }) - // Direct known-library imports use the knownRootImports fast path, so they - // do not need resolveId. - expect(resolveIdMock).not.toHaveBeenCalled() + // resolveId should only be called once during init() for the library itself + // It should NOT be called again to resolve the import binding because + // the fast path uses knownRootImports map for O(1) lookup + expect(resolveIdMock).toHaveBeenCalledTimes(1) + expect(resolveIdMock).toHaveBeenCalledWith( + '@tanstack/react-start', + undefined, + ) }) test('should use slow path for factory pattern (resolveId called for import resolution)', async () => { @@ -513,9 +293,7 @@ describe('createServerFn compiles correctly', async () => { kind: 'Root', }, ], - getKnownServerFns: () => ({}), resolveId: resolveIdMock, - mode: 'build', }) await compiler.compile({ @@ -523,379 +301,22 @@ describe('createServerFn compiles correctly', async () => { id: '/test/src/test.ts', }) - // resolveId should only be called for './factory'. Direct known-library - // imports use the knownRootImports fast path. + // resolveId should be called exactly twice: + // 1. Once during init() for '@tanstack/react-start' + // 2. Once to resolve './factory' import (slow path - not in knownRootImports) // // 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', + '@tanstack/react-start', + undefined, ) expect(resolveIdMock).toHaveBeenNthCalledWith( 2, - './factory-inner', './factory', + '/test/src/test.ts', ) }) - - 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 deleted file mode 100644 index f42a13cdba..0000000000 --- a/packages/start-plugin-core/tests/createServerFn/declaration-sites.test.ts +++ /dev/null @@ -1,122 +0,0 @@ -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 deleted file mode 100644 index 7f16dd2cc7..0000000000 --- a/packages/start-plugin-core/tests/createServerFn/exports-and-directives.test.ts +++ /dev/null @@ -1,421 +0,0 @@ -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 deleted file mode 100644 index 2f94d1b465..0000000000 --- a/packages/start-plugin-core/tests/createServerFn/handler-scope.test.ts +++ /dev/null @@ -1,363 +0,0 @@ -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 88e8607da2..51f40ea4f7 100644 --- a/packages/start-plugin-core/tests/createServerFn/snapshots/client/createServerFnDestructured.tsx +++ b/packages/start-plugin-core/tests/createServerFn/snapshots/client/createServerFnDestructured.tsx @@ -1,39 +1,23 @@ -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', - ), -) +import { createClientRpc } from '@tanstack/react-start/client-rpc'; +import { createServerFn } from '@tanstack/react-start'; +export const withUseServer = createServerFn({ + method: 'GET' +}).handler(createClientRpc("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRoVXNlU2VydmVyX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ")); +export const withArrowFunction = createServerFn({ + method: 'GET' +}).handler(createClientRpc("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRoQXJyb3dGdW5jdGlvbl9jcmVhdGVTZXJ2ZXJGbl9oYW5kbGVyIn0")); export const withArrowFunctionAndFunction = createServerFn({ - 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', - ), -) + method: 'GET' +}).handler(createClientRpc("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRoQXJyb3dGdW5jdGlvbkFuZEZ1bmN0aW9uX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ")); +export const withoutUseServer = createServerFn({ + method: 'GET' +}).handler(createClientRpc("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRob3V0VXNlU2VydmVyX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ")); +export const withVariable = createServerFn({ + method: 'GET' +}).handler(createClientRpc("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRoVmFyaWFibGVfY3JlYXRlU2VydmVyRm5faGFuZGxlciJ9")); +export const withZodValidator = createServerFn({ + method: 'GET' +}).handler(createClientRpc("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRoWm9kVmFsaWRhdG9yX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ")); +export const withValidatorFn = createServerFn({ + method: 'GET' +}).handler(createClientRpc("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRoVmFsaWRhdG9yRm5fY3JlYXRlU2VydmVyRm5faGFuZGxlciJ9")); \ No newline at end of file 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 34e0c452b6..2d2dfaf15a 100644 --- a/packages/start-plugin-core/tests/createServerFn/snapshots/client/createServerFnDestructuredRename.tsx +++ b/packages/start-plugin-core/tests/createServerFn/snapshots/client/createServerFnDestructuredRename.tsx @@ -1,22 +1,14 @@ -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', - ), -) +import { createClientRpc } from '@tanstack/react-start/client-rpc'; +import { createServerFn as serverFn } from '@tanstack/react-start'; +export const withUseServer = serverFn({ + method: 'GET' +}).handler(createClientRpc("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRoVXNlU2VydmVyX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ")); +export const withoutUseServer = serverFn({ + method: 'GET' +}).handler(createClientRpc("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRob3V0VXNlU2VydmVyX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ")); +export const withVariable = serverFn({ + method: 'GET' +}).handler(createClientRpc("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRoVmFyaWFibGVfY3JlYXRlU2VydmVyRm5faGFuZGxlciJ9")); +export const withZodValidator = serverFn({ + method: 'GET' +}).handler(createClientRpc("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRoWm9kVmFsaWRhdG9yX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ")); \ No newline at end of file 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 2cea070645..16a447fa01 100644 --- a/packages/start-plugin-core/tests/createServerFn/snapshots/client/createServerFnStarImport.tsx +++ b/packages/start-plugin-core/tests/createServerFn/snapshots/client/createServerFnStarImport.tsx @@ -1,30 +1,14 @@ -import { createClientRpc } from '@tanstack/react-start/client-rpc' -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( - createClientRpc( - 'b6fe31e85836ae6c65d8ab262dd1af6a68620aeef609029d50127f4cceaaf320', - ), -) + method: 'GET' +}).handler(createClientRpc("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRoVXNlU2VydmVyX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ")); export const withoutUseServer = TanStackStart.createServerFn({ - method: 'GET', -}).handler( - createClientRpc( - 'c0d9fdeb2b01aafecc782f439416b86f666cb5334ac9a934546b177e5698bbb2', - ), -) + method: 'GET' +}).handler(createClientRpc("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRob3V0VXNlU2VydmVyX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ")); export const withVariable = TanStackStart.createServerFn({ - method: 'GET', -}).handler( - createClientRpc( - '7d36cb30c30bd688b9773bd7f85a0d51d83f868255e127605e4f236615fefe70', - ), -) + method: 'GET' +}).handler(createClientRpc("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRoVmFyaWFibGVfY3JlYXRlU2VydmVyRm5faGFuZGxlciJ9")); export const withZodValidator = TanStackStart.createServerFn({ - method: 'GET', -}).handler( - createClientRpc( - '43606a369c85444a332f701d6399564b6a3691aabab63dfc9a0b7c341fb798f3', - ), -) + method: 'GET' +}).handler(createClientRpc("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRoWm9kVmFsaWRhdG9yX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ")); \ No newline at end of file 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 97253672a6..5e1b05659e 100644 --- a/packages/start-plugin-core/tests/createServerFn/snapshots/client/createServerFnValidator.tsx +++ b/packages/start-plugin-core/tests/createServerFn/snapshots/client/createServerFnValidator.tsx @@ -1,7 +1,5 @@ -import { createClientRpc } from '@tanstack/react-start/client-rpc' -import { createServerFn } from '@tanstack/react-start' -export const withUseServer = createServerFn({ method: 'GET' }).handler( - createClientRpc( - 'b6fe31e85836ae6c65d8ab262dd1af6a68620aeef609029d50127f4cceaaf320', - ), -) +import { createClientRpc } from '@tanstack/react-start/client-rpc'; +import { createServerFn } from '@tanstack/react-start'; +export const withUseServer = createServerFn({ + method: 'GET' +}).handler(createClientRpc("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRoVXNlU2VydmVyX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ")); \ No newline at end of file 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 889c1fbf4e..ded08d457c 100644 --- a/packages/start-plugin-core/tests/createServerFn/snapshots/client/factory.tsx +++ b/packages/start-plugin-core/tests/createServerFn/snapshots/client/factory.tsx @@ -1,34 +1,38 @@ -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', - ), -) +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("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJteUF1dGhlZEZuX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ")); +export const deleteUserFn = createAdminServerFn().handler(createClientRpc("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJkZWxldGVVc2VyRm5fY3JlYXRlU2VydmVyRm5faGFuZGxlciJ9")); function createFakeFn() { return { - handler: (cb) => { - return cb() - }, - } + handler: cb => { + return cb(); + } + }; } const x = createFakeFn().handler(() => { - return 'fakeFn' -}) + return 'fakeFn'; +}); \ No newline at end of file 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 8e09a57d37..0a013b8db1 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,49 +1,48 @@ -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', - ), -) +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("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJnZXRTZXJ2ZXJFbnZfY3JlYXRlU2VydmVyRm5faGFuZGxlciJ9")); +const getEcho = createIsomorphicFn().server((input: string) => 'server received ' + input).client(input => 'client received ' + input); +const getServerEcho = createServerFn().handler(createClientRpc("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJnZXRTZXJ2ZXJFY2hvX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ")); 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 }) + return { + envOnLoad: getEnv() + }; } - const { envOnClick, echo, serverEnv, serverEcho } = results || {} - return ( -
+}); +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 && ( -
+ {!!results &&

getEnv

@@ -63,8 +62,6 @@ 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 index efa8f395d5..b8dbdcaae5 100644 --- a/packages/start-plugin-core/tests/createServerFn/snapshots/server-caller/createServerFnDestructured.tsx +++ b/packages/start-plugin-core/tests/createServerFn/snapshots/server-caller/createServerFnDestructured.tsx @@ -1,42 +1,24 @@ -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', - ), -) +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("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRoVXNlU2VydmVyX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ", () => import("/test/src/test.ts?tss-serverfn-split").then(m => m["withUseServer_createServerFn_handler"]))); +export const withArrowFunction = createServerFn({ + method: 'GET' +}).handler(createSsrRpc("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRoQXJyb3dGdW5jdGlvbl9jcmVhdGVTZXJ2ZXJGbl9oYW5kbGVyIn0", () => import("/test/src/test.ts?tss-serverfn-split").then(m => m["withArrowFunction_createServerFn_handler"]))); 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', - ), - ) + method: 'GET' +}).handler(createSsrRpc("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRoQXJyb3dGdW5jdGlvbkFuZEZ1bmN0aW9uX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ", () => import("/test/src/test.ts?tss-serverfn-split").then(m => m["withArrowFunctionAndFunction_createServerFn_handler"]))); +export const withoutUseServer = createServerFn({ + method: 'GET' +}).handler(createSsrRpc("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRob3V0VXNlU2VydmVyX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ", () => import("/test/src/test.ts?tss-serverfn-split").then(m => m["withoutUseServer_createServerFn_handler"]))); +export const withVariable = createServerFn({ + method: 'GET' +}).handler(createSsrRpc("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRoVmFyaWFibGVfY3JlYXRlU2VydmVyRm5faGFuZGxlciJ9", () => import("/test/src/test.ts?tss-serverfn-split").then(m => m["withVariable_createServerFn_handler"]))); +export const withZodValidator = createServerFn({ + method: 'GET' +}).handler(createSsrRpc("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRoWm9kVmFsaWRhdG9yX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ", () => import("/test/src/test.ts?tss-serverfn-split").then(m => m["withZodValidator_createServerFn_handler"]))); +export const withValidatorFn = createServerFn({ + method: 'GET' +}).inputValidator(z.number()).handler(createSsrRpc("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRoVmFsaWRhdG9yRm5fY3JlYXRlU2VydmVyRm5faGFuZGxlciJ9", () => import("/test/src/test.ts?tss-serverfn-split").then(m => m["withValidatorFn_createServerFn_handler"]))); \ No newline at end of file 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 index 7088a4bc69..815702d5d8 100644 --- a/packages/start-plugin-core/tests/createServerFn/snapshots/server-caller/createServerFnDestructuredRename.tsx +++ b/packages/start-plugin-core/tests/createServerFn/snapshots/server-caller/createServerFnDestructuredRename.tsx @@ -1,22 +1,14 @@ -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', - ), -) +import { createSsrRpc } from '@tanstack/react-start/ssr-rpc'; +import { createServerFn as serverFn } from '@tanstack/react-start'; +export const withUseServer = serverFn({ + method: 'GET' +}).handler(createSsrRpc("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRoVXNlU2VydmVyX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ", () => import("/test/src/test.ts?tss-serverfn-split").then(m => m["withUseServer_createServerFn_handler"]))); +export const withoutUseServer = serverFn({ + method: 'GET' +}).handler(createSsrRpc("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRob3V0VXNlU2VydmVyX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ", () => import("/test/src/test.ts?tss-serverfn-split").then(m => m["withoutUseServer_createServerFn_handler"]))); +export const withVariable = serverFn({ + method: 'GET' +}).handler(createSsrRpc("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRoVmFyaWFibGVfY3JlYXRlU2VydmVyRm5faGFuZGxlciJ9", () => import("/test/src/test.ts?tss-serverfn-split").then(m => m["withVariable_createServerFn_handler"]))); +export const withZodValidator = serverFn({ + method: 'GET' +}).handler(createSsrRpc("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRoWm9kVmFsaWRhdG9yX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ", () => import("/test/src/test.ts?tss-serverfn-split").then(m => m["withZodValidator_createServerFn_handler"]))); \ No newline at end of file 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 index 899aaf3d0d..2f68c8c276 100644 --- a/packages/start-plugin-core/tests/createServerFn/snapshots/server-caller/createServerFnStarImport.tsx +++ b/packages/start-plugin-core/tests/createServerFn/snapshots/server-caller/createServerFnStarImport.tsx @@ -1,30 +1,14 @@ -import { createSsrRpc } from '@tanstack/react-start/ssr-rpc' -import * as TanStackStart from '@tanstack/react-start' +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', - ), -) + method: 'GET' +}).handler(createSsrRpc("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRoVXNlU2VydmVyX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ", () => import("/test/src/test.ts?tss-serverfn-split").then(m => m["withUseServer_createServerFn_handler"]))); export const withoutUseServer = TanStackStart.createServerFn({ - method: 'GET', -}).handler( - createSsrRpc( - 'c0d9fdeb2b01aafecc782f439416b86f666cb5334ac9a934546b177e5698bbb2', - ), -) + method: 'GET' +}).handler(createSsrRpc("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRob3V0VXNlU2VydmVyX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ", () => import("/test/src/test.ts?tss-serverfn-split").then(m => m["withoutUseServer_createServerFn_handler"]))); export const withVariable = TanStackStart.createServerFn({ - method: 'GET', -}).handler( - createSsrRpc( - '7d36cb30c30bd688b9773bd7f85a0d51d83f868255e127605e4f236615fefe70', - ), -) + method: 'GET' +}).handler(createSsrRpc("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRoVmFyaWFibGVfY3JlYXRlU2VydmVyRm5faGFuZGxlciJ9", () => import("/test/src/test.ts?tss-serverfn-split").then(m => m["withVariable_createServerFn_handler"]))); export const withZodValidator = TanStackStart.createServerFn({ - method: 'GET', -}).handler( - createSsrRpc( - '43606a369c85444a332f701d6399564b6a3691aabab63dfc9a0b7c341fb798f3', - ), -) + method: 'GET' +}).handler(createSsrRpc("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRoWm9kVmFsaWRhdG9yX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ", () => import("/test/src/test.ts?tss-serverfn-split").then(m => m["withZodValidator_createServerFn_handler"]))); \ No newline at end of file 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 index e1d136311b..ba0b4b577e 100644 --- a/packages/start-plugin-core/tests/createServerFn/snapshots/server-caller/createServerFnValidator.tsx +++ b/packages/start-plugin-core/tests/createServerFn/snapshots/server-caller/createServerFnValidator.tsx @@ -1,10 +1,6 @@ -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', - ), - ) +import { createSsrRpc } from '@tanstack/react-start/ssr-rpc'; +import { createServerFn } from '@tanstack/react-start'; +import { z } from 'zod'; +export const withUseServer = createServerFn({ + method: 'GET' +}).inputValidator(z.number()).handler(createSsrRpc("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRoVXNlU2VydmVyX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ", () => import("/test/src/test.ts?tss-serverfn-split").then(m => m["withUseServer_createServerFn_handler"]))); \ No newline at end of file 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 index ab19c3e1f8..dbc4e764d9 100644 --- a/packages/start-plugin-core/tests/createServerFn/snapshots/server-caller/factory.tsx +++ b/packages/start-plugin-core/tests/createServerFn/snapshots/server-caller/factory.tsx @@ -1,34 +1,38 @@ -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', - ), -) +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("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJteUF1dGhlZEZuX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ", () => import("/test/src/test.ts?tss-serverfn-split").then(m => m["myAuthedFn_createServerFn_handler"]))); +export const deleteUserFn = createAdminServerFn().handler(createSsrRpc("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJkZWxldGVVc2VyRm5fY3JlYXRlU2VydmVyRm5faGFuZGxlciJ9", () => import("/test/src/test.ts?tss-serverfn-split").then(m => m["deleteUserFn_createServerFn_handler"]))); function createFakeFn() { return { - handler: (cb) => { - return cb() - }, - } + handler: cb => { + return cb(); + } + }; } const x = createFakeFn().handler(() => { - return 'fakeFn' -}) + return 'fakeFn'; +}); \ No newline at end of file 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 index cfefad2bfb..02675e9e95 100644 --- 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 @@ -1,51 +1,48 @@ -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', - ), - ) +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("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJnZXRTZXJ2ZXJFbnZfY3JlYXRlU2VydmVyRm5faGFuZGxlciJ9", () => import("/test/src/test.ts?tss-serverfn-split").then(m => m["getServerEnv_createServerFn_handler"]))); +const getEcho = createIsomorphicFn().server((input: string) => 'server received ' + input).client(input => 'client received ' + input); +const getServerEcho = createServerFn().inputValidator((input: string) => input).handler(createSsrRpc("eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJnZXRTZXJ2ZXJFY2hvX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ", () => import("/test/src/test.ts?tss-serverfn-split").then(m => m["getServerEcho_createServerFn_handler"]))); 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 }) + return { + envOnLoad: getEnv() + }; } - const { envOnClick, echo, serverEnv, serverEcho } = results || {} - return ( -
+}); +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 && ( -
+ {!!results &&

getEnv

@@ -65,8 +62,6 @@ 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-provider/createServerFnDestructured.tsx b/packages/start-plugin-core/tests/createServerFn/snapshots/server-provider/createServerFnDestructured.tsx index 3bc4879c14..113c86dc5c 100644 --- a/packages/start-plugin-core/tests/createServerFn/snapshots/server-provider/createServerFnDestructured.tsx +++ b/packages/start-plugin-core/tests/createServerFn/snapshots/server-provider/createServerFnDestructured.tsx @@ -1,126 +1,86 @@ -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, -) +import { createServerRpc } from '@tanstack/react-start/server-rpc'; +import { createServerFn } from '@tanstack/react-start'; +import { z } from 'zod'; +const withUseServer_createServerFn_handler = createServerRpc({ + id: "eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRoVXNlU2VydmVyX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ", + 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: "eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRoQXJyb3dGdW5jdGlvbl9jcmVhdGVTZXJ2ZXJGbl9oYW5kbGVyIn0", + 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: "eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRoQXJyb3dGdW5jdGlvbkFuZEZ1bmN0aW9uX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ", + 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: "eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRob3V0VXNlU2VydmVyX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ", + 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: "eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRoVmFyaWFibGVfY3JlYXRlU2VydmVyRm5faGFuZGxlciJ9", + 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)) + 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, -) { +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, + return fn(schema.parse(input)); + }; } +const withZodValidator_createServerFn_handler = createServerRpc({ + id: "eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRoWm9kVmFsaWRhdG9yX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ", + 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: "eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRoVmFsaWRhdG9yRm5fY3JlYXRlU2VydmVyRm5faGFuZGxlciJ9", + name: "withValidatorFn", + filename: "src/test.ts" +}, opts => withValidatorFn.__executeServer(opts)); +const withValidatorFn = createServerFn({ + method: 'GET' +}).inputValidator(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 }; \ No newline at end of file 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 index 775c32b645..69acc54cca 100644 --- a/packages/start-plugin-core/tests/createServerFn/snapshots/server-provider/createServerFnDestructuredRename.tsx +++ b/packages/start-plugin-core/tests/createServerFn/snapshots/server-provider/createServerFnDestructuredRename.tsx @@ -1,86 +1,58 @@ -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, -) +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: "eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRoVXNlU2VydmVyX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ", + 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: "eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRob3V0VXNlU2VydmVyX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ", + 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: "eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRoVmFyaWFibGVfY3JlYXRlU2VydmVyRm5faGFuZGxlciJ9", + 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)) + 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, -) { +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, + return fn(schema.parse(input)); + }; } +const withZodValidator_createServerFn_handler = createServerRpc({ + id: "eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRoWm9kVmFsaWRhdG9yX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ", + 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 }; \ No newline at end of file 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 index bc18c08855..b404a17c72 100644 --- a/packages/start-plugin-core/tests/createServerFn/snapshots/server-provider/createServerFnStarImport.tsx +++ b/packages/start-plugin-core/tests/createServerFn/snapshots/server-provider/createServerFnStarImport.tsx @@ -1,88 +1,60 @@ -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), -) +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: "eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRoVXNlU2VydmVyX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ", + 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: "eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRob3V0VXNlU2VydmVyX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ", + name: "withoutUseServer", + filename: "src/test.ts" +}, opts => withoutUseServer.__executeServer(opts)); const withoutUseServer = TanStackStart.createServerFn({ - method: 'GET', + 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, -) + 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: "eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRoVmFyaWFibGVfY3JlYXRlU2VydmVyRm5faGFuZGxlciJ9", + 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)) + 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, -) { +function zodValidator(schema: TSchema, fn: (input: z.output) => TResult) { return async (input: unknown) => { - return fn(schema.parse(input)) - } + 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_handler = createServerRpc({ + id: "eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRoWm9kVmFsaWRhdG9yX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ", + 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, -} + 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 }; \ No newline at end of file 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 index f62fa718d6..4cd2ee74f2 100644 --- a/packages/start-plugin-core/tests/createServerFn/snapshots/server-provider/createServerFnValidator.tsx +++ b/packages/start-plugin-core/tests/createServerFn/snapshots/server-provider/createServerFnValidator.tsx @@ -1,15 +1,14 @@ -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 } +import { createServerRpc } from '@tanstack/react-start/server-rpc'; +import { createServerFn } from '@tanstack/react-start'; +import { z } from 'zod'; +const withUseServer_createServerFn_handler = createServerRpc({ + id: "eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJ3aXRoVXNlU2VydmVyX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ", + name: "withUseServer", + filename: "src/test.ts" +}, opts => withUseServer.__executeServer(opts)); +const withUseServer = createServerFn({ + method: 'GET' +}).inputValidator(z.number()).handler(withUseServer_createServerFn_handler, ({ + input +}) => input + 1); +export { withUseServer_createServerFn_handler }; \ No newline at end of file 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 index 26298edd56..6041459061 100644 --- a/packages/start-plugin-core/tests/createServerFn/snapshots/server-provider/factory.tsx +++ b/packages/start-plugin-core/tests/createServerFn/snapshots/server-provider/factory.tsx @@ -1,56 +1,53 @@ -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' - }, -) +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: "eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJteUF1dGhlZEZuX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ", + 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: "eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJkZWxldGVVc2VyRm5fY3JlYXRlU2VydmVyRm5faGFuZGxlciJ9", + 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() - }, - } + handler: cb => { + return cb(); + } + }; } const x = createFakeFn().handler(() => { - return 'fakeFn' -}) -export { - myAuthedFn_createServerFn_handler, - deleteUserFn_createServerFn_handler, -} + return 'fakeFn'; +}); +export { myAuthedFn_createServerFn_handler, deleteUserFn_createServerFn_handler }; \ No newline at end of file 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 index 3ae8622683..6ea0f20711 100644 --- 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 @@ -1,35 +1,19 @@ -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, -} +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: "eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJnZXRTZXJ2ZXJFbnZfY3JlYXRlU2VydmVyRm5faGFuZGxlciJ9", + 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: "eyJmaWxlIjoiL0BpZC9zcmMvdGVzdC50cz90c3Mtc2VydmVyZm4tc3BsaXQiLCJleHBvcnQiOiJnZXRTZXJ2ZXJFY2hvX2NyZWF0ZVNlcnZlckZuX2hhbmRsZXIifQ", + name: "getServerEcho", + filename: "src/test.ts" +}, opts => getServerEcho.__executeServer(opts)); +const getServerEcho = createServerFn().inputValidator((input: string) => input).handler(getServerEcho_createServerFn_handler, ({ + data +}) => getEcho(data)); +export { getServerEnv_createServerFn_handler, getServerEcho_createServerFn_handler }; \ 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 b1c5e9edf2..c0b78ded9e 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', }) - .validator(z.number()) + .inputValidator(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 6c0eda77f3..80cb70fddb 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', }) - .validator(z.number()) + .inputValidator(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 2c7bbc4a8f..773a2e5329 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() - .validator((input: string) => input) + .inputValidator((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 deleted file mode 100644 index bca42afd36..0000000000 --- a/packages/start-plugin-core/tests/createVirtualModule.test.ts +++ /dev/null @@ -1,38 +0,0 @@ -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 deleted file mode 100644 index abe28087d0..0000000000 --- a/packages/start-plugin-core/tests/csrf-warning-config.test.ts +++ /dev/null @@ -1,65 +0,0 @@ -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 deleted file mode 100644 index b8a71675a1..0000000000 --- a/packages/start-plugin-core/tests/entry-planning.test.ts +++ /dev/null @@ -1,116 +0,0 @@ -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 4c18f2da81..67650b83e8 100644 --- a/packages/start-plugin-core/tests/envOnly/envOnly.test.ts +++ b/packages/start-plugin-core/tests/envOnly/envOnly.test.ts @@ -2,8 +2,7 @@ import { readFile, readdir } from 'node:fs/promises' import path from 'node:path' import { describe, expect, test } from 'vitest' -import { StartCompiler } from '../../src/start-compiler/compiler' -import { formatSnapshot } from '../format-snapshot' +import { StartCompiler } from '../../src/start-compiler-plugin/compiler' // Default test options for StartCompiler function getDefaultTestOptions(env: 'client' | 'server') { @@ -40,7 +39,6 @@ async function compile(opts: { kind: 'ClientOnlyFn', }, ], - getKnownServerFns: () => ({}), resolveId: async (id) => { return id }, @@ -74,9 +72,9 @@ describe('envOnly functions compile correctly', async () => { id: filename, }) - await expect( - await formatSnapshot(compiledResult!.code, filename), - ).toMatchFileSnapshot(`./snapshots/${env}/${filename}`) + await expect(compiledResult!.code).toMatchFileSnapshot( + `./snapshots/${env}/${filename}`, + ) }, ) }) 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 8c97577305..d56ad1f374 100644 --- a/packages/start-plugin-core/tests/envOnly/snapshots/client/envOnlyDestructured.tsx +++ b/packages/start-plugin-core/tests/envOnly/snapshots/client/envOnlyDestructured.tsx @@ -1,6 +1,4 @@ const serverFunc = () => { - throw new Error( - 'createServerOnlyFn() functions can only be called on the server!', - ) -} -const clientFunc = () => 'client' + throw new Error("createServerOnlyFn() functions can only be called on the server!"); +}; +const clientFunc = () => 'client'; \ No newline at end of file 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 8c97577305..d56ad1f374 100644 --- a/packages/start-plugin-core/tests/envOnly/snapshots/client/envOnlyDestructuredRename.tsx +++ b/packages/start-plugin-core/tests/envOnly/snapshots/client/envOnlyDestructuredRename.tsx @@ -1,6 +1,4 @@ const serverFunc = () => { - throw new Error( - 'createServerOnlyFn() functions can only be called on the server!', - ) -} -const clientFunc = () => 'client' + throw new Error("createServerOnlyFn() functions can only be called on the server!"); +}; +const clientFunc = () => 'client'; \ No newline at end of file diff --git a/packages/start-plugin-core/tests/envOnly/snapshots/client/envOnlyExportedAlias.tsx b/packages/start-plugin-core/tests/envOnly/snapshots/client/envOnlyExportedAlias.tsx deleted file mode 100644 index cad8d612c9..0000000000 --- a/packages/start-plugin-core/tests/envOnly/snapshots/client/envOnlyExportedAlias.tsx +++ /dev/null @@ -1,10 +0,0 @@ -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 index b226e30116..6a29fcbfe6 100644 --- a/packages/start-plugin-core/tests/envOnly/snapshots/client/envOnlyFactory.tsx +++ b/packages/start-plugin-core/tests/envOnly/snapshots/client/envOnlyFactory.tsx @@ -1,34 +1,32 @@ // Server-only function factory export function createServerFactory(name: string) { return () => { - throw new Error( - 'createServerOnlyFn() functions can only be called on the server!', - ) - } + 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}` - } + 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!', - ) - } -} + throw new Error("createServerOnlyFn() functions can only be called on the server!"); + }; +}; + // Arrow function client factory export const createClientArrowFactory = (prefix: string) => { - return () => `${prefix}-client` -} + 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' + throw new Error("createServerOnlyFn() functions can only be called on the server!"); +}; +export const topLevelClientFn = () => 'client'; \ No newline at end of file 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 8c97577305..d56ad1f374 100644 --- a/packages/start-plugin-core/tests/envOnly/snapshots/client/envOnlyStarImport.tsx +++ b/packages/start-plugin-core/tests/envOnly/snapshots/client/envOnlyStarImport.tsx @@ -1,6 +1,4 @@ const serverFunc = () => { - throw new Error( - 'createServerOnlyFn() functions can only be called on the server!', - ) -} -const clientFunc = () => 'client' + throw new Error("createServerOnlyFn() functions can only be called on the server!"); +}; +const clientFunc = () => 'client'; \ No newline at end of file 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 924d8d2442..5373578295 100644 --- a/packages/start-plugin-core/tests/envOnly/snapshots/server/envOnlyDestructured.tsx +++ b/packages/start-plugin-core/tests/envOnly/snapshots/server/envOnlyDestructured.tsx @@ -1,6 +1,4 @@ -const serverFunc = () => 'server' +const serverFunc = () => 'server'; const clientFunc = () => { - throw new Error( - 'createClientOnlyFn() functions can only be called on the client!', - ) -} + throw new Error("createClientOnlyFn() functions can only be called on the client!"); +}; \ No newline at end of file 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 924d8d2442..5373578295 100644 --- a/packages/start-plugin-core/tests/envOnly/snapshots/server/envOnlyDestructuredRename.tsx +++ b/packages/start-plugin-core/tests/envOnly/snapshots/server/envOnlyDestructuredRename.tsx @@ -1,6 +1,4 @@ -const serverFunc = () => 'server' +const serverFunc = () => 'server'; const clientFunc = () => { - throw new Error( - 'createClientOnlyFn() functions can only be called on the client!', - ) -} + throw new Error("createClientOnlyFn() functions can only be called on the client!"); +}; \ No newline at end of file diff --git a/packages/start-plugin-core/tests/envOnly/snapshots/server/envOnlyExportedAlias.tsx b/packages/start-plugin-core/tests/envOnly/snapshots/server/envOnlyExportedAlias.tsx deleted file mode 100644 index 078c324406..0000000000 --- a/packages/start-plugin-core/tests/envOnly/snapshots/server/envOnlyExportedAlias.tsx +++ /dev/null @@ -1,2 +0,0 @@ -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 index fdb022bc0d..58b2483a48 100644 --- a/packages/start-plugin-core/tests/envOnly/snapshots/server/envOnlyFactory.tsx +++ b/packages/start-plugin-core/tests/envOnly/snapshots/server/envOnlyFactory.tsx @@ -1,34 +1,32 @@ // Server-only function factory export function createServerFactory(name: string) { return () => { - console.log(`Server only: ${name}`) - return `server-${name}` - } + 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!', - ) - } + throw new Error("createClientOnlyFn() functions can only be called on the client!"); + }; } + // Arrow function server factory export const createServerArrowFactory = (prefix: string) => { - return () => `${prefix}-server` -} + 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!', - ) - } -} + throw new Error("createClientOnlyFn() functions can only be called on the client!"); + }; +}; + // Top-level for comparison -export const topLevelServerFn = () => 'server' +export const topLevelServerFn = () => 'server'; export const topLevelClientFn = () => { - throw new Error( - 'createClientOnlyFn() functions can only be called on the client!', - ) -} + throw new Error("createClientOnlyFn() functions can only be called on the client!"); +}; \ No newline at end of file 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 924d8d2442..5373578295 100644 --- a/packages/start-plugin-core/tests/envOnly/snapshots/server/envOnlyStarImport.tsx +++ b/packages/start-plugin-core/tests/envOnly/snapshots/server/envOnlyStarImport.tsx @@ -1,6 +1,4 @@ -const serverFunc = () => 'server' +const serverFunc = () => 'server'; const clientFunc = () => { - throw new Error( - 'createClientOnlyFn() functions can only be called on the client!', - ) -} + throw new Error("createClientOnlyFn() functions can only be called on the client!"); +}; \ No newline at end of file diff --git a/packages/start-plugin-core/tests/envOnly/test-files/envOnlyExportedAlias.tsx b/packages/start-plugin-core/tests/envOnly/test-files/envOnlyExportedAlias.tsx deleted file mode 100644 index 1d51d5dd4f..0000000000 --- a/packages/start-plugin-core/tests/envOnly/test-files/envOnlyExportedAlias.tsx +++ /dev/null @@ -1,4 +0,0 @@ -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/format-snapshot.ts b/packages/start-plugin-core/tests/format-snapshot.ts deleted file mode 100644 index d152094bea..0000000000 --- a/packages/start-plugin-core/tests/format-snapshot.ts +++ /dev/null @@ -1,69 +0,0 @@ -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 deleted file mode 100644 index c9b98c7b4e..0000000000 --- a/packages/start-plugin-core/tests/hydrate-captures.test.ts +++ /dev/null @@ -1,309 +0,0 @@ -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 deleted file mode 100644 index cb62a7d1bd..0000000000 --- a/packages/start-plugin-core/tests/hydrate-split-modules.test.ts +++ /dev/null @@ -1,643 +0,0 @@ -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 deleted file mode 100644 index 442482bd86..0000000000 --- a/packages/start-plugin-core/tests/hydrate-when-transform.test.ts +++ /dev/null @@ -1,706 +0,0 @@ -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 deleted file mode 100644 index a2560a6197..0000000000 --- a/packages/start-plugin-core/tests/hydrateWhen/error-files/hydrateWhenFunctionChild.tsx +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 1e89bb7303..0000000000 --- a/packages/start-plugin-core/tests/hydrateWhen/error-files/hydrateWhenHookCall.tsx +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 63b91b0239..0000000000 --- a/packages/start-plugin-core/tests/hydrateWhen/error-files/hydrateWhenSuperCapture.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 5f7b3df606..0000000000 --- a/packages/start-plugin-core/tests/hydrateWhen/error-files/hydrateWhenThisCapture.tsx +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index d47bc3972d..0000000000 --- a/packages/start-plugin-core/tests/hydrateWhen/hydrateWhen.test.ts +++ /dev/null @@ -1,313 +0,0 @@ -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 deleted file mode 100644 index 5f057addab..0000000000 --- a/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenBasic.tsx +++ /dev/null @@ -1,24 +0,0 @@ -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 deleted file mode 100644 index 34203df6ad..0000000000 --- a/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenMultiple.tsx +++ /dev/null @@ -1,33 +0,0 @@ -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 deleted file mode 100644 index adec83789c..0000000000 --- a/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenNested.tsx +++ /dev/null @@ -1,24 +0,0 @@ -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 deleted file mode 100644 index c2af676fa4..0000000000 --- a/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenNever.tsx +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index b35c36ab1b..0000000000 --- a/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenNoImport.tsx +++ /dev/null @@ -1 +0,0 @@ -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 deleted file mode 100644 index b35c36ab1b..0000000000 --- a/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenNotFromTanstack.tsx +++ /dev/null @@ -1 +0,0 @@ -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 deleted file mode 100644 index a0353594f2..0000000000 --- a/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenObjectFallback.tsx +++ /dev/null @@ -1,47 +0,0 @@ -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 deleted file mode 100644 index 05028ec03b..0000000000 --- a/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenPrefetchState.tsx +++ /dev/null @@ -1,30 +0,0 @@ -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 deleted file mode 100644 index 509b2b988b..0000000000 --- a/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenRenamed.tsx +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index b35c36ab1b..0000000000 --- a/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenSplitFalse.tsx +++ /dev/null @@ -1 +0,0 @@ -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 deleted file mode 100644 index b35c36ab1b..0000000000 --- a/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenSplitFalseFunctionChild.tsx +++ /dev/null @@ -1 +0,0 @@ -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 deleted file mode 100644 index b35c36ab1b..0000000000 --- a/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenWrongImportName.tsx +++ /dev/null @@ -1 +0,0 @@ -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 deleted file mode 100644 index 71896aa304..0000000000 --- a/packages/start-plugin-core/tests/hydrateWhen/snapshots/server/hydrateWhenBasic.tsx +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index 92bb4f9a26..0000000000 --- a/packages/start-plugin-core/tests/hydrateWhen/snapshots/server/hydrateWhenMultiple.tsx +++ /dev/null @@ -1,26 +0,0 @@ -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 ( - <> - - - - - - - -