aube 1.29.0

Aube — a fast Node.js package manager
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
//! Shared helpers for the `patch` / `patch-commit` / `patch-remove`
//! commands and the install-time patch application path.
//!
//! Patches are stored alongside the project (default `patches/`) and
//! tracked as `{ "name@version": "patches/name@version.patch" }`.
//! Sources are merged from Bun's top-level `patchedDependencies`,
//! `pnpm.patchedDependencies` / `aube.patchedDependencies`, then
//! workspace-yaml `patchedDependencies`, in that precedence order.

use miette::{Context, IntoDiagnostic, Result, miette};
use sha2::{Digest, Sha256};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

/// One resolved patch entry. The key is `name@version` (the same
/// string used as the `pnpm.patchedDependencies` map key), `path` is
/// the absolute path on disk, and `content` is the raw patch text the
/// linker applies.
#[derive(Debug, Clone)]
pub struct ResolvedPatch {
    pub key: String,
    #[allow(dead_code)]
    pub name: String,
    #[allow(dead_code)]
    pub version: String,
    #[allow(dead_code)]
    pub path: PathBuf,
    pub content: String,
}

impl ResolvedPatch {
    /// Short hex digest of the patch content. Folded into the graph
    /// hash so a patched node lives at a different virtual-store path
    /// than the unpatched one.
    pub fn content_hash(&self) -> String {
        let mut h = Sha256::new();
        h.update(self.content.as_bytes());
        hex::encode(h.finalize())
    }
}

/// True when `rel` is a project-relative patch path that stays within
/// the project root. Refuses absolute paths, Windows drive or UNC
/// prefixes, NUL bytes, and any `..` component. Used as a read-side
/// guard so a hostile manifest cannot point the patch loader at
/// arbitrary files (e.g. `/etc/passwd` or `\\server\share\secret`).
fn is_safe_patch_rel(rel: &str) -> bool {
    if rel.is_empty() || rel.contains('\0') {
        return false;
    }
    let p = Path::new(rel);
    if p.is_absolute() || p.has_root() {
        return false;
    }
    // Reject a leading drive letter (`C:foo`) that `is_absolute` does
    // not always catch on the non-Windows host that rendered the
    // lockfile.
    if rel.len() >= 2 && rel.as_bytes()[1] == b':' {
        return false;
    }
    p.components().all(|c| {
        matches!(
            c,
            std::path::Component::Normal(_) | std::path::Component::CurDir
        )
    })
}

/// Split a `name@version` patch key into its parts. Mirrors
/// `commands::split_name_spec` but always requires a version (a bare
/// name is rejected — patches are always per-version).
pub fn split_patch_key(key: &str) -> Result<(String, String)> {
    let (name, ver) = if let Some(rest) = key.strip_prefix('@') {
        let slash = rest
            .find('/')
            .ok_or_else(|| miette!("invalid patch key {key:?}: scoped name missing slash"))?;
        let after = &rest[slash + 1..];
        let at = after
            .find('@')
            .ok_or_else(|| miette!("invalid patch key {key:?}: missing version"))?;
        let split = 1 + slash + 1 + at;
        (&key[..split], &key[split + 1..])
    } else {
        let at = key
            .find('@')
            .ok_or_else(|| miette!("invalid patch key {key:?}: missing version"))?;
        (&key[..at], &key[at + 1..])
    };
    if name.is_empty() || ver.is_empty() {
        return Err(miette!("invalid patch key {key:?}"));
    }
    Ok((name.to_string(), ver.to_string()))
}

