aube_resolver/lib.rs
1mod builder;
2mod catalog;
3mod error;
4mod local_source;
5pub mod override_rule;
6mod package_ext;
7mod peer_context;
8pub mod platform;
9mod primer;
10mod resolve;
11mod semver_util;
12mod trust;
13mod types;
14
15pub use error::{AgeGateDetails, CatalogDetails, Error, ExoticSubdepDetails, NoMatchDetails};
16pub use package_ext::is_deprecation_allowed;
17pub use peer_context::{
18 PeerContextOptions, UnmetPeer, apply_peer_contexts, detect_unmet_peers,
19 hoist_auto_installed_peers,
20};
21pub use platform::{SupportedArchitectures, is_supported};
22pub use primer::{PruneStats as PrimerPruneStats, prune_cache as prune_primer_cache};
23pub use trust::{MissingTimeDetails as MissingTrustTimeDetails, TrustDowngradeDetails};
24pub use trust::{TrustEvidence, TrustExcludeParseError, TrustExcludeRules};
25pub use types::{
26 DependencyPolicy, MinimumReleaseAge, PackageExtension, ReadPackageHook, ResolutionMode,
27 ResolvedPackage, TrustPolicy,
28};
29
30use semver_util::version_satisfies;
31
32#[cfg(test)]
33use aube_lockfile::{DirectDep, LocalSource, LockedPackage, LockfileGraph};
34#[cfg(test)]
35use aube_manifest::PackageJson;
36#[cfg(test)]
37use error::{
38 RegistryErrorKind, build_age_gate, build_no_match, classify_registry_error,
39 format_registry_help,
40};
41#[cfg(test)]
42use local_source::{dep_path_for, should_block_exotic_subdep};
43#[cfg(test)]
44use package_ext::{apply_package_extensions, package_selector_matches, pick_override_spec};
45#[cfg(test)]
46use peer_context::{
47 apply_dedupe_peers_to_key, contains_canonical_back_ref, dedupe_peer_suffixes,
48 dedupe_peer_variants, hash_peer_suffix,
49};
50#[cfg(test)]
51use semver_util::{PickResult, pick_version, strip_alias_prefix};
52#[cfg(test)]
53use types::format_iso8601_utc;
54
55use aube_lockfile::DepType;
56use aube_registry::Packument;
57use aube_registry::client::RegistryClient;
58use std::collections::{BTreeMap, BTreeSet};
59use std::path::PathBuf;
60use std::sync::Arc;
61use tokio::sync::mpsc;
62
63// Re-export shared aube-util collection aliases under the original
64// FxHashMap name to avoid touching every call site.
65pub(crate) use aube_util::collections::FxMap as FxHashMap;
66pub(crate) use aube_util::collections::FxSet as FxHashSet;
67
68/// BFS dependency resolver.
69pub struct Resolver {
70 client: Arc<RegistryClient>,
71 cache: FxHashMap<String, Packument>,
72 /// Optional channel to stream resolved packages as they're discovered.
73 resolved_tx: Option<mpsc::Sender<ResolvedPackage>>,
74 /// Optional disk cache directory for packuments (with ETag revalidation).
75 packument_cache_dir: Option<std::path::PathBuf>,
76 /// Separate disk cache for full (non-corgi) packuments; only used
77 /// when `resolution_mode` is `TimeBased` (which needs the `time:`
78 /// map). Defaults to the sibling `packuments-full-v1/` directory
79 /// next to `packument_cache_dir`.
80 packument_full_cache_dir: Option<std::path::PathBuf>,
81 /// When true (pnpm's default), a package's declared `peerDependencies`
82 /// are enqueued like regular transitives and — if not already
83 /// satisfied by the importer — hoisted to the importer's direct deps.
84 /// When false, peers neither get auto-installed as transitives nor
85 /// hoisted; unmet peers still surface as warnings via
86 /// `detect_unmet_peers`, but the user is on the hook for adding them
87 /// explicitly to `package.json`.
88 auto_install_peers: bool,
89 /// pnpm's `exclude-links-from-lockfile`. Round-tripped through the
90 /// lockfile's `settings:` header; when true, the pnpm writer omits
91 /// `link:` deps from the importer `dependencies:` maps so a
92 /// sibling symlink change doesn't churn the lockfile. Defaults to
93 /// false (pnpm's default). Does not affect resolution itself, only
94 /// the `canonical.settings.exclude_links_from_lockfile` flag the
95 /// writer reads.
96 exclude_links_from_lockfile: bool,
97 /// User-declared override for the host platform triple, used when
98 /// deciding whether an optional dep's `os`/`cpu`/`libc` constraints
99 /// are satisfied. Empty fields fall back to the host.
100 supported_architectures: SupportedArchitectures,
101 /// Raw dependency override map from the manifest (selector key →
102 /// replacement spec). Round-tripped verbatim through the lockfile
103 /// for drift detection; the compiled form in `override_rules` is
104 /// what the resolver hot loop actually consults.
105 overrides: BTreeMap<String, String>,
106 /// Compiled view of `overrides`. Built by `with_overrides`.
107 /// Unparseable selector keys are dropped at compile time so the
108 /// matcher never has to think about them.
109 override_rules: Vec<override_rule::OverrideRule>,
110 /// Names listed in the root manifest's `pnpm.ignoredOptionalDependencies`.
111 /// Any optional dep (root or transitive) whose name is in this set is
112 /// dropped before enqueueing — the resolver never fetches or locks it.
113 /// Mirrors pnpm's `createOptionalDependenciesRemover` read-package hook.
114 ignored_optional_dependencies: BTreeSet<String>,
115 /// pnpm's `resolution-mode` — `Highest` (default) or `TimeBased`.
116 resolution_mode: ResolutionMode,
117 /// Project root used to resolve `file:` / `link:` paths to the
118 /// target directory. Defaults to the current working directory;
119 /// callers set it via `with_project_root`.
120 project_root: PathBuf,
121 /// pnpm v11's `minimumReleaseAge` triplet. `None` disables the
122 /// supply-chain age gate entirely (matching `minimumReleaseAge: 0`).
123 minimum_release_age: Option<MinimumReleaseAge>,
124 /// Workspace catalog ranges. Outer key is the catalog name
125 /// (`default` for the unnamed `catalog:` field in
126 /// `pnpm-workspace.yaml`); inner key is the package name; value is
127 /// the version range. When the resolver encounters a `catalog:` or
128 /// `catalog:<name>` task range, it rewrites the task in place to
129 /// the matching range *before* the override / npm-alias passes,
130 /// while preserving the original `catalog:...` text in
131 /// `original_specifier` so the lockfile importer keeps the
132 /// reference verbatim.
133 catalogs: BTreeMap<String, BTreeMap<String, String>>,
134 /// Optional `readPackage` hook, invoked once per resolved package
135 /// before its transitive deps are enqueued. See [`ReadPackageHook`].
136 /// Wired up by `aube` when a `.pnpmfile.cjs` is detected and
137 /// `--ignore-pnpmfile` was not set.
138 read_package_hook: Option<Box<dyn ReadPackageHook>>,
139 dependency_policy: DependencyPolicy,
140 /// Advisory ranges to avoid when resolving audit fixes. The map is
141 /// keyed by registry package name and values are npm semver ranges
142 /// from `vulnerable_versions`. When a clean satisfying version
143 /// exists, it wins over locked/sibling reuse and the normal highest
144 /// pick; if not, resolution falls back to the ordinary pick so the
145 /// caller can report the advisory as remaining.
146 vulnerable_ranges: BTreeMap<String, Vec<String>>,
147 /// Hosts for which aube performs shallow git clones, mirroring
148 /// pnpm's `git-shallow-hosts`. When a git dep's URL host is in
149 /// this list, the store attempts `git fetch --depth 1 origin
150 /// <sha>` (falling back to a full fetch if the server refuses);
151 /// otherwise it goes straight to a full fetch. Defaults to an
152 /// empty list — `aube` populates it from the generated
153 /// `aube_settings::resolved::git_shallow_hosts` accessor (which
154 /// carries the pnpm-compat default list baked in from
155 /// `settings.toml`) via [`Self::with_git_shallow_hosts`]. Library
156 /// callers who construct a `Resolver` directly must set it
157 /// explicitly if they want the pnpm list; keeping the list in
158 /// one place (`settings.toml`) avoids drift.
159 git_shallow_hosts: Vec<String>,
160 /// pnpm's `peersSuffixMaxLength`. When the peer-ID suffix on a
161 /// `dep_path` (the `(name@version)(…)` portion) would exceed this
162 /// many bytes, the post-pass replaces the whole suffix with
163 /// `_<hex>` where `<hex>` is the first 10 chars of SHA-256 of the
164 /// full suffix. Matches pnpm's lockfile format. Default 1000.
165 peers_suffix_max_length: usize,
166 /// pnpm's `dedupe-peer-dependents`. When true (pnpm's default),
167 /// the peer-context post-pass collapses multiple dep_path variants
168 /// of the same canonical package into a single entry when their
169 /// peer resolutions are pairwise-equivalent. When false, every
170 /// distinct ancestor scope gets its own variant — useful for
171 /// debugging peer-context divergence or mimicking pnpm v6/v7
172 /// behavior.
173 dedupe_peer_dependents: bool,
174 /// pnpm's `dedupe-peers`. When true, peer suffixes in the lockfile
175 /// emit just the resolved version — `(18.2.0)` — instead of the
176 /// full `(react@18.2.0)` form. Shorter dep_paths at the cost of
177 /// peer-name fidelity in the snapshot. Defaults to false.
178 dedupe_peers: bool,
179 /// pnpm's `resolve-peers-from-workspace-root`. When true (pnpm's
180 /// default), an importer's unresolved peer can be satisfied by a
181 /// dependency declared in the root importer's `package.json`, even
182 /// when no ancestor scope carries that dep. Common monorepo knob:
183 /// the workspace root pins shared peers like `react`, and every
184 /// subpackage can peer on it without hoisting the version into
185 /// every sibling.
186 resolve_peers_from_workspace_root: bool,
187 /// pnpm's `registry-supports-time-field`. When true, the resolver
188 /// trusts the abbreviated (corgi) packument to carry the `time:`
189 /// map and keeps using the cheap `fetch_packument_cached` path
190 /// even under time-aware resolution (`TimeBased` or
191 /// `minimumReleaseAge`). Defaults to false — the same assumption
192 /// pnpm and npmjs.org ship with — so the resolver falls back to
193 /// the full-packument fetch to get `time:` reliably. No effect
194 /// when neither time-based resolution nor `minimumReleaseAge` is
195 /// active, since the abbreviated path is already the only one
196 /// running.
197 registry_supports_time_field: bool,
198 /// Use the bundled metadata primer even when the configured
199 /// registry is not npmjs.org. Intended for npm-compatible mirrors
200 /// and controlled benchmarks; tarball URLs are rewritten to the
201 /// active registry before cache seeding so installs still fetch
202 /// package bytes from the configured source.
203 force_metadata_primer: bool,
204 pub(crate) packument_network_concurrency: Option<usize>,
205}
206
207pub(crate) struct ResolveTask {
208 pub(crate) name: String,
209 pub(crate) range: String,
210 dep_type: DepType,
211 is_root: bool,
212 /// The parent dep_path, for wiring up transitive dep references
213 parent: Option<String>,
214 /// Which importer this task belongs to (e.g., "." or "packages/app")
215 pub(crate) importer: String,
216 /// The original specifier from package.json before any rewrites
217 /// (e.g. `"npm:real-pkg@^2.0.0"` for an alias, or `"^4.17.0"` for a normal range).
218 /// Only set for root deps; recorded into the lockfile for drift detection.
219 pub(crate) original_specifier: Option<String>,
220 /// Real registry package name for npm-alias tasks.
221 ///
222 /// When a task arrives with `range` like `"npm:h3@2.0.1-rc.20"`,
223 /// the preprocessing loop strips the prefix and sets this field to
224 /// the real package name (`"h3"`) while *keeping* `name` as the
225 /// user-facing alias (`"h3-v2"`, the key the package.json used).
226 /// Every identity-facing site — dep_path formation, direct-dep
227 /// records, parent `dependencies` wiring, the resolved-versions
228 /// dedupe map — uses `name`, so the alias survives all the way
229 /// to the linker and ends up as `node_modules/<alias>/` with
230 /// `LockedPackage.alias_of = Some(real_name)`. Only registry
231 /// I/O (packument fetch, tarball URL derivation) consults this
232 /// field.
233 ///
234 /// `None` for ordinary (non-aliased) tasks — `name` is already
235 /// the registry name and nothing downstream needs to distinguish.
236 real_name: Option<String>,
237 /// Outermost-first chain of `(name, version)` ancestors above this
238 /// task in the dependency graph, used by `parent>child` override
239 /// selectors. Empty for root/importer deps. Each child-enqueue
240 /// site is responsible for extending its parent's chain with the
241 /// parent's own `(name, version)` frame.
242 pub(crate) ancestors: Vec<(String, String)>,
243 /// `true` when an override rewrote `range` to a `link:`/`file:`
244 /// path. Override paths are anchored at the project root (where the
245 /// override is declared), not at the consuming workspace package or
246 /// transitive parent — same convention pnpm follows. Without this
247 /// signal the local-source resolver would re-anchor `link:./libs/x`
248 /// against the importer or parent dir and walk to a phantom path.
249 pub(crate) range_from_override: bool,
250}
251
252impl ResolveTask {
253 /// Name to use for registry operations (packument fetch, tarball
254 /// URL). Returns `real_name` for aliased tasks and `name`
255 /// otherwise. Every call site that talks to the registry goes
256 /// through this accessor so alias handling stays localized.
257 fn registry_name(&self) -> &str {
258 self.real_name.as_deref().unwrap_or(&self.name)
259 }
260
261 /// Construct a root-importer task for `(name, range)` under
262 /// `importer`, with the appropriate `dep_type` and no parent/ancestry.
263 /// Every root-dep enqueue site uses this shape; the factory keeps
264 /// the literal in one place so a new field added to `ResolveTask`
265 /// lands consistently across prod/dev/optional loops.
266 fn root(name: String, range: String, dep_type: DepType, importer: String) -> Self {
267 let original = range.clone();
268 Self {
269 name,
270 range,
271 dep_type,
272 is_root: true,
273 parent: None,
274 importer,
275 original_specifier: Some(original),
276 real_name: None,
277 ancestors: Vec::new(),
278 range_from_override: false,
279 }
280 }
281
282 /// Construct a transitive (non-root) task discovered by walking a
283 /// parent package's dependency map. Carries the parent dep_path
284 /// and inherited ancestor chain for overrides.
285 fn transitive(
286 name: String,
287 range: String,
288 dep_type: DepType,
289 parent: String,
290 importer: String,
291 ancestors: Vec<(String, String)>,
292 ) -> Self {
293 Self {
294 name,
295 range,
296 dep_type,
297 is_root: false,
298 parent: Some(parent),
299 importer,
300 original_specifier: None,
301 real_name: None,
302 ancestors,
303 range_from_override: false,
304 }
305 }
306}
307
308#[cfg(test)]
309mod tests;