fix(start-plugin-core): restore Rsbuild import-protection mocks from persistent cache #8798
main fromrefs/pull/8798/head·opened 🎯 Changes#
With performance.buildCache enabled, Rspack restores modules from its persistent cache without rerunning their loaders. Rsbuild import protection wrote its mock modules (node_modules/.virtual/import-protection/<env>/mock-*.mjs) through VirtualModulesPlugin as a side effect of the import-protection loader, so importers restored from cache pointed at mocks that were never written. In the import-protection fixture the warm build failed:
× Module not found: Can't resolve '…/node_modules/.virtual/import-protection/client/mock-edge-….mjs'
and client violations dropped from 11 to 8. A warm rsbuild dev restart failed the same way.
Mocks are now ordinary modules with their own loader (implementation by @SyMind):
- The import-protection post-loader rewrites denied imports to a real, package-owned
mock.jsentry, with the mock kind (silent/runtime/edge), environment and base64url payload in the query. mock-loadergenerates each mock's source from its query using the existing shared mock generators. The mock entry is excluded from the post-loader.- Rspack's normal module lifecycle owns every mock, so a cached importer and its mocks can each be restored or rebuilt independently. Nothing depends on replaying another loader's side effect.
- This removes
VirtualModulesPlugin, the shared write/ready/pending state, and the earlierbeforeResolverestore hook. A JSbeforeResolvetap runs on every resolve and cost ~8% of thebasicproduction build. - Mock resources keep their full query in the diagnostic graph, so imports that share a specifier keep their own violation metadata and source locations.
Tests#
persistent cache restores import-protection mocks and violations (Rsbuild-only, e2e/react-start/import-protection) runs a cold build and then a warm build with a persistent cache. It requires:
- no errors and identical violations
- that the warm build reuses (does not rebuild) an importer containing mock requests
- that two specifier violations sharing
@tanstack/react-start/serverkeep their importer location, trace and snippet
It fails without the fix. Unit test updated for the mock-loader rule (including Windows separators).
Validation#
@tanstack/start-plugin-core:test:unit(872),test:types,test:eslint,test:buildimport-protectione2e, all toolchains: Rsbuild 88 passed; Vite SSR and bundled-dev 87 passed + 1 skipped- Rsbuild
hmr28/28;server-functionsRsbuild SSR 53/53 and Rsbuild persistent cache 3/3;basice2e, all variants - Production build time vs
main(5 alternating runs):import-protection1,439 → 1,426 ms,basic2,825 → 2,838 ms (noise)
Written with AI coding assistants.
✅ Checklist#
- I have followed the steps in the Contributing guide.
- I have tested code changes locally with the relevant test commands.
- 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.
Summary by CodeRabbit#
- Bug Fixes
- Fixed an issue where Rsbuild’s persistent cache could cause import-protection mocks to be missed after a cached rebuild. Client and server builds now retain consistent protection warnings, including source locations and violation details.
- 1
Important
Review skipped#
Review was skipped as selected files did not have any reviewable changes.
Run configuration-
- Source mode: Auto
- Repository: TanStack/router
- Branch: main
- File: .coderabbit.yaml
- Commit: f723f3b
- Layers: Repository YAML
- Review profile: CHILL
- Plan: Advanced
- Run ID:
df00df0d-4b4c-4785-ae22-fe6d91f18f25
Commits-
Reviewing files that changed from the base of the PR and between 54ebe157e5166a73bf4109283ac36c9640ec9e58 and 68f04533824857fd0e9ac119351a966a485554ec.
You can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
- Trigger review
No actionable comments were generated in the recent review.
Recent review info-
Run configuration-
- Source mode: Auto
- Repository: TanStack/router
- Branch: main
- File: .coderabbit.yaml
- Commit: da2adec
- Layers: Repository YAML
- Review profile: CHILL
- Plan: Advanced
- Run ID:
6f78e3b1-7215-4fe5-950f-998372a1c5ac
Commits-
Reviewing files that changed from the base of the PR and between da2adec76dbe6c0da6d6a0d5640f7b9388217f45 and 54ebe157e5166a73bf4109283ac36c9640ec9e58.
Files selected for processing: 10-
.changeset/rsbuild-import-protection-persistent-cache.mde2e/react-start/import-protection/tests/import-protection.spec.tspackages/start-plugin-core/src/rsbuild/INTERNALS-import-protection.mdpackages/start-plugin-core/src/rsbuild/import-protection-loader.tspackages/start-plugin-core/src/rsbuild/import-protection.tspackages/start-plugin-core/src/rsbuild/mock-loader.tspackages/start-plugin-core/src/rsbuild/mock-module.tspackages/start-plugin-core/src/rsbuild/mock.tspackages/start-plugin-core/tests/rsbuild/import-protection.test.tspackages/start-plugin-core/vite.config.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.
-
Walkthrough
-
Rsbuild import protection now uses query-specific mock modules instead of shared virtual-module state. The change adds mock-module loading and resource normalization, updates loader registration and diagnostics, and adds a persistent-cache regression test.
Changes: Rsbuild import protection
Layer / File(s) Summary Query-based mock-module transport
packages/start-plugin-core/src/rsbuild/mock-module.ts,packages/start-plugin-core/src/rsbuild/mock-loader.ts,packages/start-plugin-core/src/rsbuild/mock.ts,packages/start-plugin-core/vite.config.tsMock IDs now use query parameters and optional encoded payloads. mock-loaderselects the silent, runtime, or edge mock source. The build entries include the new loader and mock resource.Import-protection integration and diagnostics
packages/start-plugin-core/src/rsbuild/import-protection-loader.ts,packages/start-plugin-core/src/rsbuild/import-protection.ts,packages/start-plugin-core/tests/rsbuild/import-protection.test.ts,packages/start-plugin-core/src/rsbuild/INTERNALS-import-protection.mdThe import-protection loader emits mock IDs instead of ensuring virtual modules through shared state. Rsbuild registers mock-loaderand excludes its resource from the import-protection rule. Diagnostic resource lookup maps mock requests to their embedded resource paths. Tests and internals documentation reflect the updated setup.Persistent-cache regression coverage
e2e/react-start/import-protection/tests/import-protection.spec.ts,.changeset/rsbuild-import-protection-persistent-cache.mdThe E2E test builds twice with a shared cache and checks warnings, importer reuse, violation locations, traces, and getRequest()snippets. A patch changeset records the issue.Estimated code review effort: 3 (Moderate) | ~20 minutes
Change: Bug fix
Sequence Diagram(s)#
sequenceDiagram participant transformImportProtection participant Rspack participant mock-loader participant getModuleResource transformImportProtection->>Rspack: Emit query-specific mock module ID Rspack->>mock-loader: Load matching mock.js request mock-loader->>Rspack: Return selected mock module source Rspack->>getModuleResource: Pass mock resource for diagnostic lookup getModuleResource->>Rspack: Return normalized embedded resource pathPossibly related PRs
- TanStack/router#8801: Both changes affect Rsbuild import-protection graph handling, including mock-module resource mapping and diagnostic trace construction.
Suggested labels:
package: start-plugin-core,documentationSuggested reviewers:
schiller-manuel,symind,beaussan
Merge Risk:
Minimal · previous review54ebe-
No actionable issue was established that should prevent merging after normal checks.
Pre-merge checks:
4 · 1-
Failed checks: 1 warningCheck name Status Explanation Resolution Docstring Coverage Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentat… Write docstrings for the functions missing them to satisfy the coverage threshold. Passed checks: 4 passed-
Check name Status Explanation Description check The description follows the required template. It explains the persistent-cache failure, the mock-loader solution, tests, validation results, checklist completion, changeset status, and AI assistance … Title check The title clearly and concisely describes the primary change: restoring Rsbuild import-protection mocks from persistent cache. Linked Issues check Check skipped because no linked issues were found for this pull request. Out of Scope Changes check Check skipped because no linked issues were found for this pull request. Full details: Description check
-
Explanation
The description follows the required template. It explains the persistent-cache failure, the mock-loader solution, tests, validation results, checklist completion, changeset status, and AI assistance disclosure.
-
Full details: Docstring Coverage
-
Explanation
Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 6 functions across 8 files. (2 skipped: 2 unsupported.)
Resolution
Write docstrings for the functions missing them to satisfy the coverage threshold.
-
Finishing Touches
-
🧪 Generate unit tests (beta)
-
- Create a new PR
-
- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
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.
-
I think a dedicated
mock-loaderis a better fit here. I implemented it on top of this PR's current head: implementation and test changes.The import-protection post-loader still checks the compiled code and rewrites denied imports, but the requests now point to a real, package-owned
mock.jsentry with the mock kind, environment, and payload in the query.mock-loadergenerates that module's source using the existing mock generators.This makes each mock independently resolvable and rebuildable even when its importer comes from persistent cache. It removes the
VirtualModulesPluginstate, pending writes, readiness tracking, and thebeforeResolverestoration hook. The full query stays in the diagnostic graph so different imports retain their own violation metadata and source locations. The tradeoff is an additional loader, entry file, and rule, but I prefer having Rspack's normal module lifecycle own the generated source.The regression test in this PR passes with this approach. I also strengthened it to check that the warm build actually reuses an importer containing mock requests, and that two distinct specifier diagnostics retain their usage locations and traces. All 88 Rsbuild import-protection E2E tests pass locally, along with the core unit/type/lint and package checks. The 18 bundle scenarios show no gzip growth. These checks were run on macOS; I haven't run Windows E2E or measured a build-time speedup.
I think a dedicated
mock-loaderis a better fit here. I implemented it on top of this PR's current head: implementation and test changes.The import-protection post-loader still checks the compiled code and rewrites denied imports, but the requests now point to a real, package-owned
mock.jsentry with the mock kind, environment, and payload in the query.mock-loadergenerates that module's source using the existing mock generators.This makes each mock independently resolvable and rebuildable even when its importer comes from persistent cache. It removes the
VirtualModulesPluginstate, pending writes, readiness tracking, and thebeforeResolverestoration hook. The full query stays in the diagnostic graph so different imports retain their own violation metadata and source locations. The tradeoff is an additional loader, entry file, and rule, but I prefer having Rspack's normal module lifecycle own the generated source.The regression test in this PR passes with this approach. I also strengthened it to check that the warm build actually reuses an importer containing mock requests, and that two distinct specifier diagnostics retain their usage locations and traces. All 88 Rsbuild import-protection E2E tests pass locally, along with the core unit/type/lint and package checks. The 18 bundle scenarios show no gzip growth. These checks were run on macOS; I haven't run Windows E2E or measured a build-time speedup.
Thanks, I pulled those into this branch and i'll update the related prs to avoid the old impl here!
@mattcosta7 Maybe we can mark this PR as ready for review.
FYI this PR will likely be superseded by https://github.com/TanStack/router/pull/8817 if i can get it through the finish line
@Sheraff Thanks for the heads-up! I noticed #8817 restores mock modules through
beforeResolve. I still think a dedicatedmock-loaderis a better fit for Rspack: the hook requires a Rust-to-JS call for every request that reaches it, even whenip.define()immediately returns for a non-mock request.With a native rule matching only mock resources, the loader runs only when a mock module needs to be built, and Rspack’s normal module cache handles reuse. It also avoids the virtual-file restoration logic.
Sign in to join this conversation.
🦋 Changeset detected#
Latest commit: 68f04533824857fd0e9ac119351a966a485554ec
The changes in this PR will be included in the next version bump.
This PR includes changesets to release 5 packages
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