fallow-core 3.43.1

Internal detector backend for fallow-engine and fallow-api
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
//! Binary name → npm package name resolution.

use std::path::{Path, PathBuf};

use rustc_hash::{FxHashMap, FxHashSet};

/// Known binary-name → package-name mappings where they diverge.
///
/// A binary can come from more than one package, for example `run-p` from
/// `npm-run-all` and from its fork `npm-run-all2`. Script analysis credits
/// every candidate, unless `node_modules` shows which candidate installs the
/// binary. Without `node_modules`, this table is the only source that maps a
/// binary to a package whose name is different.
static BINARY_TO_PACKAGE: &[(&str, &[&str])] = &[
    ("tsc", &["typescript"]),
    ("tsserver", &["typescript"]),
    ("tsgo", &["@typescript/native-preview"]),
    ("ng", &["@angular/cli"]),
    ("nuxi", &["nuxt"]),
    ("run-s", &["npm-run-all", "npm-run-all2"]),
    ("run-p", &["npm-run-all", "npm-run-all2"]),
    ("run-s2", &["npm-run-all2"]),
    ("run-p2", &["npm-run-all2"]),
    ("sb", &["storybook"]),
    ("biome", &["@biomejs/biome"]),
    ("oxlint", &["oxlint"]),
    ("ember", &["ember-cli"]),
    ("nest", &["@nestjs/cli"]),
    ("cap", &["@capacitor/cli"]),
    ("cucumber-js", &["@cucumber/cucumber", "cucumber"]),
    ("depcruise", &["dependency-cruiser"]),
    ("depcruise-baseline", &["dependency-cruiser"]),
    ("depcruise-fmt", &["dependency-cruiser"]),
    ("dependency-cruise", &["dependency-cruiser"]),
    ("cz", &["commitizen"]),
    ("git-cz", &["commitizen", "git-cz"]),
    ("flow", &["flow-bin"]),
    ("ncu", &["npm-check-updates"]),
    ("dotenv", &["dotenv-cli"]),
    ("dotenvx", &["@dotenvx/dotenvx"]),
    ("npmPkgJsonLint", &["npm-package-json-lint"]),
    ("i18next", &["i18next-parser"]),
    ("manypkg", &["@manypkg/cli"]),
    ("rstest", &["@rstest/core"]),
    ("sls", &["serverless", "osls"]),
    ("napi", &["@napi-rs/cli"]),
    ("napi-raw", &["@napi-rs/cli"]),
    ("taplo", &["@taplo/cli"]),
    ("oxnode", &["@oxc-node/cli"]),
    ("ut", &["utoo"]),
    ("utx", &["utoo"]),
    ("vp", &["vite-plus"]),
    ("vpr", &["vite-plus"]),
    ("vpx", &["vite-plus"]),
];

/// The packages that the static table maps `binary` to.
fn static_candidates(binary: &str) -> Option<&'static [&'static str]> {
    BINARY_TO_PACKAGE
        .iter()
        .find(|(bin, _)| *bin == binary)
        .map(|&(_, packages)| packages)
}

/// The package that `node_modules` says installs `binary`: the
/// `node_modules/.bin` link target first, then the `bin` field map.
fn installed_package(
    binary: &str,
    root: &Path,
    bin_map: &FxHashMap<String, String>,
) -> Option<String> {
    let bin_link = root.join("node_modules/.bin").join(binary);
    if let Ok(target) = std::fs::read_link(&bin_link)
        && let Some(pkg_name) = extract_package_from_bin_path(&target)
    {
        return Some(pkg_name);
    }
    bin_map.get(binary).cloned()
}

/// Build a reverse map from binary names to package names by reading each
/// dependency's `package.json` from `node_modules/` and extracting `bin`.
///
/// Probes each provided `node_modules/` root, which covers non-hoisted setups.
#[must_use]
pub fn build_bin_to_package_map(
    node_modules_roots: &[&Path],
    dep_names: &[String],
) -> FxHashMap<String, String> {
    let mut map = FxHashMap::default();

    for dep_name in dep_names {
        let bin = node_modules_roots.iter().find_map(|root| {
            let pkg_path = root
                .join("node_modules")
                .join(dep_name)
                .join("package.json");
            let content = std::fs::read_to_string(&pkg_path).ok()?;
            let pkg = serde_json::from_str::<serde_json::Value>(&content).ok()?;
            pkg.get("bin").cloned()
        });
        let Some(bin) = bin else {
            continue;
        };

        for bin_name in bin_names(dep_name, &bin) {
            map.insert(bin_name.to_string(), dep_name.clone());
        }
    }

    map
}

/// The binary names that a `bin` field declares: the unscoped package name
/// for the string form, the keys for the object form.
pub(super) fn bin_names<'a>(package: &'a str, bin: &'a serde_json::Value) -> Vec<&'a str> {
    match bin {
        serde_json::Value::String(_) => vec![package.rsplit('/').next().unwrap_or(package)],
        serde_json::Value::Object(obj) => obj.keys().map(String::as_str).collect(),
        _ => Vec::new(),
    }
}

