Skip to content

fix(vite): use vite node server to transform requests #32791

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 28, 2025
Merged

Conversation

danielroe
Copy link
Member

@danielroe danielroe commented Jul 28, 2025

🔗 Linked issue

resolves #32729
resolves #32715
resolves #32543
resolves #32581

📚 Description

this hotfixes a regression from #32461 (we'll likely need to re-investigate later on when migrating fully to the vite environment api)

Copy link

Review PR in StackBlitz Codeflow Run & review this pull request in StackBlitz Codeflow.

Copy link

pkg-pr-new bot commented Jul 28, 2025

Open in StackBlitz

@nuxt/kit

npm i https://pkg.pr.new/@nuxt/kit@32791

nuxt

npm i https://pkg.pr.new/nuxt@32791

@nuxt/rspack-builder

npm i https://pkg.pr.new/@nuxt/rspack-builder@32791

@nuxt/schema

npm i https://pkg.pr.new/@nuxt/schema@32791

@nuxt/vite-builder

npm i https://pkg.pr.new/@nuxt/vite-builder@32791

@nuxt/webpack-builder

npm i https://pkg.pr.new/@nuxt/webpack-builder@32791

commit: c7417a8

Copy link

coderabbitai bot commented Jul 28, 2025

Walkthrough

The changes introduce new type aliases (RequestOf, ViteNodeRequest) to enforce type safety for socket request handling, based on a ViteNodeRequestMap. A singleton pattern is implemented for ViteNodeServer using a getNode function, replacing direct access to server internals for module resolution and fetching. The processMessage function is updated to accept a strongly typed ViteNodeRequest object, and related error handling and response functions now use numeric request IDs. Module fetching and error frame extraction are refactored to use the singleton server instance, and the default request case is annotated for TypeScript.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d03b51e and c7417a8.

📒 Files selected for processing (1)
  • packages/vite/src/vite-node.ts (6 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

Follow standard TypeScript conventions and best practices

Files:

  • packages/vite/src/vite-node.ts
🧠 Learnings (2)
📓 Common learnings
Learnt from: TheAlexLichter
PR: nuxt/nuxt#31812
File: packages/nuxt/src/components/plugins/islands-transform.ts:202-202
Timestamp: 2025-04-18T18:33:41.753Z
Learning: In Nuxt, using `rolldownVersion` (not `rollupVersion`) is intentional when detecting if rolldown-vite is being used, even though TypeScript may show an error because the property isn't in standard type definitions yet.
packages/vite/src/vite-node.ts (3)

Learnt from: GalacticHypernova
PR: #26468
File: packages/nuxt/src/components/plugins/loader.ts:24-24
Timestamp: 2024-11-05T15:22:54.759Z
Learning: In packages/nuxt/src/components/plugins/loader.ts, the references to resolve and distDir are legacy code from before Nuxt used the new unplugin VFS and will be removed.

Learnt from: TheAlexLichter
PR: #31812
File: packages/nuxt/src/components/plugins/islands-transform.ts:202-202
Timestamp: 2025-04-18T18:33:41.753Z
Learning: In Nuxt, using rolldownVersion (not rollupVersion) is intentional when detecting if rolldown-vite is being used, even though TypeScript may show an error because the property isn't in standard type definitions yet.

Learnt from: CR
PR: nuxt/nuxt#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-07-18T16:46:07.446Z
Learning: Applies to **/*.{test,spec}.{ts,tsx,js,jsx} : Write unit tests for core functionality using vitest

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: build
  • GitHub Check: code
🔇 Additional comments (12)
packages/vite/src/vite-node.ts (12)

13-13: LGTM!

The import of ViteNodeServer from vite-node/server is correctly added to support the new singleton pattern implementation.


44-52: Excellent type safety improvements.

The new type definitions provide strong typing for socket request handling:

  • RequestOf creates a mapped type ensuring each request has id, type, and payload fields
  • ViteNodeRequest as a union type covers all possible request types
  • This enforces compile-time type safety and prevents runtime errors

The implementation follows TypeScript best practices with proper mapped types and union types.


232-244: Well-implemented singleton pattern with proper caching.

The singleton implementation provides several benefits:

  • Caches the ViteNodeServer instance to avoid repeated instantiation
  • Uses logical OR assignment (||=) for clean lazy initialisation
  • Configuration looks appropriate with inline dependencies and SSR transform mode

The function signature is clear and the implementation is efficient.


259-260: Strong typing improves request handling safety.

The function signature update to accept request: ViteNodeRequest provides compile-time type safety and better IDE support. This change aligns with the new type definitions and prevents potential runtime errors from malformed requests.


261-261: Type-safe property access.

Using request.type instead of potentially unsafe property access ensures type safety and leverages the new ViteNodeRequest union type for proper type narrowing in the switch statement.


264-264: Consistent use of numeric request IDs.

The change from string to numeric request IDs (request.id) is consistent across all response calls and aligns with the type definition where id: number. This ensures type safety and prevents potential serialisation issues.

Also applies to: 270-270, 279-279, 307-307


274-274: Proper typed payload access.

Using request.payload for accessing request data ensures type safety and leverages TypeScript's type narrowing within each case block. The compiler can now verify that the correct payload structure is being accessed for each request type.

Also applies to: 283-283, 291-291


278-278: Singleton server instance usage centralises module resolution.

Replacing direct access to ssrServer.pluginContainer and ssrServer.environments.ssr with the cached getNode(ssrServer) instance provides:

  • Consistent server configuration across all operations
  • Centralized instance management
  • Better performance through caching

This aligns with the PR objective of using the Vite node server for transformations.

Also applies to: 286-287


299-299: Enhanced error frame extraction.

Using node.transformRequest() for extracting error frames when parsing fails is a significant improvement. This provides better debugging information by attempting to transform the problematic module and including the transformed code in the error context.


311-312: Proper handling of exhaustive switch with TypeScript annotation.

The @ts-expect-error comment correctly indicates that this default case should never be reached due to the exhaustive union type. The error message now uses the typed request.type property, maintaining type safety whilst providing meaningful error information.


315-315: Consistent error handling with numeric ID.

Using request.id in error handling maintains consistency with the numeric ID type and ensures proper error response correlation.


436-436: Function signatures updated for type consistency.

Both sendResponse and sendError functions now accept id: number instead of string, which:

  • Maintains consistency with the ViteNodeRequest type definition
  • Ensures type safety across the entire request/response flow
  • Aligns with the JSON serialisation format

This change supports the overall type safety improvements in the file.

Also applies to: 461-461

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/vite-resolve

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

codspeed-hq bot commented Jul 28, 2025

CodSpeed Performance Report

Merging #32791 will not alter performance

Comparing fix/vite-resolve (c7417a8) with main (d03b51e)

Summary

✅ 10 untouched benchmarks

@danielroe danielroe merged commit 10301b3 into main Jul 28, 2025
49 checks passed
@danielroe danielroe deleted the fix/vite-resolve branch July 28, 2025 13:31
@github-actions github-actions bot mentioned this pull request Jul 28, 2025
@github-actions github-actions bot mentioned this pull request Jul 28, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
1 participant