Skip to content

fix(miniflare): resolve conditional exports and require() from CommonJS packages - #68

Merged
pi0 merged 2 commits into
mainfrom
fix/miniflare-cjs-resolution
Sep 29, 2026
Merged

pi0 merged 2 commits into
mainfrom
fix/miniflare-cjs-resolution

Conversation

@pi0x

@pi0x pi0x commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #67.

Conditional exports

exsolve only matches the conditions it's given, and the fallback passed just exportConditions (["workerd", "worker"]). Without import, resolving a dual package failed and fell back to require.resolve, which picks Node's require target. The fallback now adds import or require from workerd's X-Resolve-Method header, so the issue's example resolves to default.mjs (import) / default.cjs (require).

require() from CommonJS in node_modules

Bare specifiers were served under the importer's directory plus the package name (src/deep/cjs-pkg), so the CommonJS file became src/deep/index.cjs?__cjs and its require() calls resolved from there. It also meant a package imported from two directories loaded twice, and a require("dual-pkg") inside a package could hit the cached ESM shim named src/deep/dual-pkg.

  • Bare specifiers, and paths a plugin's resolveId returns (e.g. node:process → an unenv file), now redirect (301) to the file's real path, so module names match real locations. workerd's re-request of the location reuses the resolution, so there's no loop and plugin hooks run once.
  • workerd's require() asks the fallback for node:process before its own built-in, and fails with No such module on a 404. require("node:*") now redirects to node:*?__require, an ESM shim that imports the built-in. workerd also caches the shim under the requested name, so if the built-in is missing, the shim's import resolves back to itself. The shim detects that case and throws workerd's usual No such module error.

No implicit unenv polyfills

The fallback used to resolve unenv/node/<name> from the importer when it asked for a node:* module, so whether a built-in missing from workerd worked in dev depended on whether unenv happened to be installed. It now returns 404, so workerd loads its own built-in or reports it missing, as in production. Frameworks that want polyfills can alias them in their own resolution.

Tests

  • test/miniflare.test.ts: a dual package imported from a nested dir, a CommonJS package requiring node:process, a dual package and a relative file (with a same-basename decoy next to the importer), plus single-instance loading. Fails on main with the error from the issue.
  • A plugin resolving a CommonJS require("node:process") to a file with relative imports (the issue's Invalid module specifier case), with the hook called once.
  • Missing node: built-ins fail with No such module for both import and require(), even with an unenv package installed.

Only verified on Linux with miniflare v5. Windows paths reuse toWorkerdPath() and rely on the Windows CI job.

🤖 Generated with AI assistant

Summary by CodeRabbit

  • Bug Fixes
    • Improved package resolution for imports and require() calls, including conditional package exports and redirects that preserve query parameters.
    • Added support for CommonJS require() calls to Node built-ins through a compatibility shim.
    • Missing node: modules now fail consistently for both imports and require() calls, including when polyfills are present.

…onJS packages

- add the `import`/`require` export condition (from `X-Resolve-Method`)
- redirect bare specifiers to the file's real path, so a package has one
  instance and its relative imports and `require()` calls resolve from where
  it lives
- serve `require("node:*")` through an ESM shim importing the built-in
- stop polyfilling `node:*` modules with an installed `unenv`: workerd loads
  its own built-in or reports it missing, as in production

Closes #67
@coderabbitai

coderabbitai Bot commented Sep 29, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Advanced

Run ID: 733b16f7-103e-4e18-8335-53dd0db614c6

📥 Commits

Reviewing files that changed from the base of the PR and between 3ed95dc and fe5b369.

📒 Files selected for processing (3)
  • .agents/MINIFLARE.md
  • src/runners/miniflare/runner.ts
  • test/miniflare.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.


📝 Walkthrough

Walkthrough

The Miniflare fallback resolver now applies import or require conditions to package resolution. It redirects Node built-in require() requests to an ESM shim and returns 404 for Node built-in imports. New tests cover conditional exports, CommonJS resolution, and missing built-ins.

Changes

Miniflare module resolution

Layer / File(s) Summary
Request-aware package resolution
.agents/MINIFLARE.md, src/runners/miniflare/runner.ts, test/miniflare.test.ts
The fallback resolver selects import or require from the request header and adds that condition to package resolution. Successful package resolutions redirect to the resolved path and preserve the query string. Tests cover conditional exports, CommonJS package and relative-file loading, and namespace identity.
Node built-in require shim
.agents/MINIFLARE.md, src/runners/miniflare/runner.ts, test/miniflare.test.ts
Node built-in imports return 404. Node built-in require() requests redirect to a generated ESM shim, which re-exports named exports and selects a default export. Tests verify missing built-ins fail even when a matching unenv polyfill is present.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix · Severity of issue fixed: Medium

Sequence Diagram(s)

sequenceDiagram
  participant Miniflare
  participant FallbackService
  participant Exsolve
  participant Workerd
  Miniflare->>FallbackService: Send specifier and import or require method
  FallbackService->>Exsolve: Resolve bare package with method-specific conditions
  Exsolve-->>FallbackService: Return resolved path
  FallbackService-->>Miniflare: Redirect and preserve query string
  Miniflare->>Workerd: Load redirected module
Loading

Suggested reviewers: pi0

Merge Risk: ⚪ Minimal · up to fe5b3

The reviewed resolution paths appear consistent with the intended behavior. No issue identified here needs to be fixed before merging.

Security Architecture Review

Security architecture risk: 🔵 Low · up to fe5b3

This changes which package code the local worker loads for imports and CommonJS requires. The review found no new public access path or confirmed security weakness, but some redirect behavior across runtime versions remains unverified.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The affected scope is module loading in runner-owned local workers and their dependencies, not a newly exposed HTTP endpoint. No changed route from a public request to the fallback was identified.

Trust Boundaries and Controls

  • observed — The resolver still accepts module specifiers from workerd’s fallback requests, while the load-method header selects export conditions. The new Node built-in branch delegates imports to workerd and serves require shims only for the Node namespace; it does not resolve that namespace through an installed package.

Resilience and Maintainability Implications

  • inferred — Ordinary package redirects preserve the request query and converge on a real-path name. The Node require redirect instead uses a fixed shim suffix, discarding an existing query; its practical effect is unresolved because query-bearing built-in requests are not covered by the supplied tests.

Hardening Proposals

  • proposed — Before relying on the shim across supported runtime versions, verify that redirected require requests retain their load method and establish the intended identity for any query-bearing Node built-in request.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 4 functions across 2 files. (1 skipped: 1… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The PR addresses both coding objectives in issue #67. runner.ts adds the import or require condition from X-Resolve-Method, resolves bare packages with those conditions, and redirects to the r…
Out of Scope Changes check ✅ Passed The changes stay within issue #67. The runner changes implement module resolution, built-in handling, and CommonJS shims. The added tests verify those behaviors. The .agents/MINIFLARE.md updates doc…
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the primary changes: conditional export resolution and CommonJS require() handling in Miniflare.
Full details: Docstring Coverage

Explanation

Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 4 functions across 2 files. (1 skipped: 1 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
⚔️ Resolve merge conflicts 💡
  • Resolve merge conflict in branch fix/miniflare-cjs-resolution
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR

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

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

Apply the real-path redirect to paths a plugin's `resolveId` returns too,
and reuse a redirect's resolution for workerd's re-request so plugins run once.
@pi0
pi0 merged commit 888d296 into main Sep 29, 2026
9 checks passed
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.

miniflare: CommonJS resolution issues (conditional exports and require() from node_modules)

2 participants