/// The bin map of a project: the `bin` fields that `node_modules` holds for
/// `dep_names`, plus the `bin` fields of the declared workspace packages.
#[must_use]
pub fn project_bin_map<'a>(
    node_modules_roots: &[&Path],
    dep_names: &[String],
    workspace_packages: impl IntoIterator<Item = &'a fallow_config::PackageJson>,
    declared: &FxHashSet<String>,
) -> FxHashMap<String, String> {
    let mut map = build_bin_to_package_map(node_modules_roots, dep_names);
    add_workspace_binaries(&mut map, workspace_packages, declared);
    map
}

/// Add the `bin` fields of workspace packages to `map`.
///
/// The package manager links the binaries of a workspace package only into
/// the packages that declare it, so a package that no manifest declares adds
/// nothing. An entry that `node_modules` already supplies keeps priority.
/// This lets a script that calls a workspace binary credit its package when
/// `node_modules` is absent.
fn add_workspace_binaries<'a>(
    map: &mut FxHashMap<String, String>,
    packages: impl IntoIterator<Item = &'a fallow_config::PackageJson>,
    declared: &FxHashSet<String>,
) {
    for pkg in packages {
        let (Some(name), Some(bin)) = (pkg.name.as_deref(), pkg.bin.as_ref()) else {
            continue;
        };
        if !declared.contains(name) {
            continue;
        }
        for bin_name in bin_names(name, bin) {
            map.entry(bin_name.to_string())
                .or_insert_with(|| name.to_string());
        }
    }
}

/// Resolve a binary name to the npm packages that can provide it.
///
/// The static table wins over `node_modules`, because an unrelated package
/// can also ship a binary with a well-known name. When the table has more than
/// one candidate, the installed package selects one of them. Without a table
/// entry, `node_modules` decides, and the binary name is the fallback.
///
/// A path into a `node_modules/.bin` directory (`./node_modules/.bin/tool`,
/// `../../node_modules/.bin/tool`) resolves the same as the bare binary name.
/// The `.bin` link of that directory wins.
#[must_use]
pub fn resolve_binary_to_packages(
    binary: &str,
    root: &Path,
    bin_map: &FxHashMap<String, String>,
) -> Vec<String> {
    if let Some(bin_path) = NodeModulesBinPath::parse(binary) {
        if let Some(pkg_name) = bin_path.linked_package(root) {
            return vec![pkg_name];
        }
        return resolve_binary_name(bin_path.name, root, bin_map);
    }
    resolve_binary_name(binary, root, bin_map)
}

/// A command path that names a binary in a `node_modules/.bin` directory.
struct NodeModulesBinPath<'a> {
    /// The directory that holds `node_modules`, relative to the script root.
    base: &'a str,
    /// The binary name.
    name: &'a str,
}

/// The `.bin` directory segment of a command path.
const BIN_DIR_SEGMENT: &str = "node_modules/.bin/";

impl<'a> NodeModulesBinPath<'a> {
    /// Parse `path`, or return `None` when it does not name a `.bin` entry.
    fn parse(path: &'a str) -> Option<Self> {
        let (base, name) = path.rsplit_once(BIN_DIR_SEGMENT)?;
        let whole_segment = base.is_empty() || base.ends_with('/');
        (whole_segment && !name.is_empty() && !name.contains('/')).then_some(Self { base, name })
    }

    /// The package that the `.bin` link of this exact directory points to.
    fn linked_package(&self, root: &Path) -> Option<String> {
        let link = root.join(self.base).join(BIN_DIR_SEGMENT).join(self.name);
        let target = std::fs::read_link(link).ok()?;
        extract_package_from_bin_path(&target)
    }
}

/// The name of `binary` without a `node_modules/.bin/` directory, so
/// `./node_modules/.bin/tsx` and `tsx` give the same name.
pub(super) fn binary_name(binary: &str) -> &str {
    NodeModulesBinPath::parse(binary).map_or(binary, |bin_path| bin_path.name)
}

/// The binaries of a script command whose packages the command uses.
///
/// A command credits its own binary. The `node` and `bun` runtimes are not
/// packages, so they credit nothing. A Node.js runner (`is_node_runner`) also
/// credits each `node_modules/.bin` path in its file arguments, for example
/// `node ./node_modules/.bin/tool`. A preload file such as
/// `node -r ./setup.js node_modules/.bin/tool` can come before the program,
/// so the first file argument is not always the program.
pub(super) fn credited_binaries<'a>(
    binary: &'a str,
    file_args: &'a [String],
    is_node_runner: bool,
) -> impl Iterator<Item = &'a str> {
    let runtime = is_node_runner && matches!(binary, "node" | "bun");
    let programs = file_args
        .iter()
        .map(String::as_str)
        .filter(move |arg| is_node_runner && NodeModulesBinPath::parse(arg).is_some());
    (!runtime).then_some(binary).into_iter().chain(programs)
}

