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