Skip to main content

aube_resolver/
lib.rs

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