fn resolve_binary_name(
    binary: &str,
    root: &Path,
    bin_map: &FxHashMap<String, String>,
) -> Vec<String> {
    let Some(candidates) = static_candidates(binary) else {
        let installed = installed_package(binary, root, bin_map);
        return vec![installed.unwrap_or_else(|| binary.to_string())];
    };
    if candidates.len() > 1
        && let Some(pkg_name) = installed_package(binary, root, bin_map)
        && candidates.contains(&pkg_name.as_str())
    {
        return vec![pkg_name];
    }
    candidates.iter().map(|pkg| (*pkg).to_string()).collect()
}

/// Gather sorted, deduped dependency names across the root and workspace
/// manifests.
#[must_use]
pub fn all_dependency_names(manifests: &[&fallow_config::PackageJson]) -> Vec<String> {
    let mut names: Vec<String> = manifests
        .iter()
        .flat_map(|pkg| pkg.all_dependency_names())
        .collect();
    names.sort_unstable();
    names.dedup();
    names
}

/// Credit each npm alias whose aliased package `used` already holds.
///
/// A script binary resolves to the package that ships it, for example `tsc`
/// to `typescript`. A project that installs that package as
/// `"@typescript/native": "npm:typescript@7"` declares only the alias, so the
/// alias is the dependency in use.
///
/// When the manifest that declares the alias also declares the aliased
/// package under its own name, and that name is not itself an alias, the
/// plain declaration provides the binary and the alias gets no credit. This
/// keeps a side-by-side alias such as `"typescript-5": "npm:typescript@5"`
/// reportable. A plain declaration in another workspace does not block the
/// credit, because that workspace does not install the binary for the alias.
///
/// A `catalog:` reference gets its spec from the catalogs in the project root
/// of `config`, so an alias that a pnpm or Bun catalog defines counts the same
/// as an inline alias.
pub fn credit_npm_aliases(
    used: &mut FxHashSet<String>,
    manifests: &[&fallow_config::PackageJson],
    config: &fallow_config::ResolvedConfig,
) {
    let catalogs = load_catalog_data(&config.root, manifests);
    credit_npm_aliases_with_catalogs(used, manifests, catalogs.as_ref());
}

/// True when a dependency of a manifest has a `catalog:` spec.
fn has_catalog_reference(manifests: &[&fallow_config::PackageJson]) -> bool {
    manifests
        .iter()
        .flat_map(|pkg| {
            [
                &pkg.dependencies,
                &pkg.dev_dependencies,
                &pkg.optional_dependencies,
                &pkg.peer_dependencies,
            ]
        })
        .flatten()
        .flat_map(|deps| deps.values())
        .any(|spec| spec.trim_start().starts_with("catalog:"))
}

/// The catalogs that `catalog:` references in the manifests read from.
///
/// When no manifest has a `catalog:` reference, the function reads no file
/// and gives `None`. `pnpm-workspace.yaml` is the source when it exists, as
/// in catalog analysis. Otherwise Bun catalogs in the root `package.json` are
/// the source. A `pnpm-workspace.yaml` that does not parse gives `None`;
/// catalog analysis reports the parse error.
fn load_catalog_data(
    root: &Path,
    manifests: &[&fallow_config::PackageJson],
) -> Option<fallow_config::PnpmCatalogData> {
    if !has_catalog_reference(manifests) {
        return None;
    }
    if let Ok(source) = std::fs::read_to_string(root.join("pnpm-workspace.yaml")) {
        return fallow_config::parse_pnpm_catalog_data(&source).ok();
    }
    let source = std::fs::read_to_string(root.join("package.json")).ok()?;
    let data = fallow_config::parse_package_json_catalog_data(&source);
    (!data.catalogs.is_empty()).then_some(data)
}

/// [`credit_npm_aliases`] with the catalogs already loaded.
fn credit_npm_aliases_with_catalogs(
    used: &mut FxHashSet<String>,
    manifests: &[&fallow_config::PackageJson],
    catalogs: Option<&fallow_config::PnpmCatalogData>,
) {
    let mut credited: Vec<String> = Vec::new();
    for pkg in manifests {
        let aliases = pkg.npm_aliases_with_catalogs(catalogs);
        if aliases.is_empty() {
            continue;
        }
        let declared: FxHashSet<String> = pkg.all_dependency_names().into_iter().collect();
        let is_alias = |name: &str| aliases.iter().any(|(alias, _)| alias == name);
        credited.extend(
            aliases
                .iter()
                .filter(|(_, target)| used.contains(target))
                .filter(|(_, target)| !declared.contains(target) || is_alias(target))
                .map(|(alias, _)| alias.clone()),
        );
    }
    used.extend(credited);
}

