Skip to main content

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