aube_resolver/resolve.rs
1use crate::local_source::{
2 dep_path_for, is_non_registry_specifier, read_local_manifest, rebase_local, resolve_git_source,
3 resolve_remote_tarball, should_block_exotic_subdep,
4};
5use crate::package_ext::{apply_package_extensions, pick_override_spec};
6use crate::semver_util::{PickResult, pick_version, version_satisfies};
7use crate::{
8 Error, ExoticSubdepDetails, PeerContextOptions, ResolutionMode, ResolveTask, ResolvedPackage,
9 Resolver, apply_peer_contexts, catalog, error, hoist_auto_installed_peers,
10 is_deprecation_allowed, is_supported,
11};
12use aube_lockfile::{DepType, DirectDep, LocalSource, LockedPackage, LockfileGraph};
13use aube_manifest::PackageJson;
14use aube_registry::Packument;
15use rustc_hash::{FxHashMap, FxHashSet};
16use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
17use std::sync::Arc;
18
19impl Resolver {
20 /// Resolve all dependencies from a package.json.
21 ///
22 /// Uses batch-parallel BFS: each "wave" drains the queue, identifies
23 /// uncached package names, fetches their packuments concurrently, then
24 /// processes the entire batch before starting the next wave.
25 pub async fn resolve(
26 &mut self,
27 manifest: &PackageJson,
28 existing: Option<&LockfileGraph>,
29 ) -> Result<LockfileGraph, Error> {
30 self.resolve_workspace(
31 &[(".".to_string(), manifest.clone())],
32 existing,
33 &HashMap::new(),
34 )
35 .await
36 }
37
38 /// Resolve all dependencies for a workspace (multiple importers).
39 ///
40 /// `manifests` is a list of (importer_path, PackageJson) — e.g. (".", root), ("packages/app", app).
41 /// `workspace_packages` maps package name → version. Used both for
42 /// explicit `workspace:` protocol resolution and for yarn/npm/bun
43 /// style linkage where a bare semver range on a workspace-package
44 /// name resolves to the local copy when its version satisfies the
45 /// range.
46 pub async fn resolve_workspace(
47 &mut self,
48 manifests: &[(String, PackageJson)],
49 existing: Option<&LockfileGraph>,
50 workspace_packages: &HashMap<String, String>,
51 ) -> Result<LockfileGraph, Error> {
52 let resolve_start = std::time::Instant::now();
53 let mut packument_fetch_count = 0u32;
54 let mut packument_fetch_time = std::time::Duration::ZERO;
55 let mut lockfile_reuse_count = 0u32;
56 let mut resolved: BTreeMap<String, LockedPackage> = BTreeMap::new();
57 let mut resolved_versions: FxHashMap<String, Vec<String>> = FxHashMap::default();
58 let mut importers: BTreeMap<String, Vec<DirectDep>> = BTreeMap::new();
59 let mut queue: VecDeque<ResolveTask> = VecDeque::new();
60 let mut visited: FxHashSet<std::sync::Arc<str>> = FxHashSet::default();
61 // Round-tripped to the lockfile's top-level `time:` block so
62 // subsequent installs can reuse them for the cutoff computation.
63 // Populated opportunistically from whatever packuments we fetch:
64 // empty when the metadata omits `time` (corgi from npmjs.org in
65 // default mode), filled when it doesn't (Verdaccio, or the
66 // full-packument path taken for time-based resolution and
67 // `minimumReleaseAge`). This matches pnpm's `publishedAt` wiring.
68 let mut resolved_times: BTreeMap<String, String> = BTreeMap::new();
69 // Per-importer record of optionals the resolver intentionally
70 // dropped on this run — either filtered by os/cpu/libc or
71 // named in `pnpm.ignoredOptionalDependencies`. Round-tripped
72 // through the lockfile so drift detection on subsequent
73 // installs can distinguish "previously skipped" from "newly
74 // added by the user".
75 let mut skipped_optional_dependencies: BTreeMap<String, BTreeMap<String, String>> =
76 BTreeMap::new();
77 // Catalog picks gathered as the BFS rewrites `catalog:` task
78 // ranges. Outer key: catalog name. Inner: package name → spec.
79 // Resolved versions are filled in post-resolution by walking
80 // `resolved_versions` for the spec, since the picked version is
81 // an output the BFS doesn't know until version_satisfies fires.
82 let mut catalog_picks: BTreeMap<String, BTreeMap<String, String>> = BTreeMap::new();
83 let importer_declared_dep_names: BTreeMap<String, BTreeSet<String>> = manifests
84 .iter()
85 .map(|(importer_path, manifest)| {
86 let names = manifest
87 .dependencies
88 .keys()
89 .chain(manifest.dev_dependencies.keys())
90 .chain(manifest.optional_dependencies.keys())
91 .cloned()
92 .collect();
93 (importer_path.clone(), names)
94 })
95 .collect();
96 // ISO-8601 UTC cutoff string. npm's registry `time` map uses
97 // `Z`-suffixed UTC timestamps throughout, which sort
98 // lexicographically — so a raw `String` doubles as a
99 // comparable instant without pulling in a date library.
100 //
101 // Two independent features feed this cutoff:
102 // - `minimum_release_age` (pnpm v11 default, supply-chain
103 // mitigation): seeded *before* wave 0 so even direct deps
104 // are filtered. The exclude list and strict-mode behavior
105 // are scoped per-package by `pick_version` below.
106 // - `resolution-mode=time-based`: derived from the max
107 // publish time across direct deps once wave 0 finishes,
108 // then constrains transitives only.
109 // When both are configured, the resolver carries both cutoffs
110 // and the picker takes the more restrictive (earlier) one.
111 let mut published_by: Option<String> =
112 self.minimum_release_age.as_ref().and_then(|m| m.cutoff());
113 if let Some(c) = published_by.as_deref() {
114 tracing::debug!("minimumReleaseAge cutoff: {}", c);
115 }
116
117 seed_direct_deps(
118 manifests,
119 &self.ignored_optional_dependencies,
120 &mut queue,
121 &mut importers,
122 );
123
124 // Pipelined resolver state. The resolver is strictly serial in
125 // its *processing* order (tasks are popped and version-picked
126 // in seed/BFS order, which is what keeps the output lockfile
127 // byte-deterministic across runs) but fetches run freely in
128 // the background via `in_flight`. When a popped task's
129 // packument isn't in the cache, the main loop waits inline on
130 // `in_flight.join_next()` — harvesting whatever other fetches
131 // happen to land in the meantime — until this task's
132 // packument is available. Because `ensure_fetch!` is called
133 // speculatively at every enqueue site, by the time a task is
134 // popped its packument is usually already cached, so the
135 // wait is short.
136 let shared_semaphore = Arc::new(tokio::sync::Semaphore::new(
137 self.packument_network_concurrency.unwrap_or(64),
138 ));
139 // Time-based mode and `minimumReleaseAge` both need the
140 // packument's `time:` map. The abbreviated (corgi) response
141 // omits `time` by default, so we normally fall back to the
142 // full packument. `registry-supports-time-field=true` flips
143 // that: the user is asserting the configured registry ships
144 // `time` in corgi too (Verdaccio 5.15.1+, JSR, etc.), so the
145 // cheaper abbreviated path stays on the hot path and we save
146 // one full-packument fetch per distinct package.
147 let needs_time = (self.resolution_mode == ResolutionMode::TimeBased
148 || self.minimum_release_age.is_some()
149 || self.dependency_policy.trust_policy == crate::TrustPolicy::NoDowngrade)
150 && !self.registry_supports_time_field;
151 // When time data is required, fetch the full packument directly.
152 // The previous corgi-first shortcut saved bytes for old packages
153 // but cost an extra round trip for active packages whose top-level
154 // `modified` timestamp was newer than the cutoff. Clean installs of
155 // modern dependency graphs are dominated by those active packages.
156
157 // In-flight packument fetches. The spawned task returns the
158 // `(name, packument)` tuple so `join_next` gives us back the
159 // identity of whichever fetch landed next without a side
160 // table lookup.
161 #[allow(clippy::type_complexity)]
162 let mut in_flight: tokio::task::JoinSet<Result<(String, Packument), Error>> =
163 tokio::task::JoinSet::new();
164 // Names whose fetch has been spawned but not yet harvested.
165 // Dedupes spawn calls when multiple tasks discover the same
166 // transitive before any of them has been processed.
167 let mut in_flight_names: FxHashSet<String> = FxHashSet::default();
168 // TimeBased wave-0 gate: the publish-time cutoff is derived
169 // from the direct deps' resolved versions, so transitives
170 // that reach the version-pick step before all directs have
171 // completed must wait. Populated only when
172 // `cutoff_pending == true` (TimeBased mode); `Highest` mode
173 // leaves these at their defaults and the gate is a no-op.
174 let mut direct_deps_pending: usize = queue.len();
175 let mut cutoff_pending = self.resolution_mode == ResolutionMode::TimeBased;
176 let mut deferred_transitives: Vec<ResolveTask> = Vec::new();
177
178 // Set of names present in the existing lockfile. Used as a
179 // prefetch gate: names the lockfile already covers will hit
180 // the lockfile-reuse path and don't need their packuments
181 // fetched, so prefetching them is wasted tokio-spawn
182 // overhead. Load-bearing for `aube add` and
183 // frozen-lockfile-install scenarios where most tasks go
184 // through lockfile-reuse.
185 //
186 // This is strictly a *prefetch* gate, not a correctness
187 // gate: a task that fails sibling dedupe AND lockfile reuse
188 // (because its range doesn't match any of the lockfile's
189 // versions for that name) still needs a fresh fetch, and
190 // the wait-for-fetch loop below calls `ensure_fetch!`
191 // without consulting `existing_names`.
192 // Borrow names from `existing` instead of cloning. The set
193 // lives only inside `Resolver::resolve` and the prior
194 // lockfile graph outlives it. Skips 5000 String allocations
195 // on a 5000-pkg lockfile at resolve-entry.
196 let existing_names: FxHashSet<&str> = existing
197 .map(|g| g.packages.values().map(|p| p.name.as_str()).collect())
198 .unwrap_or_default();
199
200 // Spawn a packument fetch into `in_flight` if one isn't
201 // already running for `name` and the packument isn't
202 // already cached. Gated *only* on in-flight + cache —
203 // callers that want to skip prefetching names already
204 // covered by the lockfile check `existing_names` explicitly
205 // before invoking the macro.
206 macro_rules! ensure_fetch {
207 ($name:expr) => {{
208 let name: &str = $name;
209 if !in_flight_names.contains(name) && !self.cache.contains_key(name) {
210 let name_owned = name.to_string();
211 in_flight_names.insert(name_owned.clone());
212 let client = self.client.clone();
213 let cache_dir = self.packument_cache_dir.clone();
214 let full_cache_dir = self.packument_full_cache_dir.clone();
215 let minimum_release_age_excludes_name = self
216 .minimum_release_age
217 .as_ref()
218 .is_some_and(|mra| mra.exclude.contains(name));
219 let primer_covers_cutoff = minimum_release_age_excludes_name
220 || published_by
221 .as_deref()
222 .is_none_or(crate::primer::covers_cutoff);
223 let use_metadata_primer = (self.force_metadata_primer
224 || client.uses_default_npm_registry_for(&name_owned))
225 && primer_covers_cutoff;
226 let force_metadata_primer = self.force_metadata_primer;
227 let sem = shared_semaphore.clone();
228 in_flight.spawn(async move {
229 let _permit = sem
230 .acquire_owned()
231 .await
232 .map_err(|e| Error::Registry(name_owned.clone(), e.to_string()))?;
233 let mut cached = if needs_time {
234 match full_cache_dir.as_ref() {
235 Some(dir) => client.cached_full_packument_lookup(&name_owned, dir),
236 None => Default::default(),
237 }
238 } else if let Some(ref dir) = cache_dir {
239 client.cached_packument_lookup(&name_owned, dir)
240 } else {
241 Default::default()
242 };
243 if let Some(packument) = cached.packument.take() {
244 return Ok::<_, Error>((name_owned, packument));
245 }
246 if use_metadata_primer
247 && !cached.stale
248 && let Some(seed) = crate::primer::get(&name_owned)
249 {
250 let mut packument = seed.packument();
251 if force_metadata_primer {
252 for version in packument.versions.values_mut() {
253 let tarball =
254 client.tarball_url(&version.name, &version.version);
255 version.dist = version.dist.take().map(|mut dist| {
256 dist.tarball = tarball;
257 dist
258 });
259 }
260 }
261 if needs_time {
262 if let Some(dir) = full_cache_dir.as_ref() {
263 client.seed_full_packument_cache(
264 &name_owned,
265 dir,
266 &packument,
267 seed.etag.as_deref(),
268 seed.last_modified.as_deref(),
269 false,
270 );
271 }
272 } else if let Some(dir) = cache_dir.as_ref() {
273 client.seed_packument_cache(
274 &name_owned,
275 dir,
276 &packument,
277 seed.etag.as_deref(),
278 seed.last_modified.as_deref(),
279 false,
280 );
281 }
282 return Ok::<_, Error>((name_owned, packument));
283 }
284 let packument = if needs_time {
285 match full_cache_dir.as_ref() {
286 Some(dir) => {
287 client
288 .fetch_packument_with_time_cached_after_lookup(
289 &name_owned,
290 dir,
291 cached,
292 )
293 .await
294 }
295 None => client.fetch_packument(&name_owned).await,
296 }
297 } else if let Some(ref dir) = cache_dir {
298 client
299 .fetch_packument_cached_after_lookup(&name_owned, dir, cached)
300 .await
301 } else {
302 client.fetch_packument(&name_owned).await
303 }
304 .map_err(|e| Error::Registry(name_owned.clone(), e.to_string()))?;
305 Ok::<_, Error>((name_owned, packument))
306 });
307 }
308 }};
309 }
310
311 // Decrement the pending-directs counter when a root task
312 // reaches a terminal state. Used by the TimeBased cutoff
313 // trigger at the top of the outer loop.
314 macro_rules! note_root_done {
315 () => {
316 if direct_deps_pending > 0 {
317 direct_deps_pending -= 1;
318 }
319 };
320 }
321
322 // `(name, range)` is safe to speculatively prefetch against
323 // the registry when:
324 //
325 // - The range isn't a protocol we rewrite in preprocessing
326 // (`workspace:` / `catalog:` / `npm:` alias) — for those
327 // we don't know the real package name yet, so fetching
328 // the raw task name is either useless (preprocessing
329 // won't go through the registry at all) or wrong (we'd
330 // fetch the alias key instead of the real package).
331 // - The range isn't a `file:` / `link:` / `git:` /
332 // remote-tarball spec (covered by
333 // `is_non_registry_specifier`).
334 // - The name isn't in the overrides map — an override can
335 // rewrite the range into any of the above, and we can't
336 // cheaply tell whether it will, so be conservative.
337 //
338 // Called both from the upfront prefetch loop over seeded
339 // root deps *and* from the three transitive-enqueue sites
340 // inside the version-pick body, where the same class of
341 // unsafe specs can arrive via a published package's
342 // `dependencies` / `optionalDependencies` / `peerDependencies`
343 // maps (real-world case: a package whose dependency entry
344 // is an npm alias).
345 macro_rules! prefetchable {
346 ($name:expr, $range:expr) => {{
347 let r: &str = $range;
348 let n: &str = $name;
349 // A bare semver range that matches a workspace package
350 // will resolve to the workspace without ever reading
351 // the packument, so prefetching would just be a
352 // speculative 404 on e.g. an unpublished monorepo
353 // package.
354 let workspace_hit = workspace_packages
355 .get(n)
356 .is_some_and(|ws_v| version_satisfies(ws_v, r));
357 !aube_util::pkg::is_workspace_spec(r)
358 && !aube_util::pkg::is_catalog_spec(r)
359 && !aube_util::pkg::is_npm_spec(r)
360 && !aube_util::pkg::is_jsr_spec(r)
361 && !is_non_registry_specifier(r)
362 && !self.overrides.contains_key(n)
363 && !workspace_hit
364 }};
365 }
366
367 // Fire prefetches for every seeded root dep up front, so
368 // their packuments are already in flight by the time the
369 // first task is popped. Skip lockfile-covered names —
370 // they'll hit the lockfile-reuse path and never need their
371 // packuments — and anything `prefetchable!` rejects.
372 for task in queue.iter() {
373 if !prefetchable!(task.name.as_str(), task.range.as_str()) {
374 continue;
375 }
376 if existing_names.contains(task.name.as_str()) {
377 continue;
378 }
379 ensure_fetch!(&task.name);
380 }
381
382 'outer: loop {
383 // TimeBased cutoff trigger. Fires the first time
384 // `direct_deps_pending` hits zero with the cutoff still
385 // pending — at which point every direct dep has been
386 // version-picked (or terminated in preprocessing),
387 // `resolved_times` holds their publish times, and we can
388 // derive the max to seed `published_by` for the
389 // transitives we deferred.
390 if cutoff_pending && direct_deps_pending == 0 {
391 let direct_dep_paths: FxHashSet<&String> = importers
392 .values()
393 .flat_map(|deps| deps.iter().map(|d| &d.dep_path))
394 .collect();
395 let mut max_time: Option<&String> = None;
396 for (dep_path, t) in resolved_times.iter() {
397 if !direct_dep_paths.contains(dep_path) {
398 continue;
399 }
400 if max_time.map(|m| t > m).unwrap_or(true) {
401 max_time = Some(t);
402 }
403 }
404 if let Some(existing_graph) = existing {
405 for (dep_path, t) in &existing_graph.times {
406 if !direct_dep_paths.contains(dep_path) {
407 continue;
408 }
409 if max_time.map(|m| t > m).unwrap_or(true) {
410 max_time = Some(t);
411 }
412 }
413 }
414 if let Some(m) = max_time {
415 tracing::debug!("time-based resolution cutoff: {}", m);
416 published_by = Some(match published_by.take() {
417 Some(existing) if existing.as_str() < m.as_str() => existing,
418 _ => m.clone(),
419 });
420 }
421 cutoff_pending = false;
422 queue.extend(deferred_transitives.drain(..));
423 }
424
425 let Some(mut task) = queue.pop_front() else {
426 if !deferred_transitives.is_empty() {
427 return Err(Error::Registry(
428 "(resolver)".to_string(),
429 format!(
430 "{} transitives still deferred when resolve completed",
431 deferred_transitives.len()
432 ),
433 ));
434 }
435 break 'outer;
436 };
437
438 // Body of the former per-task preprocessing loop.
439 // The old wave-based code split this into a
440 // preprocessing pass and a post-fetch version-pick
441 // pass with a fetch barrier between them. Here both
442 // passes run inline for a single task: preprocess →
443 // sibling dedupe → lockfile reuse → wait on this
444 // task's packument → version-pick → enqueue
445 // transitives. The bare block keeps the original
446 // indentation so the diff stays readable against the
447 // prior shape; `continue` inside it still continues
448 // the 'outer loop because a bare block is not itself
449 // a loop.
450 {
451 // Apply bare-name overrides + npm-alias rewrites in a
452 // small fixed-point loop. Two interleavings need to
453 // work simultaneously:
454 // 1. The override *value* is itself a `npm:` alias
455 // (e.g. `"foo": "npm:bar@^2"`). The first override
456 // pass rewrites `task.range`; the alias pass then
457 // rewrites `task.name` to `bar`.
458 // 2. The user's *declared dep* is an `npm:` alias
459 // (e.g. `"foo": "npm:bar@^1"`) and the override
460 // targets the real package (`"overrides":
461 // {"bar": "2.0.0"}`). The first override pass
462 // misses (`task.name` is still `foo`), the alias
463 // pass rewrites `task.name = "bar"`, and the
464 // second override pass catches it.
465 // A two-iteration cap is enough — after one alias
466 // rewrite the name is canonical, and an override that
467 // points at a third package is itself constrained by
468 // the same rule, so there's no infinite chain.
469 //
470 // We deliberately don't touch `original_specifier`,
471 // since the lockfile/importer record should still
472 // reflect what the user wrote in package.json —
473 // overrides are a graph-shaping rule, not a rewrite of
474 // the user's declared deps.
475 // Catalog protocol: rewrite `catalog:` and
476 // `catalog:<name>` to the workspace catalog's actual
477 // range *before* the override loop, so overrides can
478 // still target a catalog dep by bare name. The original
479 // `catalog:...` text stays in `original_specifier` so
480 // the lockfile importer keeps the catalog reference and
481 // drift detection works.
482 if let Some((catalog_name, real_range)) =
483 self.resolve_catalog_spec(&task.name, &task.range)?
484 {
485 tracing::trace!("catalog: {} {} -> {}", task.name, task.range, real_range);
486 catalog_picks
487 .entry(catalog_name)
488 .or_default()
489 .insert(task.name.clone(), real_range.clone());
490 task.range = real_range;
491 }
492
493 for _ in 0..2 {
494 let mut changed = false;
495 if let Some(override_spec) = pick_override_spec(
496 &self.override_rules,
497 &task.name,
498 &task.range,
499 &task.ancestors,
500 ) {
501 // pnpm's removal marker: an override value of
502 // `"-"` drops the dep edge entirely. Skip before
503 // catalog/alias rewrites so `-` never reaches
504 // the registry resolver. The dropped edge never
505 // gets written to the parent's `.dependencies`
506 // map (that write happens downstream) and, for
507 // direct deps, never gets pushed into the
508 // importer's direct-dep list.
509 if override_spec == "-" {
510 tracing::trace!("override: {}@{} -> dropped", task.name, task.range,);
511 if task.is_root {
512 note_root_done!();
513 }
514 continue 'outer;
515 }
516 // An override may itself point at a catalog
517 // entry (e.g. `"overrides": {"foo": "catalog:"}`).
518 // The catalog pre-pass above already ran against
519 // the original range, so resolve the indirection
520 // here before assigning — otherwise `catalog:`
521 // leaks through to the registry resolver.
522 // Stash the catalog pick in a local so we only
523 // record it if the override actually moves
524 // `task.range`.
525 let (effective_spec, pending_pick) =
526 match self.resolve_catalog_spec(&task.name, &override_spec)? {
527 Some((catalog_name, real_range)) => {
528 (real_range.clone(), Some((catalog_name, real_range)))
529 }
530 None => (override_spec, None),
531 };
532 if task.range != effective_spec {
533 if let Some((catalog_name, real_range)) = pending_pick {
534 catalog_picks
535 .entry(catalog_name)
536 .or_default()
537 .insert(task.name.clone(), real_range);
538 }
539 tracing::trace!(
540 "override: {}@{} -> {}",
541 task.name,
542 task.range,
543 effective_spec
544 );
545 task.range = effective_spec;
546 // If the override replaced the spec with a
547 // bare range (not itself an `npm:` / `jsr:`
548 // alias), it's targeting `task.name` —
549 // implicitly undoing any prior alias
550 // rewrite. Without this, an override that
551 // fires after a catalog-aliased entry
552 // (e.g. catalog `js-yaml:
553 // npm:@zkochan/js-yaml@0.0.11`, override
554 // `js-yaml@<3.14.2: ^3.14.2`) would keep
555 // `task.real_name = @zkochan/js-yaml` and
556 // try to fetch `^3.14.2` from a packument
557 // that only carries `0.0.x`. If the
558 // override's value is itself an alias, the
559 // alias pass below picks up the new target
560 // on the next loop iteration.
561 if task.real_name.is_some()
562 && !task.range.starts_with("npm:")
563 && !task.range.starts_with("jsr:")
564 {
565 task.real_name = None;
566 }
567 changed = true;
568 }
569 }
570 if let Some(rest) = task.range.strip_prefix("npm:")
571 && let Some(at_idx) = rest.rfind('@')
572 {
573 let real_name = rest[..at_idx].to_string();
574 let real_range = rest[at_idx + 1..].to_string();
575 // Keep `task.name` as the user-facing alias
576 // (the key the package.json used) and stash
577 // the registry name on `real_name` so every
578 // identity-facing site — dep_path formation,
579 // direct-dep records, parent wiring — sees
580 // the alias, while only packument/tarball
581 // fetch sites (via `task.registry_name()`)
582 // hit the real package. Overwriting
583 // `task.name` here would collapse
584 // `node_modules/h3-v2/` to `node_modules/h3/`
585 // and any `require("h3-v2")` would break.
586 if task.real_name.as_deref() != Some(real_name.as_str())
587 || real_range != task.range
588 {
589 tracing::trace!(
590 "npm alias: {} -> {}@{}",
591 task.name,
592 real_name,
593 real_range
594 );
595 task.real_name = Some(real_name);
596 task.range = real_range;
597 changed = true;
598 }
599 }
600 // `jsr:<range>` and `jsr:<@scope/name>[@<range>]` both
601 // land here. JSR's npm-compat endpoint serves every
602 // package under `@jsr/<scope>__<name>`, but the
603 // user-facing dependency name stays the JSR name (or
604 // explicit alias) from package.json. Keep `task.name`
605 // unchanged for dep_path/importer/link identity and
606 // stash the npm-compat name in `real_name`, matching
607 // the npm-alias path above. Only registry IO should
608 // see `@jsr/...`.
609 if let Some(rest) = task.range.strip_prefix("jsr:") {
610 let (jsr_name_raw, jsr_range) = if let Some(body) = rest.strip_prefix('@') {
611 match body.rfind('@') {
612 Some(rel_at) => {
613 // Indices are relative to `body`; add 1 for
614 // the `@` we just stripped so we can slice
615 // against the original `rest`.
616 let at_idx = rel_at + 1;
617 (rest[..at_idx].to_string(), rest[at_idx + 1..].to_string())
618 }
619 None => (rest.to_string(), "latest".to_string()),
620 }
621 } else {
622 // Bare range form — the manifest key carries the
623 // JSR name (e.g. `"@std/collections": "jsr:^1"`).
624 (task.name.clone(), rest.to_string())
625 };
626 match aube_registry::jsr::jsr_to_npm_name(&jsr_name_raw) {
627 Some(npm_name) => {
628 if task.real_name.as_deref() != Some(npm_name.as_str())
629 || jsr_range != task.range
630 {
631 tracing::trace!(
632 "jsr: {} -> {}@{}",
633 task.name,
634 npm_name,
635 jsr_range,
636 );
637 task.real_name = Some(npm_name);
638 task.range = jsr_range;
639 changed = true;
640 }
641 }
642 None => {
643 return Err(Error::Registry(
644 task.name.clone(),
645 format!(
646 "invalid jsr: spec `{}` — expected `jsr:@scope/name[@range]`",
647 task.range,
648 ),
649 ));
650 }
651 }
652 }
653 if !changed {
654 break;
655 }
656 }
657
658 // Handle file: / link: / git: protocols — the dep points
659 // at a path on disk or a remote git repo rather than a
660 // registry package. Only valid on root deps; a nested
661 // package.json that declares its own `file:` dep silently
662 // falls through to the normal resolver path and fails
663 // loudly there.
664 if is_non_registry_specifier(&task.range) {
665 if should_block_exotic_subdep(
666 &task,
667 &resolved,
668 self.dependency_policy.block_exotic_subdeps,
669 ) {
670 return Err(Error::BlockedExoticSubdep(Box::new(ExoticSubdepDetails {
671 name: task.name.clone(),
672 spec: task.range.clone(),
673 parent: task
674 .parent
675 .clone()
676 .unwrap_or_else(|| "<unknown>".to_string()),
677 ancestors: task.ancestors.clone(),
678 importer: task.importer.clone(),
679 })));
680 }
681 let importer_root = if task.importer == "." {
682 self.project_root.clone()
683 } else {
684 self.project_root.join(&task.importer)
685 };
686 let Some(raw_local) = LocalSource::parse(&task.range, &importer_root) else {
687 return Err(Error::Registry(
688 task.name.clone(),
689 format!("unparseable local specifier: {}", task.range),
690 ));
691 };
692 // For git sources we have to talk to the remote
693 // right now so the resolver can (a) pin the
694 // committish to a full SHA for the lockfile and
695 // (b) read the cloned repo's `package.json` for
696 // transitive deps. `resolve_git_source` does the
697 // `ls-remote` + shallow clone dance and returns a
698 // `LocalSource::Git` with `resolved` populated,
699 // plus the manifest tuple the rest of the branch
700 // already expects.
701 if !task.is_root
702 && !matches!(
703 raw_local,
704 LocalSource::Git(_) | LocalSource::RemoteTarball(_)
705 )
706 {
707 return Err(Error::Registry(
708 task.name.clone(),
709 format!(
710 "transitive local specifier {} cannot be resolved without the parent package source root",
711 task.range
712 ),
713 ));
714 }
715 let (local, real_version, target_deps) = if let LocalSource::Git(ref g) =
716 raw_local
717 {
718 let shallow = aube_store::git_host_in_list(&g.url, &self.git_shallow_hosts);
719 let (resolved_local, version, deps) =
720 resolve_git_source(&task.name, g, shallow, Some(self.client.as_ref()))
721 .await
722 .map_err(|e| {
723 Error::Registry(
724 task.name.clone(),
725 format!("git resolve {}: {e}", task.range),
726 )
727 })?;
728 (resolved_local, version, deps)
729 } else if let LocalSource::RemoteTarball(ref t) = raw_local {
730 let (resolved_local, version, deps) =
731 resolve_remote_tarball(&task.name, t, self.client.as_ref())
732 .await
733 .map_err(|e| {
734 Error::Registry(
735 task.name.clone(),
736 format!("remote tarball {}: {e}", task.range),
737 )
738 })?;
739 (resolved_local, version, deps)
740 } else {
741 // Rewrite the path to be relative to the
742 // project root so every downstream consumer
743 // can resolve it with a single
744 // `project_root.join(rel)`.
745 let local = rebase_local(&raw_local, &importer_root, &self.project_root);
746 let (_target_name, version, deps) =
747 read_local_manifest(&raw_local, &importer_root).unwrap_or_else(|_| {
748 (task.name.clone(), "0.0.0".to_string(), BTreeMap::new())
749 });
750 (local, version, deps)
751 };
752 let dep_path = local.dep_path(&task.name);
753 let linked_name = task.name.clone();
754
755 if task.is_root
756 && let Some(deps) = importers.get_mut(&task.importer)
757 {
758 deps.push(DirectDep {
759 name: task.name.clone(),
760 dep_path: dep_path.clone(),
761 dep_type: task.dep_type,
762 specifier: task.original_specifier.clone(),
763 });
764 }
765
766 // Wire parent -> this exotic transitive. Without
767 // this, the parent snapshot's `dependencies` map
768 // omits the git/url/file subdep entirely, so the
769 // linker never creates the sibling symlink inside
770 // the parent's node_modules and the package fails
771 // to resolve at runtime. The value is the dep_path
772 // tail (e.g. `git+<hash>`) so the linker can
773 // reconstruct the full dep_path by concatenating
774 // `{name}@{value}` — matching the key format used
775 // when inserting the resolved package below.
776 if let Some(ref parent_dp) = task.parent
777 && let Some(parent_pkg) = resolved.get_mut(parent_dp)
778 {
779 // `local.dep_path(name)` always returns
780 // `{name}@{tail}`; if that invariant ever
781 // breaks we'd silently store a malformed dep
782 // value that the pnpm writer would emit as-is.
783 let name_prefix = format!("{}@", task.name);
784 debug_assert!(
785 dep_path.starts_with(&name_prefix),
786 "local.dep_path returned {dep_path:?} without expected prefix {name_prefix:?}"
787 );
788 let dep_tail = dep_path
789 .strip_prefix(&name_prefix)
790 .unwrap_or(&dep_path)
791 .to_string();
792 parent_pkg
793 .dependencies
794 .insert(task.name.clone(), dep_tail.clone());
795 if task.dep_type == DepType::Optional {
796 parent_pkg
797 .optional_dependencies
798 .insert(task.name.clone(), dep_tail);
799 }
800 }
801
802 if visited.insert(std::sync::Arc::from(dep_path.as_str())) {
803 resolved.insert(
804 dep_path.clone(),
805 LockedPackage {
806 name: linked_name.clone(),
807 version: real_version.clone(),
808 dep_path: dep_path.clone(),
809 local_source: Some(local.clone()),
810 ..Default::default()
811 },
812 );
813 if let Some(ref tx) = self.resolved_tx {
814 let _ = tx
815 .send(ResolvedPackage {
816 dep_path: dep_path.clone(),
817 name: linked_name.clone(),
818 version: real_version.clone(),
819 integrity: None,
820 tarball_url: None,
821 // local_source deps aren't aliased —
822 // `file:`/`link:` specifiers go
823 // through the local-source branch,
824 // not the `npm:` rewrite.
825 alias_of: None,
826 local_source: Some(local.clone()),
827 // Local `file:`/`link:` packages never
828 // carry npm-style platform constraints
829 // — they're whatever the user points
830 // at, so the fetch coordinator treats
831 // them as unconstrained (always fetch).
832 os: aube_lockfile::PlatformList::new(),
833 cpu: aube_lockfile::PlatformList::new(),
834 libc: aube_lockfile::PlatformList::new(),
835 deprecated: None,
836 })
837 .await;
838 }
839 // Enqueue transitive deps of the local package
840 // (directories + tarballs only — `link:` deps
841 // are fully the target's responsibility).
842 if !matches!(local, LocalSource::Link(_)) {
843 let mut child_ancestors = task.ancestors.clone();
844 child_ancestors.push((linked_name.clone(), real_version.clone()));
845 for (child_name, child_range) in target_deps {
846 queue.push_back(ResolveTask::transitive(
847 child_name,
848 child_range,
849 DepType::Production,
850 dep_path.clone(),
851 task.importer.clone(),
852 child_ancestors.clone(),
853 ));
854 }
855 }
856 }
857 if task.is_root {
858 note_root_done!();
859 }
860 continue;
861 }
862
863 // Handle workspace linkage. Two cases resolve to the
864 // workspace package rather than the registry:
865 // 1. Explicit `workspace:` protocol (pnpm/yarn-berry
866 // style). The range after the prefix is accepted
867 // unconditionally — the user asserted this should
868 // link.
869 // 2. Bare semver range whose name matches a workspace
870 // package whose version satisfies the range. This
871 // is the yarn-v1 / npm / bun default: siblings pin
872 // each other with normal version strings and
873 // expect the workspace to win over the registry.
874 // A workspace is typically either unpublished or
875 // is itself the source of truth for its name, so
876 // preferring the local copy matches every other
877 // mainstream pm.
878 if let Some(ws_version) = workspace_packages.get(&task.name)
879 && (match task.range.strip_prefix("workspace:") {
880 // workspace:*, workspace:^, workspace:~
881 // bind to whatever local workspace version is.
882 // These are pnpm's "don't pin me, just track
883 // local" sigils. Match them before range check.
884 Some("" | "*" | "^" | "~") => true,
885 // workspace:<range> like workspace:^2.0.0 or
886 // workspace:1.x. Must still satisfy local
887 // version. Before this fix, any workspace:
888 // prefix short-circuited. Consumer could pin
889 // workspace:^2 against local 1.0.0 and aube
890 // would silently link the wrong version.
891 // pnpm errors here with no-matching-version.
892 Some(rest) => version_satisfies(ws_version, rest),
893 // Bare semver (no workspace: prefix) path.
894 // Linker walks up to workspace yarn-v1 style.
895 // Special case `*` and `""` (bare catch-all)
896 // to always match the workspace copy, even
897 // when the ws version is a prerelease like
898 // `0.0.0-0` which semver strict rules would
899 // otherwise exclude. Placeholder versions
900 // are common in fresh changesets-managed
901 // workspaces and would silently fall through
902 // to registry resolution otherwise, picking
903 // up a stale published build instead of the
904 // local source.
905 None if task.range.is_empty() || task.range == "*" => true,
906 None => version_satisfies(ws_version, &task.range),
907 })
908 {
909 let dep_path = dep_path_for(&task.name, ws_version);
910 if task.is_root
911 && let Some(deps) = importers.get_mut(&task.importer)
912 {
913 deps.push(DirectDep {
914 name: task.name.clone(),
915 dep_path: dep_path.clone(),
916 dep_type: task.dep_type,
917 specifier: task.original_specifier.clone(),
918 });
919 }
920 if let Some(ref parent_dp) = task.parent
921 && let Some(parent_pkg) = resolved.get_mut(parent_dp)
922 {
923 parent_pkg
924 .dependencies
925 .insert(task.name.clone(), ws_version.clone());
926 if task.dep_type == DepType::Optional {
927 parent_pkg
928 .optional_dependencies
929 .insert(task.name.clone(), ws_version.clone());
930 }
931 }
932 if task.is_root {
933 note_root_done!();
934 }
935 continue;
936 }
937
938 // Sibling dedupe. If another task for this same name
939 // has already settled on a version that satisfies
940 // this task's range, wire up to that resolution and
941 // short-circuit. In the old wave code this check
942 // lived in the post-fetch loop as `existing_match`;
943 // in the pipelined loop we run it up front so
944 // dedupable tasks never block on a fetch or a
945 // lockfile scan.
946 if let Some(matched_ver) = resolved_versions.get(&task.name).and_then(|versions| {
947 versions
948 .iter()
949 .find(|v| {
950 version_satisfies(v, &task.range)
951 && !is_vulnerable(task.registry_name(), v, &self.vulnerable_ranges)
952 })
953 .cloned()
954 }) {
955 let dep_path = dep_path_for(&task.name, &matched_ver);
956 if task.is_root
957 && let Some(deps) = importers.get_mut(&task.importer)
958 {
959 deps.push(DirectDep {
960 name: task.name.clone(),
961 dep_path: dep_path.clone(),
962 dep_type: task.dep_type,
963 specifier: task.original_specifier.clone(),
964 });
965 }
966 if let Some(ref parent_dp) = task.parent
967 && let Some(parent_pkg) = resolved.get_mut(parent_dp)
968 {
969 parent_pkg
970 .dependencies
971 .insert(task.name.clone(), matched_ver.clone());
972 if task.dep_type == DepType::Optional {
973 parent_pkg
974 .optional_dependencies
975 .insert(task.name.clone(), matched_ver);
976 }
977 }
978 if task.is_root {
979 note_root_done!();
980 }
981 continue;
982 }
983
984 // Lockfile reuse. Runs unconditionally after sibling
985 // dedupe fails — the old code gated this behind a
986 // `cache.contains_key` check, but in the pipelined
987 // loop the cache is populated incrementally and the
988 // gate was a false optimization.
989 {
990 if let Some(locked_pkg) = existing.and_then(|g| {
991 g.packages.values().find(|p| {
992 p.name == task.name
993 && version_satisfies(&p.version, &task.range)
994 && !is_vulnerable(
995 task.registry_name(),
996 &p.version,
997 &self.vulnerable_ranges,
998 )
999 })
1000 }) {
1001 // Drop optional deps whose platform constraints
1002 // don't match the active host / supported set.
1003 // This is the path that handles frozen/lockfile
1004 // installs on a different machine than the one
1005 // that wrote the lockfile.
1006 if task.dep_type == DepType::Optional
1007 && !is_supported(
1008 &locked_pkg.os,
1009 &locked_pkg.cpu,
1010 &locked_pkg.libc,
1011 &self.supported_architectures,
1012 )
1013 {
1014 tracing::debug!(
1015 "skipping optional dep {}@{}: platform mismatch",
1016 task.name,
1017 locked_pkg.version
1018 );
1019 if task.is_root
1020 && let Some(spec) = task.original_specifier.as_ref()
1021 {
1022 skipped_optional_dependencies
1023 .entry(task.importer.clone())
1024 .or_default()
1025 .insert(task.name.clone(), spec.clone());
1026 }
1027 if task.is_root {
1028 note_root_done!();
1029 }
1030 continue;
1031 }
1032 let version = locked_pkg.version.clone();
1033 let dep_path = dep_path_for(&task.name, &version);
1034
1035 if task.is_root
1036 && let Some(deps) = importers.get_mut(&task.importer)
1037 {
1038 deps.push(DirectDep {
1039 name: task.name.clone(),
1040 dep_path: dep_path.clone(),
1041 dep_type: task.dep_type,
1042 specifier: task.original_specifier.clone(),
1043 });
1044 }
1045 if let Some(ref parent_dp) = task.parent
1046 && let Some(parent_pkg) = resolved.get_mut(parent_dp)
1047 {
1048 parent_pkg
1049 .dependencies
1050 .insert(task.name.clone(), version.clone());
1051 if task.dep_type == DepType::Optional {
1052 parent_pkg
1053 .optional_dependencies
1054 .insert(task.name.clone(), version.clone());
1055 }
1056 }
1057 if visited.insert(std::sync::Arc::from(dep_path.as_str())) {
1058 resolved_versions
1059 .entry(task.name.clone())
1060 .or_default()
1061 .push(version.clone());
1062
1063 // Carry any round-tripped publish time
1064 // forward so (a) the cutoff computation at
1065 // the end of wave 0 can see reused directs
1066 // alongside freshly-resolved ones and
1067 // (b) the next lockfile write preserves the
1068 // existing `time:` entry even when this
1069 // install reuses the locked version without
1070 // re-fetching a packument.
1071 if self.should_record_times()
1072 && let Some(g) = existing
1073 && let Some(t) = g.times.get(&dep_path)
1074 {
1075 resolved_times.insert(dep_path.clone(), t.clone());
1076 }
1077
1078 if let Some(ref tx) = self.resolved_tx {
1079 let _ = tx
1080 .send(ResolvedPackage {
1081 dep_path: dep_path.clone(),
1082 name: task.name.clone(),
1083 version: version.clone(),
1084 integrity: locked_pkg.integrity.clone(),
1085 tarball_url: locked_pkg.tarball_url.clone(),
1086 // Carry the alias identity
1087 // through the reuse path — the
1088 // existing `locked_pkg` already
1089 // records it if the lockfile held
1090 // an aliased entry, so the
1091 // streaming fetch still hits the
1092 // real registry name.
1093 alias_of: locked_pkg.alias_of.clone(),
1094 local_source: locked_pkg.local_source.clone(),
1095 os: locked_pkg.os.clone(),
1096 cpu: locked_pkg.cpu.clone(),
1097 libc: locked_pkg.libc.clone(),
1098 // Lockfile reuse skips the packument
1099 // fetch, so we have no deprecation
1100 // message to forward here. The
1101 // `aube deprecations` command re-queries
1102 // packuments live for the
1103 // after-the-fact view.
1104 deprecated: None,
1105 })
1106 .await;
1107 }
1108
1109 // Carry declared peer deps forward from the
1110 // existing lockfile so subsequent peer-context
1111 // computation sees them without a re-fetch.
1112 resolved.insert(
1113 dep_path.clone(),
1114 LockedPackage {
1115 name: task.name.clone(),
1116 version: version.clone(),
1117 integrity: locked_pkg.integrity.clone(),
1118 dependencies: BTreeMap::new(),
1119 optional_dependencies: BTreeMap::new(),
1120 peer_dependencies: locked_pkg.peer_dependencies.clone(),
1121 peer_dependencies_meta: locked_pkg
1122 .peer_dependencies_meta
1123 .clone(),
1124 dep_path: dep_path.clone(),
1125 local_source: locked_pkg.local_source.clone(),
1126 os: locked_pkg.os.clone(),
1127 cpu: locked_pkg.cpu.clone(),
1128 libc: locked_pkg.libc.clone(),
1129 bundled_dependencies: locked_pkg.bundled_dependencies.clone(),
1130 optional: locked_pkg.optional,
1131 transitive_peer_dependencies: locked_pkg
1132 .transitive_peer_dependencies
1133 .clone(),
1134 tarball_url: locked_pkg.tarball_url.clone(),
1135 alias_of: locked_pkg.alias_of.clone(),
1136 yarn_checksum: locked_pkg.yarn_checksum.clone(),
1137 engines: locked_pkg.engines.clone(),
1138 bin: locked_pkg.bin.clone(),
1139 declared_dependencies: locked_pkg.declared_dependencies.clone(),
1140 license: locked_pkg.license.clone(),
1141 funding_url: locked_pkg.funding_url.clone(),
1142 extra_meta: locked_pkg.extra_meta.clone(),
1143 },
1144 );
1145
1146 // Enqueue transitive deps from the locked package.
1147 // Strip any peer-context suffix off the version
1148 // before treating it as a semver range — a
1149 // locked `"18.2.0(react@18.2.0)"` tail should
1150 // match against packuments as just `18.2.0`.
1151 // Also strip a leading `name@` if present:
1152 // bun/yarn parsers store transitive deps in
1153 // `name@version` (full dep_path) form, while
1154 // pnpm stores bare versions. Without the
1155 // strip, a yarn/bun-locked `is-odd` would
1156 // emit a transitive task for is-number with
1157 // range `"is-number@6.0.0"`, which doesn't
1158 // parse as semver and fails resolution.
1159 // The lockfile already omitted bundled dep
1160 // edges on write, so iterating
1161 // `locked_pkg.dependencies` naturally skips them.
1162 let mut child_ancestors = task.ancestors.clone();
1163 child_ancestors.push((task.name.clone(), version.clone()));
1164 for (dep_name, dep_version) in &locked_pkg.dependencies {
1165 let prefix = format!("{dep_name}@");
1166 let stripped =
1167 dep_version.strip_prefix(&prefix).unwrap_or(dep_version);
1168 let canonical_version =
1169 stripped.split('(').next().unwrap_or(stripped).to_string();
1170 let dep_type =
1171 if locked_pkg.optional_dependencies.contains_key(dep_name) {
1172 DepType::Optional
1173 } else {
1174 DepType::Production
1175 };
1176 queue.push_back(ResolveTask::transitive(
1177 dep_name.clone(),
1178 canonical_version,
1179 dep_type,
1180 dep_path.clone(),
1181 task.importer.clone(),
1182 child_ancestors.clone(),
1183 ));
1184 }
1185 }
1186 lockfile_reuse_count += 1;
1187 if task.is_root {
1188 note_root_done!();
1189 }
1190 continue;
1191 }
1192 }
1193
1194 // Packument not in cache. Spawn its fetch if one
1195 // isn't already running, then wait for packument
1196 // fetches to land until this task's packument is
1197 // available. Other fetches that happen to complete
1198 // while we're waiting get cached opportunistically,
1199 // which is exactly what lets the pipeline overlap
1200 // network and CPU: by the time a later task is
1201 // popped its packument is usually already sitting
1202 // in the cache because it landed while an earlier
1203 // task was being waited on.
1204 let wait_start = std::time::Instant::now();
1205 // Cache is keyed by the *registry* name — for aliased
1206 // tasks `task.name` is the user-facing alias (e.g.
1207 // `h3-v2`), which would never hit. `registry_name()`
1208 // returns the alias-resolved target (`h3`) on
1209 // aliased tasks and `task.name` otherwise.
1210 let fetch_name = task.registry_name().to_string();
1211 while !self.cache.contains_key(&fetch_name) {
1212 ensure_fetch!(&fetch_name);
1213 match in_flight.join_next().await {
1214 Some(Ok(Ok((name, packument)))) => {
1215 in_flight_names.remove(&name);
1216 self.cache.insert(name, packument);
1217 packument_fetch_count += 1;
1218 }
1219 Some(Ok(Err(e))) => return Err(e),
1220 Some(Err(join_err)) => {
1221 return Err(Error::Registry(
1222 "(join)".to_string(),
1223 join_err.to_string(),
1224 ));
1225 }
1226 None => {
1227 // ensure_fetch! guarantees something is
1228 // in flight if the cache still doesn't
1229 // hold this name, so a None here means
1230 // the spawn failed silently. Surface it.
1231 return Err(Error::Registry(
1232 fetch_name.clone(),
1233 "packument fetch disappeared before completing".to_string(),
1234 ));
1235 }
1236 }
1237 }
1238 packument_fetch_time += wait_start.elapsed();
1239
1240 // TimeBased wave-0 gate. Transitives that reach
1241 // the version-pick step while the cutoff is still
1242 // unknown must wait until the direct deps have
1243 // been picked and the cutoff has been derived;
1244 // otherwise they'd pick against a `None` cutoff
1245 // and miss the filter. In `Highest` mode (the
1246 // default), `cutoff_pending` starts false and this
1247 // is a no-op.
1248 if cutoff_pending && !task.is_root {
1249 deferred_transitives.push(task);
1250 continue;
1251 }
1252
1253 // Version-pick + transitive enqueue. Was a separate
1254 // sub-loop over `processed_batch` in the old wave
1255 // code; here it's inline as the tail of the per-task
1256 // pipeline now that we know the packument is in
1257 // cache. `registry_name()` is the cache key for
1258 // aliased tasks (cache is populated under the real
1259 // registry name), so use the same accessor here.
1260 let packument = self.cache.get(task.registry_name()).ok_or_else(|| {
1261 Error::Registry(
1262 task.registry_name().to_string(),
1263 "packument not in cache".to_string(),
1264 )
1265 })?;
1266
1267 // Find locked version
1268 let locked_version = existing.and_then(|g| {
1269 g.packages
1270 .values()
1271 .find(|p| p.name == task.name && version_satisfies(&p.version, &task.range))
1272 .map(|p| p.version.as_str())
1273 .filter(|v| {
1274 !is_vulnerable(task.registry_name(), v, &self.vulnerable_ranges)
1275 })
1276 });
1277
1278 // Direct deps in time-based mode pick the lowest
1279 // satisfying version; everything else (transitives,
1280 // and all picks in Highest mode) picks highest.
1281 let pick_lowest = self.resolution_mode == ResolutionMode::TimeBased && task.is_root;
1282 // Apply the cutoff unless this package is on the
1283 // minimumReleaseAge exclude list. The exclude list only
1284 // suppresses the *minimumReleaseAge* leg, not the
1285 // time-based-mode leg — but since we collapse both
1286 // into the same `published_by` string at this point,
1287 // we have to skip the cutoff entirely for excluded
1288 // names. Acceptable: time-based mode and exclude
1289 // lists aren't expected to coexist in the wild.
1290 let cutoff_for_pkg = match self.minimum_release_age.as_ref() {
1291 Some(mra) if mra.exclude.contains(&task.name) => None,
1292 _ => published_by.as_deref(),
1293 };
1294 // Strict semantics in two cases:
1295 // - `minimumReleaseAgeStrict=true` (the user opted in
1296 // to hard failures), or
1297 // - the cutoff comes from `--resolution-mode=time-based`
1298 // alone, with no `minimumReleaseAge` configured. The
1299 // time-based cutoff is intended as a hard wall — if
1300 // no version fits, the *correct* fix is for the user
1301 // to update the lockfile, not for the resolver to
1302 // silently pick a different version.
1303 let strict = match self.minimum_release_age.as_ref() {
1304 Some(m) => m.strict,
1305 None => true,
1306 };
1307 let pick = pick_version(
1308 packument,
1309 &task.range,
1310 locked_version,
1311 pick_lowest,
1312 cutoff_for_pkg,
1313 strict,
1314 );
1315 let picked_ref = match pick {
1316 PickResult::Found(meta) => meta,
1317 // Only surface `AgeGate` when the cutoff actually
1318 // came from `minimumReleaseAge`. When it came from
1319 // `--resolution-mode=time-based` alone, the user
1320 // never opted into the supply-chain age gate, so
1321 // the failure should report as a plain no-match
1322 // instead of a misleading "older than 0 minutes".
1323 PickResult::AgeGated => match self.minimum_release_age.as_ref() {
1324 Some(mra) => {
1325 return Err(Error::AgeGate(Box::new(error::build_age_gate(
1326 &task,
1327 packument,
1328 mra.minutes,
1329 ))));
1330 }
1331 None => {
1332 return Err(Error::NoMatch(Box::new(error::build_no_match(
1333 &task, packument,
1334 ))));
1335 }
1336 },
1337 PickResult::NoMatch => {
1338 return Err(Error::NoMatch(Box::new(error::build_no_match(
1339 &task, packument,
1340 ))));
1341 }
1342 };
1343 let picked_ref = prefer_non_vulnerable_pick(
1344 task.registry_name(),
1345 packument,
1346 &task.range,
1347 picked_ref,
1348 pick_lowest,
1349 cutoff_for_pkg,
1350 &self.vulnerable_ranges,
1351 );
1352 // Trust-policy enforcement runs *before* any other
1353 // post-pick processing (mirrors pnpm's placement
1354 // immediately after `pickPackage`). Skip when policy is
1355 // off so the off-by-default case is a single enum
1356 // compare. The check needs the live packument's `time`
1357 // map and all version metadata, both of which are still
1358 // in scope here from L1191.
1359 if self.dependency_policy.trust_policy == crate::TrustPolicy::NoDowngrade {
1360 crate::trust::check_no_downgrade(
1361 packument,
1362 &picked_ref.version,
1363 picked_ref,
1364 &self.dependency_policy.trust_policy_exclude,
1365 self.dependency_policy.trust_policy_ignore_after,
1366 )
1367 .map_err(|e| match e {
1368 crate::trust::TrustCheckError::Downgrade(d) => {
1369 Error::TrustDowngrade(Box::new(d))
1370 }
1371 crate::trust::TrustCheckError::MissingTime(d) => {
1372 Error::TrustCheckMissingTime(Box::new(d))
1373 }
1374 })?;
1375 }
1376
1377 // Clone the picked metadata into an owned value so we can
1378 // both run the `readPackage` hook (which needs a
1379 // disjoint `&mut self` borrow) and, later, mutate the
1380 // resolver's own caches without holding a borrow into
1381 // `self.cache`. Also grab the publish-time entry now,
1382 // for the same reason.
1383 let mut picked_owned = picked_ref.clone();
1384 let picked_publish_time = packument.time.get(&picked_ref.version).cloned();
1385 // Skip the readPackage hook entirely for a `(name, version)`
1386 // pair we've already fully processed via a prior task. The
1387 // mutated dep maps only drive the transitive enqueue below,
1388 // and that block is short-circuited by the `visited` guard
1389 // later in this iteration — so running the hook here would
1390 // just burn an IPC round-trip whose result is discarded.
1391 let prehook_dep_path = dep_path_for(&task.name, &picked_ref.version);
1392 let already_visited = visited.contains(prehook_dep_path.as_str());
1393
1394 if !already_visited {
1395 apply_package_extensions(
1396 &mut picked_owned,
1397 &self.dependency_policy.package_extensions,
1398 );
1399 }
1400
1401 // readPackage hook. Runs at most once per version-picked
1402 // package, before transitive enqueue. We honor edits to
1403 // the four dep maps and warn on (then discard) edits to
1404 // name/version/dist/platform/`hasInstallScript` — pnpm
1405 // tolerates readPackage returning a hollowed-out
1406 // object, so we restore those fields from the original
1407 // packument entry after the call.
1408 if !already_visited && let Some(hook) = self.read_package_hook.as_mut() {
1409 let before_name = picked_owned.name.clone();
1410 let before_version = picked_owned.version.clone();
1411 let before_dist = picked_owned.dist.clone();
1412 let before_os = picked_owned.os.clone();
1413 let before_cpu = picked_owned.cpu.clone();
1414 let before_libc = picked_owned.libc.clone();
1415 let before_bundled = picked_owned.bundled_dependencies.clone();
1416 let before_has_install_script = picked_owned.has_install_script;
1417 let before_deprecated = picked_owned.deprecated.clone();
1418 let input = picked_owned.clone();
1419 let mut after = hook.read_package(input).await.map_err(|e| {
1420 Error::Registry(before_name.clone(), format!("readPackage hook: {e}"))
1421 })?;
1422 if after.name != before_name || after.version != before_version {
1423 tracing::warn!(
1424 "[pnpmfile] readPackage rewrote {}@{} identity to {}@{}; \
1425 aube ignores identity edits",
1426 before_name,
1427 before_version,
1428 after.name,
1429 after.version,
1430 );
1431 }
1432 after.name = before_name;
1433 after.version = before_version;
1434 after.dist = before_dist;
1435 after.os = before_os;
1436 after.cpu = before_cpu;
1437 after.libc = before_libc;
1438 after.bundled_dependencies = before_bundled;
1439 after.has_install_script = before_has_install_script;
1440 after.deprecated = before_deprecated;
1441 picked_owned = after;
1442 }
1443 let version_meta = &picked_owned;
1444
1445 // Optional deps that don't match the host platform get
1446 // silently dropped — pnpm parity. Required deps with a
1447 // bad platform still get installed; the warning matches
1448 // pnpm's `packageIsInstallable` behavior.
1449 let platform_ok = is_supported(
1450 &version_meta.os,
1451 &version_meta.cpu,
1452 &version_meta.libc,
1453 &self.supported_architectures,
1454 );
1455 if !platform_ok {
1456 if task.dep_type == DepType::Optional {
1457 tracing::debug!(
1458 "skipping optional dep {}@{}: unsupported platform (os={:?} cpu={:?} libc={:?})",
1459 task.name,
1460 version_meta.version,
1461 version_meta.os,
1462 version_meta.cpu,
1463 version_meta.libc
1464 );
1465 if task.is_root
1466 && let Some(spec) = task.original_specifier.as_ref()
1467 {
1468 skipped_optional_dependencies
1469 .entry(task.importer.clone())
1470 .or_default()
1471 .insert(task.name.clone(), spec.clone());
1472 }
1473 if task.is_root {
1474 note_root_done!();
1475 }
1476 continue;
1477 }
1478 tracing::warn!(
1479 "required dep {}@{} declares unsupported platform (os={:?} cpu={:?} libc={:?}); installing anyway",
1480 task.name,
1481 version_meta.version,
1482 version_meta.os,
1483 version_meta.cpu,
1484 version_meta.libc
1485 );
1486 }
1487
1488 let version = version_meta.version.clone();
1489 let dep_path = dep_path_for(&task.name, &version);
1490
1491 // Record publish time for the cutoff / `time:` block
1492 // whenever the packument carries one — matches pnpm,
1493 // which populates `publishedAt` opportunistically via
1494 // `meta.time?.[version]` regardless of resolution mode.
1495 // Corgi packuments from npmjs.org omit `time`, so in
1496 // Highest mode this is usually a no-op; Verdaccio
1497 // (v5.15.1+) and full-packument fetches do include it,
1498 // and then we round-trip it into the lockfile just like
1499 // pnpm does.
1500 if self.should_record_times()
1501 && let Some(t) = picked_publish_time.as_ref()
1502 {
1503 resolved_times.insert(dep_path.clone(), t.clone());
1504 }
1505
1506 // Record root dep
1507 if task.is_root
1508 && let Some(deps) = importers.get_mut(&task.importer)
1509 {
1510 deps.push(DirectDep {
1511 name: task.name.clone(),
1512 dep_path: dep_path.clone(),
1513 dep_type: task.dep_type,
1514 specifier: task.original_specifier.clone(),
1515 });
1516 }
1517
1518 // Wire parent
1519 if let Some(ref parent_dp) = task.parent
1520 && let Some(parent_pkg) = resolved.get_mut(parent_dp)
1521 {
1522 parent_pkg
1523 .dependencies
1524 .insert(task.name.clone(), version.clone());
1525 if task.dep_type == DepType::Optional {
1526 parent_pkg
1527 .optional_dependencies
1528 .insert(task.name.clone(), version.clone());
1529 }
1530 }
1531
1532 // Skip if already fully processed this exact version
1533 if visited.contains(dep_path.as_str()) {
1534 if task.is_root {
1535 note_root_done!();
1536 }
1537 continue;
1538 }
1539 visited.insert(std::sync::Arc::from(dep_path.as_str()));
1540
1541 tracing::trace!("resolved {}@{}", task.name, version);
1542
1543 // Forward a deprecation message to the install command,
1544 // subject to `allowedDeprecatedVersions` suppression.
1545 // User-facing rendering is the CLI's job — doing it here
1546 // would fire per resolved version with no way for the
1547 // caller to batch or filter direct-vs-transitive.
1548 let deprecated_msg: Option<Arc<str>> =
1549 version_meta.deprecated.as_deref().and_then(|msg| {
1550 let suppressed = is_deprecation_allowed(
1551 &task.name,
1552 &version,
1553 &self.dependency_policy.allowed_deprecated_versions,
1554 );
1555 (!suppressed).then(|| Arc::<str>::from(msg))
1556 });
1557
1558 // Track this version
1559 resolved_versions
1560 .entry(task.name.clone())
1561 .or_default()
1562 .push(version.clone());
1563
1564 let integrity = version_meta.dist.as_ref().and_then(|d| d.integrity.clone());
1565 // Always stash the registry tarball URL on the locked
1566 // package. pnpm / yarn writers gate emission on
1567 // `lockfile_include_tarball_url` (so the pnpm
1568 // round-trip stays byte-identical for projects that
1569 // opted out); the npm writer emits `resolved:` on
1570 // every package entry unconditionally, which is what
1571 // npm itself writes. Carrying the URL on every
1572 // LockedPackage lets both policies work without a
1573 // second packument fetch at write time.
1574 let tarball_url = version_meta.dist.as_ref().map(|d| d.tarball.clone());
1575
1576 // Stream this resolved package for early tarball fetching.
1577 // `alias_of` mirrors what the LockedPackage below
1578 // will carry — the streaming fetch consumer in
1579 // install.rs uses it to derive the real tarball URL
1580 // for aliased packages where `name` alone (`h3-v2`)
1581 // would 404.
1582 if let Some(ref tx) = self.resolved_tx {
1583 let _ = tx
1584 .send(ResolvedPackage {
1585 dep_path: dep_path.clone(),
1586 name: task.name.clone(),
1587 version: version.clone(),
1588 integrity: integrity.clone(),
1589 tarball_url: tarball_url.clone(),
1590 alias_of: task.real_name.clone(),
1591 local_source: None,
1592 os: version_meta.os.iter().cloned().collect(),
1593 cpu: version_meta.cpu.iter().cloned().collect(),
1594 libc: version_meta.libc.iter().cloned().collect(),
1595 deprecated: deprecated_msg.clone(),
1596 })
1597 .await;
1598 }
1599
1600 // Capture the declared peer deps now so the post-pass can
1601 // compute each consumer's peer context without re-reading
1602 // the packument.
1603 let peer_deps = version_meta.peer_dependencies.clone();
1604 let peer_meta: BTreeMap<String, aube_lockfile::PeerDepMeta> = version_meta
1605 .peer_dependencies_meta
1606 .iter()
1607 .map(|(k, v)| {
1608 (
1609 k.clone(),
1610 aube_lockfile::PeerDepMeta {
1611 optional: v.optional,
1612 },
1613 )
1614 })
1615 .collect();
1616 // `bundledDependencies` names are shipped inside the
1617 // tarball itself and must not be resolved from the
1618 // registry. If we did enqueue them, we'd fetch a
1619 // (possibly different) version and plant a sibling
1620 // symlink inside `.aube/<parent>@ver/node_modules/`
1621 // that would shadow the bundled copy during Node's
1622 // directory walk. Compute the skip set once here and
1623 // store the names on the LockedPackage so restore
1624 // (from lockfile, skipping this code path) also
1625 // knows to avoid the sibling symlinks — see the
1626 // `.dependencies` write-through downstream.
1627 let bundled_names: FxHashSet<String> = version_meta
1628 .bundled_dependencies
1629 .as_ref()
1630 .map(|b| {
1631 b.names(&version_meta.dependencies)
1632 .into_iter()
1633 .map(String::from)
1634 .collect()
1635 })
1636 .unwrap_or_default();
1637
1638 resolved.insert(
1639 dep_path.clone(),
1640 LockedPackage {
1641 name: task.name.clone(),
1642 version: version.clone(),
1643 integrity,
1644 dependencies: BTreeMap::new(),
1645 optional_dependencies: BTreeMap::new(),
1646 peer_dependencies: peer_deps,
1647 peer_dependencies_meta: peer_meta,
1648 dep_path: dep_path.clone(),
1649 local_source: None,
1650 os: version_meta.os.iter().cloned().collect(),
1651 cpu: version_meta.cpu.iter().cloned().collect(),
1652 libc: version_meta.libc.iter().cloned().collect(),
1653 bundled_dependencies: {
1654 let mut v: Vec<String> = bundled_names.iter().cloned().collect();
1655 v.sort();
1656 v
1657 },
1658 tarball_url,
1659 // `name` is the alias for npm-aliased tasks
1660 // (`"h3-v2": "npm:h3@..."` → name = "h3-v2"),
1661 // so stash the real registry name here. The
1662 // lockfile writer + installer consult
1663 // `alias_of` whenever they need to hit the
1664 // registry, matching how the npm-lockfile
1665 // reader populates this field.
1666 alias_of: task.real_name.clone(),
1667 yarn_checksum: None,
1668 engines: version_meta.engines.clone(),
1669 // Rehydrate a string-form bin (`"bin": "cli.js"`)
1670 // into `{<package_name>: "cli.js"}` — registry
1671 // packuments leave the name off, expecting
1672 // consumers to default it to the package name.
1673 // Doing it here keeps bun's per-entry meta
1674 // byte-identical to bun's own output without
1675 // pushing the fixup into every writer.
1676 bin: {
1677 let mut m = version_meta.bin.clone();
1678 if let Some(path) = m.remove("") {
1679 // String-form `bin` in a packument
1680 // (`"bin": "cli.js"`) is implicitly
1681 // named after the real registry
1682 // package — not the alias. For an
1683 // aliased dep (`"h3-v2": "npm:h3@…"`)
1684 // the bun writer must emit the bin
1685 // under `h3`, not `h3-v2`, or the
1686 // map drifts against bun's own
1687 // output (and the shim install path
1688 // creates the wrong binary name).
1689 let bin_name =
1690 task.real_name.as_deref().unwrap_or(&task.name).to_string();
1691 m.insert(bin_name, path);
1692 }
1693 m
1694 },
1695 // Declared ranges straight from the packument's
1696 // `dependencies` / `optionalDependencies`. Fed
1697 // back out by npm / yarn / bun writers so
1698 // nested package entries keep the original
1699 // specifiers instead of collapsing to pins.
1700 declared_dependencies: {
1701 let mut m = version_meta.dependencies.clone();
1702 for (k, v) in &version_meta.optional_dependencies {
1703 m.insert(k.clone(), v.clone());
1704 }
1705 m
1706 },
1707 license: version_meta.license.clone(),
1708 funding_url: version_meta.funding_url.clone(),
1709 optional: false,
1710 transitive_peer_dependencies: Vec::new(),
1711 extra_meta: BTreeMap::new(),
1712 },
1713 );
1714
1715 // Enqueue transitive deps. Kick off a background
1716 // packument fetch the instant we discover the dep
1717 // name — so by the time the task is popped off the
1718 // queue below, its packument is usually already in
1719 // flight (and often already in cache). This is where
1720 // the pipeline overlaps fetches with CPU work without
1721 // any explicit wave barrier.
1722 //
1723 // Compute the child ancestor chain once — the same
1724 // frame (this package's name + resolved version)
1725 // applies to every dep / optionalDep / peer we enqueue
1726 // below.
1727 let mut child_ancestors = task.ancestors.clone();
1728 child_ancestors.push((task.name.clone(), version.clone()));
1729
1730 for (dep_name, dep_range) in &version_meta.dependencies {
1731 if bundled_names.contains(dep_name) {
1732 continue;
1733 }
1734 if self.dependency_policy.block_exotic_subdeps
1735 && is_non_registry_specifier(dep_range)
1736 {
1737 return Err(Error::Registry(
1738 dep_name.clone(),
1739 format!(
1740 "uses exotic specifier \"{dep_range}\" which is blocked \
1741 by blockExoticSubdeps (declared by {})",
1742 task.name
1743 ),
1744 ));
1745 }
1746 if !existing_names.contains(dep_name.as_str())
1747 && prefetchable!(dep_name.as_str(), dep_range.as_str())
1748 {
1749 ensure_fetch!(dep_name);
1750 }
1751 queue.push_back(ResolveTask::transitive(
1752 dep_name.clone(),
1753 dep_range.clone(),
1754 DepType::Production,
1755 dep_path.clone(),
1756 task.importer.clone(),
1757 child_ancestors.clone(),
1758 ));
1759 }
1760
1761 for (dep_name, dep_range) in &version_meta.optional_dependencies {
1762 if bundled_names.contains(dep_name) {
1763 continue;
1764 }
1765 if self.ignored_optional_dependencies.contains(dep_name) {
1766 continue;
1767 }
1768 if self.dependency_policy.block_exotic_subdeps
1769 && is_non_registry_specifier(dep_range)
1770 {
1771 tracing::warn!(
1772 "skipping optional dependency {dep_name} of {} — \
1773 exotic specifier \"{dep_range}\" blocked by blockExoticSubdeps",
1774 task.name
1775 );
1776 continue;
1777 }
1778 if !existing_names.contains(dep_name.as_str())
1779 && prefetchable!(dep_name.as_str(), dep_range.as_str())
1780 {
1781 ensure_fetch!(dep_name);
1782 }
1783 queue.push_back(ResolveTask::transitive(
1784 dep_name.clone(),
1785 dep_range.clone(),
1786 DepType::Optional,
1787 dep_path.clone(),
1788 task.importer.clone(),
1789 child_ancestors.clone(),
1790 ));
1791 }
1792
1793 // Peer dependencies: enqueue only required peers that
1794 // are truly missing from the importer/root scope. The
1795 // post-pass below (`apply_peer_contexts`) computes
1796 // which version each consumer sees, via ancestor
1797 // scope, and assigns peer-suffixed dep_paths.
1798 //
1799 // pnpm's `auto-install-peers=true` fills in missing
1800 // required peers, but it does not install optional peer
1801 // alternatives that the user did not ask for, and it
1802 // does not install a second compatible peer when the
1803 // importer already declares that peer name at an
1804 // incompatible version. In the latter case pnpm keeps
1805 // the user's direct dependency and reports an unmet
1806 // peer warning.
1807 //
1808 // When `auto-install-peers=false`, we skip enqueueing
1809 // peers entirely. Users are on the hook for adding
1810 // them to `package.json` themselves. Unmet peers still
1811 // surface as warnings via `detect_unmet_peers` after
1812 // resolve — in fact more so, since nothing gets
1813 // auto-installed.
1814 //
1815 // Skip peers that are already declared as regular or
1816 // optional deps of the same package — those already have a
1817 // task queued via the loops above, and duplicating would
1818 // just burn a queue slot.
1819 if self.auto_install_peers {
1820 for (dep_name, dep_range) in &version_meta.peer_dependencies {
1821 let peer_optional = version_meta
1822 .peer_dependencies_meta
1823 .get(dep_name)
1824 .map(|m| m.optional)
1825 .unwrap_or(false);
1826 // Optional peers are opt-in integrations, not
1827 // auto-install candidates. Users who need one must
1828 // declare it in their own manifest so the normal dep
1829 // loops above resolve it explicitly.
1830 if peer_optional {
1831 continue;
1832 }
1833 let importer_declares_peer = importer_declared_dep_names
1834 .get(&task.importer)
1835 .is_some_and(|names| names.contains(dep_name));
1836 let root_declares_peer = self.resolve_peers_from_workspace_root
1837 && task.importer != "."
1838 && importer_declared_dep_names
1839 .get(".")
1840 .is_some_and(|names| names.contains(dep_name));
1841 let peer_dep_is_ancestor =
1842 task.ancestors.iter().any(|(name, _)| name == dep_name);
1843 if importer_declares_peer || root_declares_peer || peer_dep_is_ancestor {
1844 continue;
1845 }
1846 if version_meta.dependencies.contains_key(dep_name)
1847 || version_meta.optional_dependencies.contains_key(dep_name)
1848 || bundled_names.contains(dep_name)
1849 {
1850 continue;
1851 }
1852 if self.dependency_policy.block_exotic_subdeps
1853 && is_non_registry_specifier(dep_range)
1854 {
1855 tracing::warn!(
1856 "skipping peer dependency {dep_name} of {} — \
1857 exotic specifier \"{dep_range}\" blocked \
1858 by blockExoticSubdeps",
1859 task.name
1860 );
1861 continue;
1862 }
1863 if !existing_names.contains(dep_name.as_str())
1864 && prefetchable!(dep_name.as_str(), dep_range.as_str())
1865 {
1866 ensure_fetch!(dep_name);
1867 }
1868 queue.push_back(ResolveTask::transitive(
1869 dep_name.clone(),
1870 dep_range.clone(),
1871 DepType::Production,
1872 dep_path.clone(),
1873 task.importer.clone(),
1874 child_ancestors.clone(),
1875 ));
1876 }
1877 }
1878
1879 // Root task just completed its full version-pick
1880 // path. Decrement the pending-directs counter so
1881 // the TimeBased cutoff trigger at the top of the
1882 // outer loop can fire once wave 0 is resolved.
1883 if task.is_root {
1884 note_root_done!();
1885 }
1886 }
1887 }
1888
1889 // Drain any remaining in-flight fetches so their tasks get
1890 // cleanly joined. Normally the main loop has harvested every
1891 // spawned fetch by the time the queue drains, but a few may
1892 // still be pending if the resolver short-circuited via
1893 // sibling dedupe or lockfile reuse after ensure_fetch! had
1894 // already spawned them.
1895 while in_flight.join_next().await.is_some() {}
1896
1897 let resolve_elapsed = resolve_start.elapsed();
1898 tracing::debug!(
1899 "resolver: {:.1?} total, {} packuments fetched ({:.1?} wall), {} reused from lockfile, {} packages resolved",
1900 resolve_elapsed,
1901 packument_fetch_count,
1902 packument_fetch_time,
1903 lockfile_reuse_count,
1904 resolved.len()
1905 );
1906
1907 let resolved_catalogs =
1908 catalog::materialize_catalog_picks(catalog_picks, &resolved_versions);
1909
1910 let canonical = LockfileGraph {
1911 importers,
1912 packages: resolved,
1913 settings: aube_lockfile::LockfileSettings {
1914 auto_install_peers: self.auto_install_peers,
1915 exclude_links_from_lockfile: self.exclude_links_from_lockfile,
1916 // Tarball-URL recording is a lockfile-writer concern; the
1917 // resolver never populates URLs itself. Install flips this
1918 // on after the graph is built when the setting is active.
1919 lockfile_include_tarball_url: false,
1920 },
1921 // Stamp the resolver's overrides into the output graph so the
1922 // lockfile writer can round-trip them and the next install's
1923 // drift check can compare them against the manifest.
1924 overrides: self.overrides.clone(),
1925 ignored_optional_dependencies: self.ignored_optional_dependencies.clone(),
1926 times: resolved_times,
1927 skipped_optional_dependencies,
1928 catalogs: resolved_catalogs,
1929 // Resolver output is format-agnostic; the bun writer layer
1930 // defaults `configVersion` to 1 when emitting a fresh
1931 // lockfile.
1932 bun_config_version: None,
1933 // Fresh resolves don't carry over unknown blocks; the
1934 // install-side merge (`overlay_metadata_from`) copies
1935 // them back from the prior lockfile when round-tripping.
1936 patched_dependencies: BTreeMap::new(),
1937 trusted_dependencies: Vec::new(),
1938 extra_fields: BTreeMap::new(),
1939 workspace_extra_fields: BTreeMap::new(),
1940 };
1941
1942 // Second pass: hoist every auto-installed peer to its importer's
1943 // direct deps so pnpm-style `node_modules/<peer>` top-level
1944 // symlinks get created and the lockfile's `importers.` section
1945 // lists them the way pnpm does with `auto-install-peers=true`.
1946 // Skipped entirely when the setting is off — matches pnpm, which
1947 // leaves the importer's `dependencies` untouched in that mode.
1948 let hoisted = if self.auto_install_peers {
1949 hoist_auto_installed_peers(canonical)
1950 } else {
1951 canonical
1952 };
1953
1954 // Third pass: compute peer-context suffixes for every reachable
1955 // package. See `apply_peer_contexts` for the details.
1956 let peer_options = PeerContextOptions {
1957 dedupe_peer_dependents: self.dedupe_peer_dependents,
1958 dedupe_peers: self.dedupe_peers,
1959 resolve_from_workspace_root: self.resolve_peers_from_workspace_root,
1960 peers_suffix_max_length: self.peers_suffix_max_length,
1961 };
1962 let contextualized = apply_peer_contexts(hoisted, &peer_options);
1963 tracing::debug!(
1964 "peer-context pass produced {} contextualized packages",
1965 contextualized.packages.len()
1966 );
1967 Ok(contextualized)
1968 }
1969}
1970
1971fn is_vulnerable(
1972 package_name: &str,
1973 version: &str,
1974 vulnerable_ranges: &BTreeMap<String, Vec<String>>,
1975) -> bool {
1976 let Some(ranges) = vulnerable_ranges.get(package_name) else {
1977 return false;
1978 };
1979 let Ok(version) = node_semver::Version::parse(version) else {
1980 return false;
1981 };
1982 ranges
1983 .iter()
1984 .filter_map(|range| node_semver::Range::parse(range).ok())
1985 .any(|range| version.satisfies(&range))
1986}
1987
1988fn prefer_non_vulnerable_pick<'a>(
1989 package_name: &str,
1990 packument: &'a Packument,
1991 range_str: &str,
1992 fallback: &'a aube_registry::VersionMetadata,
1993 pick_lowest: bool,
1994 cutoff: Option<&str>,
1995 vulnerable_ranges: &BTreeMap<String, Vec<String>>,
1996) -> &'a aube_registry::VersionMetadata {
1997 if !is_vulnerable(package_name, &fallback.version, vulnerable_ranges) {
1998 return fallback;
1999 }
2000 let Ok(range) = node_semver::Range::parse(crate::semver_util::normalize_range(range_str))
2001 else {
2002 return fallback;
2003 };
2004 let passes_cutoff = |ver: &str| -> bool {
2005 let Some(c) = cutoff else { return true };
2006 match packument.time.get(ver) {
2007 Some(t) => t.as_str() <= c,
2008 None => true,
2009 }
2010 };
2011 let mut best: Option<(node_semver::Version, &'a aube_registry::VersionMetadata)> = None;
2012 for (ver_str, meta) in &packument.versions {
2013 let Ok(version) = node_semver::Version::parse(ver_str) else {
2014 continue;
2015 };
2016 if !version.satisfies(&range)
2017 || !passes_cutoff(ver_str)
2018 || is_vulnerable(package_name, ver_str, vulnerable_ranges)
2019 {
2020 continue;
2021 }
2022 let replace = best.as_ref().is_none_or(|(cur, _)| {
2023 if pick_lowest {
2024 version < *cur
2025 } else {
2026 version > *cur
2027 }
2028 });
2029 if replace {
2030 best = Some((version, meta));
2031 }
2032 }
2033 best.map(|(_, meta)| meta).unwrap_or(fallback)
2034}
2035
2036/// Seed the BFS queue with direct deps from every importer manifest.
2037///
2038/// When a package is declared in more than one section
2039/// (`dependencies` + `devDependencies`, etc.) we keep only the
2040/// highest-priority entry — `dependencies` > `devDependencies` >
2041/// `optionalDependencies` — matching pnpm, which silently drops
2042/// the lower-priority duplicates on resolve. Without this the
2043/// same name gets pushed into the importer's `DirectDep` list
2044/// twice (once per section), and the linker's parallel step 2
2045/// races to create the same `node_modules/<name>` symlink from
2046/// two tasks, producing an `EEXIST` on the loser.
2047fn seed_direct_deps(
2048 manifests: &[(String, PackageJson)],
2049 ignored_optional_dependencies: &BTreeSet<String>,
2050 queue: &mut VecDeque<ResolveTask>,
2051 importers: &mut BTreeMap<String, Vec<DirectDep>>,
2052) {
2053 for (importer_path, manifest) in manifests {
2054 importers.insert(importer_path.clone(), Vec::new());
2055
2056 for (name, range) in &manifest.dependencies {
2057 queue.push_back(ResolveTask::root(
2058 name.clone(),
2059 range.clone(),
2060 DepType::Production,
2061 importer_path.clone(),
2062 ));
2063 }
2064 for (name, range) in &manifest.dev_dependencies {
2065 if manifest.dependencies.contains_key(name) {
2066 continue;
2067 }
2068 queue.push_back(ResolveTask::root(
2069 name.clone(),
2070 range.clone(),
2071 DepType::Dev,
2072 importer_path.clone(),
2073 ));
2074 }
2075 for (name, range) in &manifest.optional_dependencies {
2076 if ignored_optional_dependencies.contains(name) {
2077 tracing::debug!(
2078 "ignoring optional dependency {name} (pnpm.ignoredOptionalDependencies)"
2079 );
2080 continue;
2081 }
2082 if manifest.dependencies.contains_key(name)
2083 || manifest.dev_dependencies.contains_key(name)
2084 {
2085 continue;
2086 }
2087 queue.push_back(ResolveTask::root(
2088 name.clone(),
2089 range.clone(),
2090 DepType::Optional,
2091 importer_path.clone(),
2092 ));
2093 }
2094 }
2095}