/// Read every patch declared in the active lockfile, `package.json`,
/// and `pnpm-workspace.yaml`, then return them keyed by `name@version`.
/// Workspace-yaml entries (pnpm v10+ canonical location) win over
/// `package.json`, which wins over lockfile entries, on key conflict.
/// Missing patch files become a hard error — that matches pnpm, which
/// refuses to install with a declared-but-missing patch.
/// Load patches and pre-build the two shapes the linker + GVS-prewarm
/// materializer want: a `(name@version, content)` map and a
/// `(name@version, content_hash)` map. Both materializer call sites
/// (lockfile + no-lockfile) and the link phase compute these from the
/// same `load_patches` output, hoisted here so the BTreeMap walks
/// happen once per install.
///
/// Result is cached per cwd for the lifetime of the process. The 2-3
/// call sites within a single install hit the cache on calls 2+ instead
/// of re-walking `patches/` from disk. pnpm.patchedDependencies is
/// resolved at install entry; patch files are static across the run.
pub fn load_patches_for_linker(
    cwd: &Path,
    lockfile_patched_dependencies: &BTreeMap<String, String>,
) -> Result<(aube_linker::Patches, BTreeMap<String, String>)> {
    use std::sync::{Mutex, OnceLock};
    type CacheKey = (PathBuf, BTreeMap<String, String>);
    type CachedShape = (aube_linker::Patches, BTreeMap<String, String>);
    static CACHE: OnceLock<Mutex<std::collections::HashMap<CacheKey, CachedShape>>> =
        OnceLock::new();
    let cache = CACHE.get_or_init(|| Mutex::new(std::collections::HashMap::new()));
    // Canonicalize so `cwd` and `cwd.canonicalize()` collapse to one
    // key. Windows `\\?\C:\foo` vs `C:\foo`, Unix `cwd` vs `cwd/.`
    // would otherwise miss the cache. Falls back to the raw path when
    // canonicalize fails (e.g. cwd is the parent of a not-yet-created
    // workspace dir).
    let key = (
        cwd.canonicalize().unwrap_or_else(|_| cwd.to_path_buf()),
        lockfile_patched_dependencies.clone(),
    );
    if let Ok(guard) = cache.lock()
        && let Some(hit) = guard.get(&key)
    {
        return Ok(hit.clone());
    }
    let resolved = load_patches_with_lockfile_entries(cwd, lockfile_patched_dependencies)?;
    let patches: aube_linker::Patches = resolved
        .values()
        .map(|p| (p.key.clone(), p.content.clone()))
        .collect();
    let hashes: BTreeMap<String, String> = resolved
        .values()
        .map(|p| (p.key.clone(), p.content_hash()))
        .collect();
    if let Ok(mut guard) = cache.lock() {
        guard.insert(key, (patches.clone(), hashes.clone()));
    }
    Ok((patches, hashes))
}

#[cfg(test)]
fn load_patches(cwd: &Path) -> Result<BTreeMap<String, ResolvedPatch>> {
    load_patches_with_lockfile_entries(cwd, &BTreeMap::new())
}

fn load_patches_with_lockfile_entries(
    cwd: &Path,
    lockfile_patched_dependencies: &BTreeMap<String, String>,
) -> Result<BTreeMap<String, ResolvedPatch>> {
    let mut entries: BTreeMap<String, String> = BTreeMap::new();
    entries.extend(lockfile_patched_dependencies.clone());

    let manifest_path = cwd.join("package.json");
    if manifest_path.exists() {
        let manifest = aube_manifest::PackageJson::from_path(&manifest_path)
            .map_err(miette::Report::new)
            .wrap_err("failed to read package.json")?;
        entries.extend(manifest.bun_patched_dependencies());
        entries.extend(manifest.pnpm_patched_dependencies());
    }

    let ws_config = aube_manifest::workspace::WorkspaceConfig::load(cwd)
        .map_err(miette::Report::new)
        .wrap_err("failed to read pnpm-workspace.yaml")?;
    entries.extend(ws_config.patched_dependencies);

    let mut out = BTreeMap::new();
    for (key, rel) in entries {
        let (name, version) = split_patch_key(&key)?;
        // Refuse absolute paths and `..` traversal in the manifest-
        // declared patch path so a hostile `package.json` cannot
        // coerce `aube install` into reading an arbitrary file off
        // disk. The linker already guards the *apply* side with
        // `is_safe_rel_component`, and mirroring the same check on
        // the *read* side keeps the trust boundary uniform.
        if !is_safe_patch_rel(&rel) {
            return Err(miette!(
                "refusing unsafe patch path for {key}: {rel:?} (absolute, UNC, or contains `..`)"
            ));
        }
        let path = cwd.join(&rel);
        let content = std::fs::read_to_string(&path)
            .into_diagnostic()
            .map_err(|e| {
                miette!(
                    "failed to read patch file {} for {key}: {e}",
                    path.display()
                )
            })?;
        out.insert(
            key.clone(),
            ResolvedPatch {
                key,
                name,
                version,
                path,
                content,
            },
        );
    }
    Ok(out)
}

