Skip to main content

aube_resolver/
builder.rs

1use crate::{
2    DependencyPolicy, MinimumReleaseAge, ReadPackageHook, ResolutionMode, ResolvedPackage,
3    Resolver, SupportedArchitectures, override_rule,
4};
5use aube_registry::client::RegistryClient;
6use rustc_hash::FxHashMap;
7use std::collections::{BTreeMap, BTreeSet};
8use std::path::PathBuf;
9use std::sync::Arc;
10use tokio::sync::mpsc;
11
12impl Resolver {
13    const DEFAULT_STREAM_CAPACITY: usize = 64;
14
15    pub fn new(client: Arc<RegistryClient>) -> Self {
16        Self {
17            client,
18            cache: FxHashMap::default(),
19            resolved_tx: None,
20            packument_cache_dir: None,
21            packument_full_cache_dir: None,
22            auto_install_peers: true,
23            exclude_links_from_lockfile: false,
24            supported_architectures: SupportedArchitectures::default(),
25            overrides: BTreeMap::new(),
26            override_rules: Vec::new(),
27            ignored_optional_dependencies: BTreeSet::new(),
28            resolution_mode: ResolutionMode::Highest,
29            project_root: PathBuf::from("."),
30            minimum_release_age: None,
31            catalogs: BTreeMap::new(),
32            read_package_hook: None,
33            dependency_policy: DependencyPolicy::default(),
34            vulnerable_ranges: BTreeMap::new(),
35            git_shallow_hosts: Vec::new(),
36            peers_suffix_max_length: 1000,
37            dedupe_peer_dependents: true,
38            dedupe_peers: false,
39            resolve_peers_from_workspace_root: true,
40            registry_supports_time_field: false,
41            packument_network_concurrency: None,
42        }
43    }
44
45    /// Create a resolver that streams resolved packages through a channel.
46    /// Returns `(resolver, receiver)`. The receiver yields packages as they're
47    /// discovered, allowing tarball fetches to start during resolution.
48    pub fn with_stream(client: Arc<RegistryClient>) -> (Self, mpsc::Receiver<ResolvedPackage>) {
49        Self::with_stream_capacity(client, Self::DEFAULT_STREAM_CAPACITY)
50    }
51
52    /// Create a streaming resolver with a bounded resolved-package buffer.
53    pub fn with_stream_capacity(
54        client: Arc<RegistryClient>,
55        capacity: usize,
56    ) -> (Self, mpsc::Receiver<ResolvedPackage>) {
57        let (tx, rx) = mpsc::channel(capacity.max(1));
58        (
59            Self {
60                client,
61                cache: FxHashMap::default(),
62                resolved_tx: Some(tx),
63                packument_cache_dir: None,
64                packument_full_cache_dir: None,
65                auto_install_peers: true,
66                exclude_links_from_lockfile: false,
67                supported_architectures: SupportedArchitectures::default(),
68                overrides: BTreeMap::new(),
69                override_rules: Vec::new(),
70                ignored_optional_dependencies: BTreeSet::new(),
71                resolution_mode: ResolutionMode::Highest,
72                project_root: PathBuf::from("."),
73                minimum_release_age: None,
74                catalogs: BTreeMap::new(),
75                read_package_hook: None,
76                dependency_policy: DependencyPolicy::default(),
77                vulnerable_ranges: BTreeMap::new(),
78                git_shallow_hosts: Vec::new(),
79                peers_suffix_max_length: 1000,
80                dedupe_peer_dependents: true,
81                dedupe_peers: false,
82                resolve_peers_from_workspace_root: true,
83                registry_supports_time_field: false,
84                packument_network_concurrency: None,
85            },
86            rx,
87        )
88    }
89
90    pub fn with_packument_network_concurrency(mut self, n: Option<usize>) -> Self {
91        self.packument_network_concurrency = n.filter(|&n| n > 0);
92        self
93    }
94
95    /// Enable disk-backed packument caching with ETag/Last-Modified revalidation.
96    pub fn with_packument_cache(mut self, cache_dir: std::path::PathBuf) -> Self {
97        self.packument_cache_dir = Some(cache_dir);
98        self
99    }
100
101    /// Disk cache for full (non-corgi) packuments, used in
102    /// `ResolutionMode::TimeBased` so we can read the `time:` map.
103    pub fn with_packument_full_cache(mut self, cache_dir: std::path::PathBuf) -> Self {
104        self.packument_full_cache_dir = Some(cache_dir);
105        self
106    }
107
108    /// Set the resolution mode. Defaults to `Highest` (pnpm's classic
109    /// behavior). `TimeBased` switches direct deps to lowest-satisfying
110    /// and constrains transitives by a publish-date cutoff.
111    pub fn with_resolution_mode(mut self, mode: ResolutionMode) -> Self {
112        self.resolution_mode = mode;
113        self
114    }
115
116    /// Configure pnpm v11's `minimumReleaseAge` family of settings.
117    /// Pass `None` (or a config with `minutes == 0`) to disable.
118    pub fn with_minimum_release_age(mut self, mra: Option<MinimumReleaseAge>) -> Self {
119        self.minimum_release_age = mra.filter(|m| m.minutes > 0);
120        self
121    }
122
123    /// Whether the resolver should round-trip registry `time:` entries
124    /// into the output graph. pnpm only writes `time:` to its lockfile
125    /// when one of `resolution-mode=time-based` / `minimumReleaseAge`
126    /// is active — otherwise the field is dead weight and, worse, shows
127    /// up as churn in a pnpm ↔ aube diff. Gate the insertion at the
128    /// two `resolved_times.insert` call sites on this predicate so
129    /// Highest-mode installs never populate the map.
130    pub(crate) fn should_record_times(&self) -> bool {
131        self.resolution_mode == ResolutionMode::TimeBased
132            || self.minimum_release_age.is_some()
133            || self.dependency_policy.trust_policy == crate::TrustPolicy::NoDowngrade
134    }
135
136    /// Override the default `auto-install-peers=true` behavior. pnpm reads
137    /// this from `.npmrc` or `pnpm-workspace.yaml`; aube's install command
138    /// plumbs the resolved value through here before running resolution.
139    pub fn with_auto_install_peers(mut self, auto_install_peers: bool) -> Self {
140        self.auto_install_peers = auto_install_peers;
141        self
142    }
143
144    /// Configure pnpm's `peersSuffixMaxLength`. When the peer suffix on a
145    /// `dep_path` would exceed this many bytes, the post-pass replaces it
146    /// with `_<10-char-sha256-hex>`. Default 1000 (pnpm's default).
147    pub fn with_peers_suffix_max_length(mut self, max_length: usize) -> Self {
148        self.peers_suffix_max_length = max_length;
149        self
150    }
151
152    /// Override the default `dedupe-peer-dependents=true` behavior. When
153    /// false, the peer-context pass keeps every distinct ancestor-scope
154    /// variant of a package instead of collapsing peer-equivalent ones
155    /// into a single dep_path. Plumbed from `.npmrc` /
156    /// `pnpm-workspace.yaml` via the install command.
157    pub fn with_dedupe_peer_dependents(mut self, value: bool) -> Self {
158        self.dedupe_peer_dependents = value;
159        self
160    }
161
162    /// Override the default `dedupe-peers=false` behavior. When true,
163    /// peer suffixes in the lockfile drop the peer name and emit only
164    /// the resolved version — `(18.2.0)` instead of `(react@18.2.0)`.
165    /// Plumbed from `.npmrc` / `pnpm-workspace.yaml` via the install
166    /// command.
167    pub fn with_dedupe_peers(mut self, value: bool) -> Self {
168        self.dedupe_peers = value;
169        self
170    }
171
172    /// Override the default `resolve-peers-from-workspace-root=true`
173    /// behavior. When false, peer resolution stops at the importer's
174    /// own scope + BFS-auto-installed transitives instead of consulting
175    /// the workspace root's direct deps as a fallback tier. Plumbed
176    /// from `.npmrc` / `pnpm-workspace.yaml` via the install command.
177    pub fn with_resolve_peers_from_workspace_root(mut self, value: bool) -> Self {
178        self.resolve_peers_from_workspace_root = value;
179        self
180    }
181
182    /// Configure pnpm's `registry-supports-time-field`. When true,
183    /// the resolver keeps using the abbreviated (corgi) packument
184    /// path even when `time:` is needed, saving one full-packument
185    /// fetch per distinct package. Safe for registries that embed
186    /// `time` in their abbreviated responses (Verdaccio 5.15.1+, JSR,
187    /// most in-house mirrors); leave at the default `false` for
188    /// npmjs.org.
189    pub fn with_registry_supports_time_field(mut self, value: bool) -> Self {
190        self.registry_supports_time_field = value;
191        self
192    }
193
194    /// Configure pnpm's `exclude-links-from-lockfile` setting. Only
195    /// affects lockfile serialization — the resolver still builds the
196    /// same graph either way, but the value is stamped into
197    /// `LockfileGraph::settings` so the pnpm writer can filter `link:`
198    /// importer entries on write.
199    pub fn with_exclude_links_from_lockfile(mut self, value: bool) -> Self {
200        self.exclude_links_from_lockfile = value;
201        self
202    }
203
204    /// Override the host platform triple used when filtering optional
205    /// dependencies. See [`platform::SupportedArchitectures`].
206    pub fn with_supported_architectures(mut self, value: SupportedArchitectures) -> Self {
207        self.supported_architectures = value;
208        self
209    }
210
211    /// Provide dependency overrides. The map's keys are selector
212    /// strings — bare name, `parent>child`, `foo@<2`, `**/foo`, or any
213    /// combination thereof — and values are version specifiers (or
214    /// `npm:` aliases). Keys are compiled into `override_rule`
215    /// structures; unparseable keys are dropped. Whenever the resolver
216    /// encounters a task matching a rule (by name + ancestor chain +
217    /// optional version constraints), the requested range is replaced
218    /// with the rule's replacement before any packument fetch or
219    /// version pick. Workspace + manifest sources are merged by the
220    /// caller.
221    pub fn with_overrides(mut self, overrides: BTreeMap<String, String>) -> Self {
222        self.override_rules = override_rule::compile(&overrides);
223        self.overrides = overrides;
224        self
225    }
226
227    /// Provide workspace catalog ranges. Outer key is the catalog name
228    /// (`default` for the unnamed `catalog:` field in
229    /// `pnpm-workspace.yaml`); inner key is the package name. The
230    /// resolver rewrites `catalog:` and `catalog:<name>` task ranges
231    /// against this map before the override / npm-alias passes, and
232    /// records the picks in the output graph's `catalogs` field.
233    pub fn with_catalogs(mut self, catalogs: BTreeMap<String, BTreeMap<String, String>>) -> Self {
234        self.catalogs = catalogs;
235        self
236    }
237
238    /// Set the project root used to resolve `file:` / `link:` paths.
239    /// `file:./vendor/foo` resolves against this directory, and a
240    /// matching directory / tarball is read to drive resolution of the
241    /// local package's transitive deps.
242    pub fn with_project_root(mut self, project_root: PathBuf) -> Self {
243        self.project_root = project_root;
244        self
245    }
246
247    /// Names to strip from every `optionalDependencies` map before
248    /// enqueueing (pnpm's `pnpm.ignoredOptionalDependencies`). Applied
249    /// to both root and transitive optional deps. Empty by default.
250    pub fn with_ignored_optional_dependencies(mut self, ignored: BTreeSet<String>) -> Self {
251        self.ignored_optional_dependencies = ignored;
252        self
253    }
254
255    /// Install a `readPackage` hook. The resolver calls it once per
256    /// version-picked packument before enqueueing transitives; see
257    /// [`ReadPackageHook`] for what mutations are honored.
258    pub fn with_read_package_hook(mut self, hook: Box<dyn ReadPackageHook>) -> Self {
259        self.read_package_hook = Some(hook);
260        self
261    }
262
263    /// Configure dependency resolution policy settings such as
264    /// `packageExtensions`, `allowedDeprecatedVersions`, `trustPolicy*`,
265    /// and `blockExoticSubdeps`.
266    pub fn with_dependency_policy(mut self, policy: DependencyPolicy) -> Self {
267        self.dependency_policy = policy;
268        self
269    }
270
271    /// Prefer non-vulnerable versions for the supplied audit ranges.
272    /// Used by `audit --fix=update` to reuse the normal resolver while
273    /// steering only vulnerable packages away from affected versions.
274    pub fn with_vulnerable_ranges(mut self, ranges: BTreeMap<String, Vec<String>>) -> Self {
275        self.vulnerable_ranges = ranges;
276        self
277    }
278
279    /// Set the `git-shallow-hosts` list used when cloning git deps.
280    /// When a git URL's host matches an entry here (exact match,
281    /// same as pnpm), aube attempts a shallow fetch by SHA; other
282    /// hosts get a plain `git fetch origin`. An empty list forces
283    /// every git dep through the full-fetch path.
284    pub fn with_git_shallow_hosts(mut self, hosts: Vec<String>) -> Self {
285        self.git_shallow_hosts = hosts;
286        self
287    }
288}