Skip to content

refactor: hmr #2222

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

Open
wants to merge 1 commit into
base: v2-dev
Choose a base branch
from
Open

refactor: hmr #2222

wants to merge 1 commit into from

Conversation

Nirvana-Jie
Copy link
Contributor

Description:
refactor: hmr

BREAKING CHANGE:
None

Related issue (if exists):
None

Copy link

changeset-bot bot commented Aug 21, 2025

🦋 Changeset detected

Latest commit: 60fadbd

The changes in this PR will be included in the next version bump.

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

💥 An error occurred when fetching the changed packages and changesets in this PR
Some errors occurred when validating the changesets config:
The package or glob expression "farm-docs" is specified in the `ignore` option but it is not found in the project. You may have misspelled the package name or provided an invalid glob expression. Note that glob expressions must be defined according to https://www.npmjs.com/package/micromatch.
The package or glob expression "bench" is specified in the `ignore` option but it is not found in the project. You may have misspelled the package name or provided an invalid glob expression. Note that glob expressions must be defined according to https://www.npmjs.com/package/micromatch.

Copy link

coderabbitai bot commented Aug 21, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch refactor/hmr

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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR refactors the HMR (Hot Module Replacement) system by breaking down the monolithic HmrEngine class into specialized components for better separation of concerns.

  • Splits HMR functionality into coordinator, broadcaster, and error handler components
  • Introduces an update queue system with priority and deduplication support
  • Improves error handling and retry mechanisms for HMR operations

Reviewed Changes

Copilot reviewed 8 out of 8 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
packages/core/src/server/index.ts Reorders HMR engine initialization to occur after websocket server setup
packages/core/src/server/hmr/updateQueue.ts Adds new update queue management with batching and priority support
packages/core/src/server/hmr/index.ts Provides exports for the new HMR module components
packages/core/src/server/hmr/hmrErrorHandler.ts Implements centralized error handling with retry logic and error history
packages/core/src/server/hmr/hmrCoordinator.ts Coordinates HMR update process with queue management and compilation
packages/core/src/server/hmr/hmrBroadcaster.ts Handles broadcasting update messages to WebSocket clients
packages/core/src/server/hmr-engine.ts Refactored to use the new component-based architecture
.changeset/spicy-kings-shave.md Adds changeset entry for the HMR refactoring

Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

type: 'error',
err: ${JSON.stringify({ message: serialization })},
overlay: ${this.options.hmrOptions?.overlay ?? true}
}`;
Copy link
Preview

Copilot AI Aug 22, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The error message is constructed as a template string without proper JSON formatting. This will result in invalid JSON being sent to clients. Use JSON.stringify() to create a valid JSON string instead.

Suggested change
}`;
const errorMessage = JSON.stringify({
type: 'error',
err: { message: serialization },
overlay: this.options.hmrOptions?.overlay ?? true
});

Copilot uses AI. Check for mistakes.

boundaries: ${JSON.stringify(boundaries)},
dynamicResourcesMap: ${JSON.stringify(dynamicResourcesMap)}
}
}`;
Copy link
Preview

Copilot AI Aug 22, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The update message is constructed as a template string without proper JSON formatting. This will result in invalid JSON being sent to clients. Use JSON.stringify() to create a valid JSON object instead of string templates.

Suggested change
}`;
const messageObj = {
type: 'farm-update',
result: {
added: this.formatModuleArray(added),
changed: this.formatModuleArray(changed),
removed: this.formatModuleArray(removed),
immutableModules: immutableModules.trim(),
mutableModules: mutableModules.trim(),
boundaries,
dynamicResourcesMap
}
};
return JSON.stringify(messageObj);

Copilot uses AI. Check for mistakes.

* Cleanup expired error records
*/
cleanupOldErrors(maxAge = 3600000): void {
// Default 1 hour
Copy link
Preview

Copilot AI Aug 22, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The default value 3600000 should be documented with its unit. Consider adding a JSDoc comment explaining that this is milliseconds (1 hour) or use a named constant.

Suggested change
// Default 1 hour
/**
* Remove error records older than maxAge.
* @param maxAge Maximum age in milliseconds. Default is 1 hour (3600000 ms).
*/
cleanupOldErrors(maxAge = ONE_HOUR_MS): void {

Copilot uses AI. Check for mistakes.


for (const path of pathArray) {
// Check if file exists and timestamp
if (!force && existsSync(path)) {
Copy link
Preview

Copilot AI Aug 22, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The logic checks existsSync(path) only when !force, but continues processing when the file doesn't exist. This could lead to processing non-existent files. Consider checking file existence regardless of the force flag.

Suggested change
if (!force && existsSync(path)) {
// Always check if file exists
if (!existsSync(path)) {
continue;
}
// Check timestamp if not force
if (!force) {

Copilot uses AI. Check for mistakes.

onUpdateFinish(cb: (result: JsUpdateResult) => void): void {
this._onUpdates.push(cb);
// Also register to coordinator
this.coordinator.onUpdateFinish(cb);
Copy link
Preview

Copilot AI Aug 22, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Registering the callback with both the local array and the coordinator could lead to duplicate callback execution. The callback will be called twice for each update - once from the local array and once from the coordinator.

Suggested change
this.coordinator.onUpdateFinish(cb);

Copilot uses AI. Check for mistakes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant