Skip to main content

aube_resolver/
lib.rs

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