Skip to content

fix(trace): resolve optional deps by walking node_modules when exports omits package.json - #48

Merged
pi0 merged 2 commits into
unjs:mainfrom
tsushanth:fix/optional-dep-resolve-package-fallback
Jun 29, 2026
Merged

pi0 merged 2 commits into
unjs:mainfrom
tsushanth:fix/optional-dep-resolve-package-fallback

Conversation

@tsushanth

@tsushanth tsushanth commented Jun 17, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #47.

The optionalDependencies auto-detection in traceNodeModules (src/trace.ts) locates platform-binding packages that aren't reachable through the JS graph by calling:

resolveModulePath(depName + "/package.json", { try: true, from: versionEntry.path });

This goes through the dependency's exports map, so it silently returns undefined for packages that ship a restrictive exports — most notably @img/sharp-libvips-<platform>@1.3+:

"exports": {
  "./lib": "./lib/index.js",
  "./package": "./package.json",
  "./versions": "./versions.json"
}

There is no ./package.json and no . entry, so the resolve returns undefined, the continue fires, and the dylib package gets silently dropped from the trace output.

Why this matters now

  • sharp <=0.34 reached @img/sharp-libvips-* through its JS graph, so @vercel/nft traced it directly and this path never had to fire.
  • sharp 0.35+ removed the JS edge — the only reference is the @rpath link inside the prebuilt addon (@img/sharp-<platform>/lib/*.node → libvips-cpp.*.dylib).
  • Nitro / TanStack Start production builds then fail at runtime with ERR_DLOPEN_FAILED: ... Library not loaded: @rpath/libvips-cpp.*.dylib.

The fix

Rather than hardcoding a depName + "/package" fallback (which only works because libvips happens to expose a ./package alias — a brittle convention assumption), this stops relying on the exports map to locate the package at all.

A new resolvePackageDir(name, from) helper walks up node_modules from the parent package, mirroring Node.js resolution (correct for nested, hoisted, and pnpm layouts), and reads package.json straight from disk:

  • resolveModulePath("<dep>/package.json") stays as the primary path — unchanged behavior for every package that resolves today.
  • When it fails, fall back to the directory walk instead of guessing a subpath name.

This handles any restrictive-exports package generically, including ones that expose neither ./package.json nor ./package.

Test

Adds a regression test (test/trace.test.ts) with a fixture (@fixture/native-libvips) that mirrors libvips exactly: declared only as an optionalDependency (no JS import), shipping an exports map that omits both . and ./package.json, plus a dummy native binary. The test asserts the manifest and the .node binary land in the trace output.

Verified it fails without the fix (ENOENT … native-libvips/package.json) and passes with it. Full suite (lint + tsgo + vitest) green.

…e.json` is not in exports

Some platform-bindings packages — notably `@img/sharp-libvips-*@1.3+` — ship a
restrictive `exports` map that exposes `./lib`, `./package`, and `./versions`
but not `./package.json` (or `.`). The optionalDependencies fallback added in
the auto-trace block at `trace.ts:142` was hardcoded to
`resolveModulePath(depName + "/package.json", ...)`, which silently returns
`undefined` against those exports, the `continue` fires, and the dylib
package is dropped from the trace output.

Downstream effect: any Nitro / TanStack Start production build that imports
`sharp` 0.35+ fails at runtime with
`ERR_DLOPEN_FAILED: ... @rpath/libvips-cpp.*.dylib`, because the prebuilt
`@img/sharp-<platform>/lib/*.node` links `libvips-cpp` via `@rpath` and the
sibling `@img/sharp-libvips-<platform>` package is no longer in the output
tree. Reachability via the JS graph worked on sharp <=0.34 and stopped on
0.35, which is why this only surfaced now.

Both `depName + "/package.json"` and `depName + "/package"` resolve to the
same `package.json` file when either succeeds, so `readJSON(resolved)` and
`dirname(resolved)` downstream are unchanged. The fallback only fires when
the canonical path can't be resolved, so existing packages keep their
current behaviour.

Closes unjs#47.
@coderabbitai

coderabbitai Bot commented Jun 17, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@pi0x, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 42 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 019aaf05-b8fe-43c1-9251-c9cd32546644

📥 Commits

Reviewing files that changed from the base of the PR and between d6aa570 and c0f3a89.

⛔ Files ignored due to path filters (6)
  • test/fixture/node_modules/@fixture/native-binding/index.mjs is excluded by !**/node_modules/**
  • test/fixture/node_modules/@fixture/native-binding/package.json is excluded by !**/node_modules/**
  • test/fixture/node_modules/@fixture/native-libvips/lib/index.js is excluded by !**/node_modules/**
  • test/fixture/node_modules/@fixture/native-libvips/lib/libvips.node is excluded by !**/node_modules/**
  • test/fixture/node_modules/@fixture/native-libvips/package.json is excluded by !**/node_modules/**
  • test/fixture/node_modules/@fixture/native-libvips/versions.json is excluded by !**/node_modules/**
📒 Files selected for processing (4)
  • src/_utils.ts
  • src/trace.ts
  • test/fixture/native.mjs
  • test/trace.test.ts
📝 Walkthrough

Walkthrough

In traceNodeModules, the optional dependency resolution in src/trace.ts now attempts resolveModulePath(depName + "/package.json", ...) first and falls back to resolveModulePath(depName + "/package", ...) if the first call returns undefined, handling packages whose exports map omits ./package.json.

Changes

Optional dependency resolution fallback

Layer / File(s) Summary
Optional dep package.json resolve with /package fallback
src/trace.ts
Lines 141–154: resolution now tries depName + "/package.json" then falls back to depName + "/package" before calling continue, so packages with restrictive exports maps (e.g., @img/sharp-libvips-*) are no longer silently skipped.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~5 minutes

Possibly related issues

  • #47: nf3 drops @img/sharp-libvips-* during trace → sharp fails with ERR_DLOPEN_FAILED — This PR directly implements the "suggested fix" from that issue: resolve depName + "/package" as a fallback when depName + "/package.json" fails.

Possibly related PRs

  • unjs/nf3#35: Introduced the optional-dependency auto-tracing block in traceNodeModules that this PR patches with the fallback resolution.
  • unjs/nf3#36: Also modifies the optional-dependency tracing flow in src/trace.ts, specifically the file enumeration step that runs after the resolution step changed here.

Suggested reviewers

  • pi0

Poem

🐇 Hoppin' through the module maze,
./package.json lost in a haze —
One fallback path, a gentle try,
./package found what slipped on by!
Sharp dylibs safe, no dlopen cry! 🎉

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. 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 code changes directly implement the primary objective from issue #47: adding a fallback resolution mechanism in the traceNodeModules function to resolve optionalDependencies via /package when /package.json fails, enabling @img/sharp-libvips packages to be traced.
Out of Scope Changes check ✅ Passed All changes are narrowly scoped to the optionalDependencies fallback mechanism in src/trace.ts, directly addressing the issue. No unrelated refactoring, dependency updates, or out-of-scope modifications are present.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main fix: resolving optional dependencies when package exports omit package.json.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@pi0x pi0x changed the title fix(trace): resolve optionalDependencies via /package when /package.json is not exported fix(trace): resolve optional deps by walking node_modules when exports omits package.json Jun 29, 2026
Replace the hardcoded `<dep>/package` fallback with a `resolvePackageDir`
helper that walks up `node_modules` and reads `package.json` from disk,
bypassing the `exports` map entirely. This handles any package with a
restrictive `exports` (e.g. `@img/sharp-libvips-*`, which omits both `.`
and `./package.json`) instead of relying on a coincidental `./package`
alias.

Add a regression test with a libvips-style fixture: an optional dep with
no JS import and an `exports` map omitting `.` and `./package.json`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@codecov

codecov Bot commented Jun 29, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.85714% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 77.20%. Comparing base (34c8f04) to head (c0f3a89).
⚠️ Report is 5 commits behind head on main.

Files with missing lines Patch % Lines
src/_utils.ts 90.90% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main      #48      +/-   ##
==========================================
+ Coverage   73.74%   77.20%   +3.45%     
==========================================
  Files           5        5              
  Lines         419      465      +46     
  Branches      128      141      +13     
==========================================
+ Hits          309      359      +50     
- Misses         76       77       +1     
+ Partials       34       29       -5     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@pi0
pi0 merged commit d449dd5 into unjs:main Jun 29, 2026
6 checks passed
@homersimpsons

Copy link
Copy Markdown

Can this be backported to nitro v2?

From what I understand this was shipped in https://github.com/unjs/nf3/releases/tag/v0.3.18 and nf3 is a extract from nitro:

nf3/README.md

Line 19 in a81bf79

Originally extracted from [Nitro](https://nitro.build) and used for optimizing `nf3` package dist itself!

but it is not included in nitro v2 (https://github.com/nitrojs/nitro/blob/v2/package.json) while it is in nitro v3:
https://github.com/nitrojs/nitro/blob/77b77ffb19fd522400b517f6773b78832ff436b7/package.json#L78

Nitro v2 seems to still be maintained https://github.com/nitrojs/nitro/commits/v2/.

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.

nf3 drops @img/sharp-libvips-* during trace → sharp fails with ERR_DLOPEN_FAILED

3 participants