/// Resolve a binary only when it is known to belong to a declared dependency.
#[must_use]
pub fn resolve_known_dependency_binary(
    binary: &str,
    root: &Path,
    bin_map: &FxHashMap<String, String>,
    declared_packages: &FxHashSet<String>,
) -> Option<String> {
    if let Some(pkg) = static_candidates(binary)
        .into_iter()
        .flatten()
        .find(|pkg| declared_packages.contains(**pkg))
    {
        return Some((*pkg).to_string());
    }

    let bin_link = root.join("node_modules/.bin").join(binary);
    if let Ok(target) = std::fs::read_link(&bin_link)
        && let Some(pkg_name) = extract_package_from_bin_path(&target)
        && declared_packages.contains(&pkg_name)
    {
        return Some(pkg_name);
    }

    if let Some(pkg_name) = bin_map.get(binary)
        && declared_packages.contains(pkg_name)
    {
        return Some(pkg_name.clone());
    }

    declared_packages
        .contains(binary)
        .then(|| binary.to_string())
}

/// The binary names that the declared dependencies of a project provide.
///
/// Script analysis builds the bin map once. Source analysis uses the same map
/// to resolve a `node_modules/.bin/<name>` path in code.
#[derive(Debug, Clone, Default)]
pub struct DependencyBinaries {
    root: PathBuf,
    bin_map: FxHashMap<String, String>,
    declared_packages: FxHashSet<String>,
}

impl DependencyBinaries {
    #[must_use]
    pub const fn new(
        root: PathBuf,
        bin_map: FxHashMap<String, String>,
        declared_packages: FxHashSet<String>,
    ) -> Self {
        Self {
            root,
            bin_map,
            declared_packages,
        }
    }

    /// Every dependency name the root and workspace manifests declare.
    #[must_use]
    pub const fn declared_packages(&self) -> &FxHashSet<String> {
        &self.declared_packages
    }

    /// The declared dependency that provides `binary`, if one does.
    #[must_use]
    pub fn package_for(&self, binary: &str) -> Option<String> {
        resolve_known_dependency_binary(binary, &self.root, &self.bin_map, &self.declared_packages)
    }
}

/// Extract a package name from a `node_modules/.bin` symlink target path.
///
/// Typical symlink targets:
/// - `../webpack/bin/webpack.js` → `webpack`
/// - `../@babel/cli/bin/babel.js` → `@babel/cli`
pub fn extract_package_from_bin_path(target: &std::path::Path) -> Option<String> {
    let target_str = target.to_string_lossy();
    let parts: Vec<&str> = target_str.split('/').collect();

    for (i, part) in parts.iter().enumerate() {
        if *part == ".." {
            continue;
        }
        if part.starts_with('@') && i + 1 < parts.len() {
            return Some(format!("{}/{}", part, parts[i + 1]));
        }
        return Some(part.to_string());
    }

    None
}

#[cfg(test)]
mod tests {
    use super::*;

    fn empty_map() -> FxHashMap<String, String> {
        FxHashMap::default()
    }

    fn declared(packages: &[&str]) -> FxHashSet<String> {
        packages.iter().map(|pkg| (*pkg).to_string()).collect()
    }

    #[test]
    fn tsserver_maps_to_typescript() {
        let pkg = resolve_binary_to_packages("tsserver", Path::new("/nonexistent"), &empty_map());
        assert_eq!(pkg, ["typescript"]);
    }

    #[test]
    fn nuxi_maps_to_nuxt() {
        let pkg = resolve_binary_to_packages("nuxi", Path::new("/nonexistent"), &empty_map());
        assert_eq!(pkg, ["nuxt"]);
    }

    #[test]
    fn run_p_maps_to_npm_run_all_and_its_fork() {
        let pkg = resolve_binary_to_packages("run-p", Path::new("/nonexistent"), &empty_map());
        assert_eq!(pkg, ["npm-run-all", "npm-run-all2"]);
    }

    #[test]
    fn installed_fork_selects_one_static_candidate() {
        let mut map = FxHashMap::default();
        map.insert("run-p".to_string(), "npm-run-all2".to_string());
        let pkg = resolve_binary_to_packages("run-p", Path::new("/nonexistent"), &map);
        assert_eq!(pkg, ["npm-run-all2"]);
    }

    #[cfg(unix)]
    #[test]
    fn bin_link_selects_one_static_candidate() {
        let dir = tempfile::tempdir().unwrap();
        let bin_dir = dir.path().join("node_modules/.bin");
        std::fs::create_dir_all(&bin_dir).unwrap();
        std::os::unix::fs::symlink("../npm-run-all2/bin/run-s/index.js", bin_dir.join("run-s"))
            .unwrap();
        let pkg = resolve_binary_to_packages("run-s", dir.path(), &empty_map());
        assert_eq!(pkg, ["npm-run-all2"]);
    }