/// Add or replace an entry in `patchedDependencies`. Routes through
/// the shared [`aube_manifest::workspace::config_write_target`] rule:
/// workspace yaml when one is present, otherwise `package.json`.
/// Returns the path that was rewritten so the caller can report it to
/// the user.
pub fn upsert_patched_dependency(cwd: &Path, key: &str, rel_patch_path: &str) -> Result<PathBuf> {
    use aube_manifest::workspace::ConfigWriteTarget;
    match aube_manifest::workspace::config_write_target(cwd) {
        ConfigWriteTarget::PackageJson => {
            aube_manifest::workspace::edit_setting_map(cwd, "patchedDependencies", |map| {
                map.insert(
                    key.to_string(),
                    serde_json::Value::String(rel_patch_path.to_string()),
                );
            })
            .map_err(miette::Report::new)
            .wrap_err("failed to write package.json")?;
            Ok(cwd.join("package.json"))
        }
        ConfigWriteTarget::WorkspaceYaml(path) => {
            aube_manifest::workspace::upsert_workspace_patched_dependency(
                &path,
                key,
                rel_patch_path,
            )
            .map_err(miette::Report::new)
            .wrap_err_with(|| format!("failed to write {}", path.display()))?;
            Ok(path)
        }
    }
}

/// Drop an entry from `patchedDependencies` in whichever file declares
/// it (workspace yaml, Bun's top-level
/// `package.json#patchedDependencies`,
/// `package.json#pnpm.patchedDependencies`,
/// `package.json#aube.patchedDependencies`, or any combination).
/// Returns the files that were rewritten — empty when no location held
/// the entry. Each side peeks before rewriting so the no-op case
/// leaves the file (and any user yaml comments) intact.
pub fn remove_patched_dependency(cwd: &Path, key: &str) -> Result<Vec<PathBuf>> {
    let mut rewritten = Vec::new();
    if let Some(ws_path) = aube_manifest::workspace::workspace_yaml_existing(cwd)
        && aube_manifest::workspace::remove_workspace_patched_dependency(&ws_path, key)
            .map_err(miette::Report::new)
            .wrap_err_with(|| format!("failed to write {}", ws_path.display()))?
    {
        rewritten.push(ws_path);
    }
    let removed_namespaced =
        aube_manifest::workspace::remove_setting_entry(cwd, "patchedDependencies", key)
            .map_err(miette::Report::new)
            .wrap_err("failed to write package.json")?;
    let removed_bun =
        remove_bun_patched_dependency(cwd, key).wrap_err("failed to write package.json")?;
    if removed_namespaced || removed_bun {
        rewritten.push(cwd.join("package.json"));
    }
    Ok(rewritten)
}

fn remove_bun_patched_dependency(cwd: &Path, key: &str) -> Result<bool> {
    let path = cwd.join("package.json");
    if !path.exists() {
        return Ok(false);
    }
    let raw = std::fs::read_to_string(&path)
        .into_diagnostic()
        .map_err(|e| miette!("failed to read {}: {e}", path.display()))?;
    let mut value =
        aube_manifest::parse_json::<serde_json::Value>(&path, raw).map_err(miette::Report::new)?;
    let obj = value
        .as_object_mut()
        .ok_or_else(|| miette!("package.json is not an object"))?;
    let before = obj.clone();

    let mut remove_empty_map = false;
    let removed = if let Some(patched) = obj
        .get_mut("patchedDependencies")
        .and_then(serde_json::Value::as_object_mut)
    {
        let removed = patched.remove(key).is_some();
        if removed {
            remove_empty_map = patched.is_empty();
        }
        removed
    } else {
        false
    };
    if remove_empty_map {
        obj.remove("patchedDependencies");
    }
    if *obj == before {
        return Ok(removed);
    }

    let mut out = serde_json::to_string_pretty(&value)
        .into_diagnostic()
        .map_err(|e| miette!("failed to serialize {}: {e}", path.display()))?;
    out.push('\n');
    std::fs::write(&path, out)
        .into_diagnostic()
        .map_err(|e| miette!("failed to write {}: {e}", path.display()))?;
    Ok(removed)
}