    #[test]
    fn unrelated_installed_package_does_not_override_static_candidates() {
        let mut map = FxHashMap::default();
        map.insert("run-p".to_string(), "wrong-package".to_string());
        let pkg = resolve_binary_to_packages("run-p", Path::new("/nonexistent"), &map);
        assert_eq!(pkg, ["npm-run-all", "npm-run-all2"]);
    }

    #[test]
    fn divergent_binaries_resolve_without_node_modules() {
        let cases = [
            ("ember", "ember-cli"),
            ("nest", "@nestjs/cli"),
            ("cap", "@capacitor/cli"),
            ("cucumber-js", "@cucumber/cucumber"),
            ("depcruise", "dependency-cruiser"),
            ("cz", "commitizen"),
            ("git-cz", "commitizen"),
            ("tsgo", "@typescript/native-preview"),
            ("flow", "flow-bin"),
            ("ncu", "npm-check-updates"),
            ("dotenv", "dotenv-cli"),
            ("dotenvx", "@dotenvx/dotenvx"),
            ("npmPkgJsonLint", "npm-package-json-lint"),
            ("i18next", "i18next-parser"),
            ("manypkg", "@manypkg/cli"),
            ("napi", "@napi-rs/cli"),
            ("napi-raw", "@napi-rs/cli"),
            ("taplo", "@taplo/cli"),
            ("oxnode", "@oxc-node/cli"),
            ("ut", "utoo"),
            ("utx", "utoo"),
        ];
        for (binary, package) in cases {
            let pkg = resolve_binary_to_packages(binary, Path::new("/nonexistent"), &empty_map());
            assert!(
                pkg.iter().any(|candidate| candidate == package),
                "{binary} must resolve to {package}, got {pkg:?}"
            );
        }
    }

    #[test]
    fn known_dependency_binary_accepts_declared_fork() {
        let pkg = resolve_known_dependency_binary(
            "run-p",
            Path::new("/nonexistent"),
            &empty_map(),
            &declared(&["npm-run-all2"]),
        );
        assert_eq!(pkg.as_deref(), Some("npm-run-all2"));
    }

    #[test]
    fn run_s2_maps_to_npm_run_all2() {
        let pkg = resolve_binary_to_packages("run-s2", Path::new("/nonexistent"), &empty_map());
        assert_eq!(pkg, ["npm-run-all2"]);
    }

    #[test]
    fn run_p2_maps_to_npm_run_all2() {
        let pkg = resolve_binary_to_packages("run-p2", Path::new("/nonexistent"), &empty_map());
        assert_eq!(pkg, ["npm-run-all2"]);
    }

    #[test]
    fn sb_maps_to_storybook() {
        let pkg = resolve_binary_to_packages("sb", Path::new("/nonexistent"), &empty_map());
        assert_eq!(pkg, ["storybook"]);
    }

    #[test]
    fn oxlint_maps_to_oxlint() {
        let pkg = resolve_binary_to_packages("oxlint", Path::new("/nonexistent"), &empty_map());
        assert_eq!(pkg, ["oxlint"]);
    }

    #[test]
    fn bin_map_resolves_divergent_binary() {
        let mut map = FxHashMap::default();
        map.insert("attw".to_string(), "@arethetypeswrong/cli".to_string());
        let pkg = resolve_binary_to_packages("attw", Path::new("/nonexistent"), &map);
        assert_eq!(pkg, ["@arethetypeswrong/cli"]);
    }

    #[test]
    fn bin_map_does_not_override_static_table() {
        let mut map = FxHashMap::default();
        map.insert("tsc".to_string(), "wrong-package".to_string());
        let pkg = resolve_binary_to_packages("tsc", Path::new("/nonexistent"), &map);
        assert_eq!(pkg, ["typescript"]);
    }

    #[test]
    fn bin_map_scoped_package_string_bin() {
        let mut map = FxHashMap::default();
        map.insert("my-tool".to_string(), "@scope/my-tool".to_string());
        let pkg = resolve_binary_to_packages("my-tool", Path::new("/nonexistent"), &map);
        assert_eq!(pkg, ["@scope/my-tool"]);
    }

    #[test]
    fn unknown_binary_returns_identity() {
        let pkg =
            resolve_binary_to_packages("some-random-tool", Path::new("/nonexistent"), &empty_map());
        assert_eq!(pkg, ["some-random-tool"]);
    }

    #[test]
    fn known_dependency_binary_accepts_declared_identity() {
        let pkg = resolve_known_dependency_binary(
            "envinfo",
            Path::new("/nonexistent"),
            &empty_map(),
            &declared(&["envinfo"]),
        );
        assert_eq!(pkg.as_deref(), Some("envinfo"));
    }

    #[test]
    fn known_dependency_binary_accepts_static_mapping_when_declared() {
        let pkg = resolve_known_dependency_binary(
            "tsc",
            Path::new("/nonexistent"),
            &empty_map(),
            &declared(&["typescript"]),
        );
        assert_eq!(pkg.as_deref(), Some("typescript"));
    }

    #[test]
    fn known_dependency_binary_accepts_bin_map_when_declared() {
        let mut map = FxHashMap::default();
        map.insert("attw".to_string(), "@arethetypeswrong/cli".to_string());
        let pkg = resolve_known_dependency_binary(
            "attw",
            Path::new("/nonexistent"),
            &map,
            &declared(&["@arethetypeswrong/cli"]),
        );
        assert_eq!(pkg.as_deref(), Some("@arethetypeswrong/cli"));
    }

    #[test]
    fn known_dependency_binary_rejects_identity_fallback_when_not_declared() {
        let pkg = resolve_known_dependency_binary(
            "some-random-tool",
            Path::new("/nonexistent"),
            &empty_map(),
            &FxHashSet::default(),
        );
        assert_eq!(pkg, None);
    }

    fn credit(used: &[&str], dev_dependencies: &str) -> FxHashSet<String> {
        let pkg = workspace_package(&format!(r#"{{"devDependencies": {dev_dependencies}}}"#));
        let mut used = declared(used);
        credit_npm_aliases_with_catalogs(&mut used, &[&pkg], None);
        used
    }

    #[test]
    fn npm_alias_is_credited_when_another_manifest_declares_the_target_plainly() {
        let root = workspace_package(r#"{"devDependencies": {"typescript": "^5.0.0"}}"#);
        let ws = workspace_package(
            r#"{"devDependencies": {"@typescript/native": "npm:typescript@~7.0.2"}}"#,
        );
        let mut used = declared(&["typescript"]);
        credit_npm_aliases_with_catalogs(&mut used, &[&root, &ws], None);
        assert_eq!(used, declared(&["typescript", "@typescript/native"]));
    }

    #[test]
    fn npm_alias_of_a_used_package_is_credited() {
        let used = credit(
            &["typescript"],
            r#"{"@typescript/native": "npm:typescript@~7.0.2", "idle": "npm:left-pad@1"}"#,
        );
        assert_eq!(used, declared(&["typescript", "@typescript/native"]));
    }

    #[test]
    fn npm_alias_is_credited_when_the_target_name_is_another_alias() {
        let used = credit(
            &["typescript"],
            r#"{"@typescript/native": "npm:typescript@7", "typescript": "npm:@typescript/typescript6@6"}"#,
        );
        assert!(used.contains("@typescript/native"));
    }

    #[test]
    fn npm_alias_is_not_credited_when_the_target_is_declared_plainly() {
        let used = credit(
            &["typescript"],
            r#"{"typescript": "^7.0.2", "typescript-5": "npm:typescript@5"}"#,
        );
        assert_eq!(used, declared(&["typescript"]));
    }

    fn credit_with_catalog(
        used: &[&str],
        dev_dependencies: &str,
        catalog: &str,
    ) -> FxHashSet<String> {
        let pkg = workspace_package(&format!(r#"{{"devDependencies": {dev_dependencies}}}"#));
        let catalogs = fallow_config::parse_pnpm_catalog_data(catalog).expect("valid YAML");
        let mut used = declared(used);
        credit_npm_aliases_with_catalogs(&mut used, &[&pkg], Some(&catalogs));
        used
    }

    #[test]
    fn npm_alias_from_a_catalog_is_credited() {
        let used = credit_with_catalog(
            &["typescript"],
            r#"{"@typescript/native": "catalog:", "typescript": "catalog:"}"#,
            "catalog:\n  \"@typescript/native\": npm:typescript@~7.0.2\n  typescript: npm:@typescript/typescript6@~6.0.2\n",
        );
        assert_eq!(used, declared(&["typescript", "@typescript/native"]));
    }

    #[test]
    fn npm_alias_from_a_named_catalog_is_credited() {
        let used = credit_with_catalog(
            &["vite"],
            r#"{"vite-next": "catalog:tools"}"#,
            "catalogs:\n  tools:\n    vite-next: npm:vite@^7.0.0\n",
        );
        assert_eq!(used, declared(&["vite", "vite-next"]));
    }

    #[test]
    fn npm_alias_from_a_catalog_is_not_credited_when_the_target_is_declared_plainly() {
        let used = credit_with_catalog(
            &["typescript"],
            r#"{"typescript": "catalog:", "typescript-5": "catalog:"}"#,
            "catalog:\n  typescript: ^7.0.2\n  typescript-5: npm:typescript@5\n",
        );
        assert_eq!(used, declared(&["typescript"]));
    }

    #[test]
    fn npm_alias_from_a_bun_catalog_in_the_root_package_json_is_credited() {
        let root = tempfile::tempdir().unwrap();
        std::fs::write(
            root.path().join("package.json"),
            r#"{"workspaces": {"packages": ["packages/*"], "catalogs": {"tools": {"vite-next": "npm:vite@^7.0.0"}}}}"#,
        )
        .unwrap();
        let pkg = workspace_package(r#"{"devDependencies": {"vite-next": "catalog:tools"}}"#);
        let catalogs = load_catalog_data(root.path(), &[&pkg]);
        let mut used = declared(&["vite"]);
        credit_npm_aliases_with_catalogs(&mut used, &[&pkg], catalogs.as_ref());
        assert_eq!(used, declared(&["vite", "vite-next"]));
    }

    #[test]
    fn pnpm_workspace_catalog_takes_precedence_over_the_root_package_json() {
        let root = tempfile::tempdir().unwrap();
        std::fs::write(
            root.path().join("pnpm-workspace.yaml"),
            "catalog:\n  vite-next: ^7.0.0\n",
        )
        .unwrap();
        std::fs::write(
            root.path().join("package.json"),
            r#"{"workspaces": {"catalog": {"vite-next": "npm:vite@^7.0.0"}}}"#,
        )
        .unwrap();
        let pkg = workspace_package(r#"{"devDependencies": {"vite-next": "catalog:"}}"#);
        let catalogs = load_catalog_data(root.path(), &[&pkg]);
        let mut used = declared(&["vite"]);
        credit_npm_aliases_with_catalogs(&mut used, &[&pkg], catalogs.as_ref());
        assert_eq!(used, declared(&["vite"]));
    }

    #[test]
    fn catalog_files_are_not_read_without_a_catalog_reference() {
        let root = tempfile::tempdir().unwrap();
        std::fs::write(
            root.path().join("pnpm-workspace.yaml"),
            "catalog:\n  vite-next: npm:vite@^7.0.0\n",
        )
        .unwrap();
        let pkg = workspace_package(r#"{"devDependencies": {"vite-next": "^7.0.0"}}"#);
        assert!(load_catalog_data(root.path(), &[&pkg]).is_none());
    }

    #[test]
    fn jest_identity_without_symlink() {
        let pkg = resolve_binary_to_packages("jest", Path::new("/nonexistent"), &empty_map());
        assert_eq!(pkg, ["jest"]);
    }

    #[test]
    fn eslint_identity_without_symlink() {
        let pkg = resolve_binary_to_packages("eslint", Path::new("/nonexistent"), &empty_map());
        assert_eq!(pkg, ["eslint"]);
    }

    #[test]
    fn bin_path_simple_package() {
        let path = std::path::Path::new("../eslint/bin/eslint.js");
        assert_eq!(
            extract_package_from_bin_path(path),
            Some("eslint".to_string())
        );
    }

    #[test]
    fn bin_path_scoped_package() {
        let path = std::path::Path::new("../@angular/cli/bin/ng");
        assert_eq!(
            extract_package_from_bin_path(path),
            Some("@angular/cli".to_string())
        );
    }

    #[test]
    fn bin_path_deeply_nested() {
        let path = std::path::Path::new("../../typescript/bin/tsc");
        assert_eq!(
            extract_package_from_bin_path(path),
            Some("typescript".to_string())
        );
    }

    #[test]
    fn bin_path_no_parent_dots() {
        let path = std::path::Path::new("webpack/bin/webpack.js");
        assert_eq!(
            extract_package_from_bin_path(path),
            Some("webpack".to_string())
        );
    }

    #[test]
    fn bin_path_only_dots() {
        let path = std::path::Path::new("../../..");
        assert_eq!(extract_package_from_bin_path(path), None);
    }

    #[test]
    fn bin_path_scoped_with_multiple_parents() {
        let path = std::path::Path::new("../../../@biomejs/biome/bin/biome");
        assert_eq!(
            extract_package_from_bin_path(path),
            Some("@biomejs/biome".to_string())
        );
    }

    #[test]
    fn bin_map_object_form() {
        let dir = tempfile::tempdir().unwrap();
        let nm = dir.path().join("node_modules/my-cli");
        std::fs::create_dir_all(&nm).unwrap();
        std::fs::write(
            nm.join("package.json"),
            r#"{"name": "my-cli", "bin": {"mycli": "./bin/cli.js", "mc": "./bin/short.js"}}"#,
        )
        .unwrap();

        let map = build_bin_to_package_map(&[dir.path()], &["my-cli".to_string()]);
        assert_eq!(&map["mycli"], "my-cli");
        assert_eq!(&map["mc"], "my-cli");
        assert!(!map.contains_key("my-cli"));
    }

    #[test]
    fn bin_map_string_form_unscoped() {
        let dir = tempfile::tempdir().unwrap();
        let nm = dir.path().join("node_modules/publint");
        std::fs::create_dir_all(&nm).unwrap();
        std::fs::write(
            nm.join("package.json"),
            r#"{"name": "publint", "bin": "./cli.js"}"#,
        )
        .unwrap();

        let map = build_bin_to_package_map(&[dir.path()], &["publint".to_string()]);
        assert_eq!(&map["publint"], "publint");
    }

    #[test]
    fn bin_map_string_form_scoped() {
        let dir = tempfile::tempdir().unwrap();
        let nm = dir.path().join("node_modules/@scope/my-tool");
        std::fs::create_dir_all(&nm).unwrap();
        std::fs::write(
            nm.join("package.json"),
            r#"{"name": "@scope/my-tool", "bin": "./cli.js"}"#,
        )
        .unwrap();

        let map = build_bin_to_package_map(&[dir.path()], &["@scope/my-tool".to_string()]);
        assert_eq!(&map["my-tool"], "@scope/my-tool");
    }

    #[test]
    fn bin_map_missing_node_modules() {
        let map = build_bin_to_package_map(&[Path::new("/nonexistent")], &["foo".to_string()]);
        assert!(map.is_empty());
    }

    #[test]
    fn bin_map_no_bin_field() {
        let dir = tempfile::tempdir().unwrap();
        let nm = dir.path().join("node_modules/lodash");
        std::fs::create_dir_all(&nm).unwrap();
        std::fs::write(
            nm.join("package.json"),
            r#"{"name": "lodash", "main": "index.js"}"#,
        )
        .unwrap();

        let map = build_bin_to_package_map(&[dir.path()], &["lodash".to_string()]);
        assert!(map.is_empty());
    }

    #[test]
    fn bin_map_attw_scenario() {
        let dir = tempfile::tempdir().unwrap();
        let nm = dir.path().join("node_modules/@arethetypeswrong/cli");
        std::fs::create_dir_all(&nm).unwrap();
        std::fs::write(
            nm.join("package.json"),
            r#"{"name": "@arethetypeswrong/cli", "bin": {"attw": "./bin/cli.js"}}"#,
        )
        .unwrap();

        let map = build_bin_to_package_map(&[dir.path()], &["@arethetypeswrong/cli".to_string()]);
        assert_eq!(&map["attw"], "@arethetypeswrong/cli");
    }

    #[test]
    fn bin_map_workspace_fallback() {
        let root = tempfile::tempdir().unwrap();
        let ws = tempfile::tempdir().unwrap();
        let ws_nm = ws.path().join("node_modules/my-ws-tool");
        std::fs::create_dir_all(&ws_nm).unwrap();
        std::fs::write(
            ws_nm.join("package.json"),
            r#"{"name": "my-ws-tool", "bin": {"wstool": "./cli.js"}}"#,
        )
        .unwrap();

        let map = build_bin_to_package_map(&[root.path(), ws.path()], &["my-ws-tool".to_string()]);
        assert_eq!(&map["wstool"], "my-ws-tool");
    }

    fn workspace_package(json: &str) -> fallow_config::PackageJson {
        serde_json::from_str(json).unwrap()
    }

    #[test]
    fn workspace_bin_object_form_maps_each_name() {
        let pkg = workspace_package(
            r#"{"name": "@scope/tool", "bin": {"my-tool": "./a.js", "tool-alias": "./b.js"}}"#,
        );
        let mut map = empty_map();
        add_workspace_binaries(&mut map, [&pkg], &declared(&["@scope/tool"]));
        assert_eq!(map.get("my-tool").map(String::as_str), Some("@scope/tool"));
        assert_eq!(
            map.get("tool-alias").map(String::as_str),
            Some("@scope/tool")
        );
    }

    #[test]
    fn workspace_bin_string_form_uses_unscoped_name() {
        let pkg = workspace_package(r#"{"name": "@eggjs/scripts", "bin": "./bin/cli.js"}"#);
        let mut map = empty_map();
        add_workspace_binaries(&mut map, [&pkg], &declared(&["@eggjs/scripts"]));
        assert_eq!(
            map.get("scripts").map(String::as_str),
            Some("@eggjs/scripts")
        );
    }

    #[test]
    fn undeclared_workspace_package_bins_are_skipped() {
        let pkg = workspace_package(r#"{"name": "@scope/tool", "bin": {"my-tool": "./a.js"}}"#);
        let mut map = empty_map();
        add_workspace_binaries(&mut map, [&pkg], &declared(&["other"]));
        assert!(map.is_empty());
    }

    #[test]
    fn node_modules_bin_entry_wins_over_workspace_bin() {
        let pkg = workspace_package(r#"{"name": "@scope/tool", "bin": {"my-tool": "./a.js"}}"#);
        let mut map = empty_map();
        map.insert("my-tool".to_string(), "installed-tool".to_string());
        add_workspace_binaries(&mut map, [&pkg], &declared(&["@scope/tool"]));
        assert_eq!(
            map.get("my-tool").map(String::as_str),
            Some("installed-tool")
        );
    }
}