/// Read every declared `patchedDependencies` entry across both the
/// workspace yaml and `package.json`, with workspace-yaml entries
/// winning on key conflict (same precedence used by `load_patches`).
pub fn read_patched_dependencies(cwd: &Path) -> Result<BTreeMap<String, String>> {
    let mut out = read_package_json_patched_dependencies(cwd)?;
    let ws_config = aube_manifest::workspace::WorkspaceConfig::load(cwd)
        .map_err(miette::Report::new)
        .wrap_err("failed to read workspace yaml")?;
    out.extend(ws_config.patched_dependencies);
    Ok(out)
}

fn read_package_json_patched_dependencies(cwd: &Path) -> Result<BTreeMap<String, String>> {
    let manifest_path = cwd.join("package.json");
    if !manifest_path.exists() {
        return Ok(BTreeMap::new());
    }
    let manifest = aube_manifest::PackageJson::from_path(&manifest_path)
        .map_err(miette::Report::new)
        .wrap_err("failed to read package.json")?;
    let mut out = manifest.bun_patched_dependencies();
    out.extend(manifest.pnpm_patched_dependencies());
    Ok(out)
}

/// Recursively copy `src` into `dst`, following file content but
/// preserving relative layout. Used by `aube patch` to snapshot a
/// package out of the virtual store into both a "source" reference
/// directory and a "user edit" directory.
pub fn copy_dir_all(src: &Path, dst: &Path) -> Result<()> {
    std::fs::create_dir_all(dst)
        .into_diagnostic()
        .map_err(|e| miette!("failed to create {}: {e}", dst.display()))?;
    for entry in std::fs::read_dir(src)
        .into_diagnostic()
        .map_err(|e| miette!("failed to read {}: {e}", src.display()))?
    {
        let entry = entry
            .into_diagnostic()
            .map_err(|e| miette!("failed to read entry under {}: {e}", src.display()))?;
        let ty = entry
            .file_type()
            .into_diagnostic()
            .map_err(|e| miette!("failed to stat {}: {e}", entry.path().display()))?;
        let from = entry.path();
        let to = dst.join(entry.file_name());
        if ty.is_dir() {
            copy_dir_all(&from, &to)?;
        } else if ty.is_symlink() {
            // Skip symlinks — packages we extract from the virtual
            // store can contain `node_modules` symlinks pointing into
            // sibling packages, which we don't want to drag into the
            // patch source dir.
            continue;
        } else {
            std::fs::copy(&from, &to).into_diagnostic().map_err(|e| {
                miette!("failed to copy {} -> {}: {e}", from.display(), to.display())
            })?;
        }
    }
    Ok(())
}

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

    #[test]
    fn split_simple() {
        let (n, v) = split_patch_key("is-positive@3.1.0").unwrap();
        assert_eq!(n, "is-positive");
        assert_eq!(v, "3.1.0");
    }

    #[test]
    fn split_scoped() {
        let (n, v) = split_patch_key("@babel/core@7.0.0").unwrap();
        assert_eq!(n, "@babel/core");
        assert_eq!(v, "7.0.0");
    }

    #[test]
    fn split_missing_version_errors() {
        assert!(split_patch_key("is-positive").is_err());
        assert!(split_patch_key("@babel/core").is_err());
    }

    #[test]
    fn upsert_writes_to_yaml_when_one_exists() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("package.json"), "{}\n").unwrap();
        std::fs::write(
            dir.path().join("pnpm-workspace.yaml"),
            "packages:\n  - 'pkgs/*'\n",
        )
        .unwrap();
        let written =
            upsert_patched_dependency(dir.path(), "a@1.0.0", "patches/a@1.0.0.patch").unwrap();
        assert_eq!(written, dir.path().join("pnpm-workspace.yaml"));
    }

    #[test]
    fn upsert_writes_to_package_json_when_no_yaml() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("package.json"), "{}\n").unwrap();
        let written =
            upsert_patched_dependency(dir.path(), "a@1.0.0", "patches/a@1.0.0.patch").unwrap();
        assert_eq!(written, dir.path().join("package.json"));
    }

    #[test]
    fn upsert_writes_to_aube_namespace_when_no_pnpm_in_manifest() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("package.json"), "{}\n").unwrap();
        upsert_patched_dependency(dir.path(), "a@1.0.0", "patches/a@1.0.0.patch").unwrap();
        let manifest = std::fs::read_to_string(dir.path().join("package.json")).unwrap();
        assert!(
            manifest.contains("\"aube\""),
            "expected aube namespace, got:\n{manifest}"
        );
        assert!(
            !manifest.contains("\"pnpm\""),
            "should not introduce pnpm namespace, got:\n{manifest}"
        );
        assert!(manifest.contains("\"patchedDependencies\""));
    }

    #[test]
    fn load_reads_bun_top_level_patched_dependencies() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir(dir.path().join("patches")).unwrap();
        std::fs::write(
            dir.path().join("package.json"),
            r#"{
  "patchedDependencies": {
    "is-number@7.0.0": "patches/is-number.patch"
  }
}
"#,
        )
        .unwrap();
        std::fs::write(
            dir.path().join("patches/is-number.patch"),
            "diff --git a/index.js b/index.js\n",
        )
        .unwrap();

        let patches = load_patches(dir.path()).unwrap();
        assert_eq!(
            patches
                .get("is-number@7.0.0")
                .map(|p| p.path.strip_prefix(dir.path()).unwrap()),
            Some(Path::new("patches/is-number.patch"))
        );
    }

    #[test]
    fn upsert_collapses_shadow_when_other_namespace_holds_stale_entry() {
        // A pnpm-aware tool can add a `pnpm` namespace after aube has
        // already populated `aube.patchedDependencies`. Without the
        // merge-and-collapse below, the next `aube patch-commit` would
        // write to `pnpm.patchedDependencies` while the stale
        // `aube.patchedDependencies.<key>` entry shadowed it on read
        // (aube.* wins on conflict). Pin the post-write invariant:
        // exactly one namespace holds the entry.
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("package.json"),
            "{\"aube\":{\"patchedDependencies\":{\"a@1.0.0\":\"patches/old.patch\"}},\"pnpm\":{\"someKey\":1}}\n",
        )
        .unwrap();
        upsert_patched_dependency(dir.path(), "a@1.0.0", "patches/new.patch").unwrap();
        let raw = std::fs::read_to_string(dir.path().join("package.json")).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&raw).unwrap();
        // Entry migrated to pnpm.patchedDependencies, with the new value.
        assert_eq!(
            parsed["pnpm"]["patchedDependencies"]["a@1.0.0"],
            "patches/new.patch"
        );
        // Stale aube.patchedDependencies entry is gone — no shadow.
        assert!(parsed["aube"]["patchedDependencies"].is_null());
        // The user's other pnpm config is preserved.
        assert_eq!(parsed["pnpm"]["someKey"], 1);
    }

    #[test]
    fn upsert_writes_to_pnpm_namespace_when_pnpm_already_present() {
        let dir = tempfile::tempdir().unwrap();
        // User already has a pnpm-namespaced setting (allowBuilds);
        // a new patch should land in the same pnpm bucket so we don't
        // fragment their config across two namespaces.
        std::fs::write(
            dir.path().join("package.json"),
            "{\"pnpm\":{\"allowBuilds\":{\"esbuild\":true}}}\n",
        )
        .unwrap();
        upsert_patched_dependency(dir.path(), "a@1.0.0", "patches/a@1.0.0.patch").unwrap();
        let manifest = std::fs::read_to_string(dir.path().join("package.json")).unwrap();
        assert!(manifest.contains("\"pnpm\""));
        assert!(
            !manifest.contains("\"aube\""),
            "should not introduce aube namespace alongside pnpm: {manifest}"
        );
        // The patch entry must be inside pnpm.
        let parsed: serde_json::Value = serde_json::from_str(&manifest).unwrap();
        assert!(parsed["pnpm"]["patchedDependencies"]["a@1.0.0"].is_string());
    }

    #[test]
    fn remove_deletes_bun_top_level_patched_dependency() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("package.json"),
            r#"{
  "patchedDependencies": {
    "a@1.0.0": "patches/a.patch",
    "b@2.0.0": "patches/b.patch"
  }
}
"#,
        )
        .unwrap();

        let rewritten = remove_patched_dependency(dir.path(), "a@1.0.0").unwrap();
        assert_eq!(rewritten, vec![dir.path().join("package.json")]);
        let parsed: serde_json::Value = serde_json::from_str(
            &std::fs::read_to_string(dir.path().join("package.json")).unwrap(),
        )
        .unwrap();
        assert!(parsed["patchedDependencies"]["a@1.0.0"].is_null());
        assert_eq!(parsed["patchedDependencies"]["b@2.0.0"], "patches/b.patch");
    }

    #[test]
    fn remove_drops_empty_bun_top_level_patched_dependencies() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("package.json"),
            r#"{
  "patchedDependencies": {
    "a@1.0.0": "patches/a.patch"
  }
}
"#,
        )
        .unwrap();

        remove_patched_dependency(dir.path(), "a@1.0.0").unwrap();
        let parsed: serde_json::Value = serde_json::from_str(
            &std::fs::read_to_string(dir.path().join("package.json")).unwrap(),
        )
        .unwrap();
        assert!(parsed["patchedDependencies"].is_null());
    }

    #[test]
    fn remove_leaves_empty_bun_top_level_map_when_key_missing() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("package.json"),
            "{\n  \"patchedDependencies\": {}\n}\n",
        )
        .unwrap();

        let rewritten = remove_patched_dependency(dir.path(), "missing@9.9.9").unwrap();
        assert!(rewritten.is_empty());
        assert_eq!(
            std::fs::read_to_string(dir.path().join("package.json")).unwrap(),
            "{\n  \"patchedDependencies\": {}\n}\n"
        );
    }

    #[test]
    fn remove_reads_bom_prefixed_package_json() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("package.json"),
            "\u{feff}{\n  \"patchedDependencies\": {\n    \"a@1.0.0\": \"patches/a.patch\"\n  }\n}\n",
        )
        .unwrap();

        let rewritten = remove_patched_dependency(dir.path(), "a@1.0.0").unwrap();
        assert_eq!(rewritten, vec![dir.path().join("package.json")]);
        let parsed: serde_json::Value = serde_json::from_str(
            &std::fs::read_to_string(dir.path().join("package.json")).unwrap(),
        )
        .unwrap();
        assert!(parsed["patchedDependencies"].is_null());
    }

    #[test]
    fn load_reads_lockfile_patched_dependencies() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".yarn/patches")).unwrap();
        std::fs::write(
            dir.path().join(".yarn/patches/is-number.patch"),
            "diff --git a/index.js b/index.js\n",
        )
        .unwrap();

        let (patches, hashes) = load_patches_for_linker(
            dir.path(),
            &BTreeMap::from([(
                "is-number@7.0.0".to_string(),
                ".yarn/patches/is-number.patch".to_string(),
            )]),
        )
        .unwrap();

        assert_eq!(
            patches.get("is-number@7.0.0").map(String::as_str),
            Some("diff --git a/index.js b/index.js\n")
        );
        assert!(hashes.contains_key("is-number@7.0.0"));
    }

    #[test]
    fn remove_returns_each_rewritten_file() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("package.json"),
            "{\"pnpm\":{\"patchedDependencies\":{\"a@1.0.0\":\"patches/a@1.0.0.patch\"}}}\n",
        )
        .unwrap();
        std::fs::write(
            dir.path().join("pnpm-workspace.yaml"),
            "patchedDependencies:\n  \"a@1.0.0\": patches/a@1.0.0.patch\n",
        )
        .unwrap();
        let rewritten = remove_patched_dependency(dir.path(), "a@1.0.0").unwrap();
        let names: Vec<String> = rewritten
            .iter()
            .filter_map(|p| p.file_name().map(|n| n.to_string_lossy().into_owned()))
            .collect();
        assert_eq!(names, vec!["pnpm-workspace.yaml", "package.json"]);
    }

    #[test]
    fn remove_returns_empty_when_neither_file_holds_key() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("package.json"), "{}\n").unwrap();
        std::fs::write(
            dir.path().join("pnpm-workspace.yaml"),
            "packages:\n  - 'pkgs/*'\n",
        )
        .unwrap();
        let rewritten = remove_patched_dependency(dir.path(), "missing@9.9.9").unwrap();
        assert!(rewritten.is_empty());
    }
}