deps-core 2.0.0

Core abstractions for deps-lsp: caching, errors, and traits
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
//! Newtypes distinguishing package names, version requirement strings, and
//! concrete resolved versions.
//!
//! [`PackageName`], [`VersionReq`], and [`ConcreteVersion`] wrap `String` to
//! give these kinds of manifest and registry data their own types, so a
//! function that expects one cannot accidentally be called with another.
//! None of these types validate, trim, or normalize their contents:
//! ecosystem-specific normalization (case folding, separator rewriting,
//! etc.) belongs to `EcosystemFormatter`, not to these types. See each
//! type's documentation for details.

use std::borrow::Borrow;
use std::fmt;

/// A package/crate name as it appears in a manifest file.
///
/// This is deliberately permissive: it stores whatever bytes the manifest
/// contained, including the empty string, leading/trailing whitespace, or
/// non-ASCII characters. No validation, trimming, or normalization is
/// performed by this type.
///
/// For several ecosystems this is not a "package name" in the narrow sense
/// but a registry lookup key: Maven and Gradle store `"group:artifact"`, Swift
/// stores `"owner/repo"`, and Go stores a URL-like module path. All of these
/// are valid `PackageName` values. Ecosystem-specific normalization (case
/// folding, separator rewriting, etc.) is the responsibility of
/// `EcosystemFormatter`, not this type — do not add validation rules here,
/// as it would silently break those ecosystems.
///
/// This type has no [`Display`](fmt::Display) impl, and its [`Debug`](fmt::Debug) impl
/// redacts via [`crate::redact::redact_declaration_key`] rather than deriving (#1217) —
/// see [`Self::for_tracing`] for why, and use [`Self::as_str`]/[`Self::as_ref`]/
/// [`Self::into_string`] for the raw value.
///
/// # Examples
///
/// ```
/// use deps_core::PackageName;
///
/// let name = PackageName::new("serde");
/// assert_eq!(name.as_str(), "serde");
/// assert_eq!(name, "serde");
/// ```
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct PackageName(String);

impl PackageName {
    /// Wraps `value` as a `PackageName`, unchanged.
    ///
    /// This never fails and never modifies its input: an empty string is a
    /// valid `PackageName`, as is a string with surrounding whitespace.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::PackageName;
    ///
    /// let name = PackageName::new(String::from("tokio"));
    /// assert_eq!(name.as_str(), "tokio");
    /// ```
    pub fn new(value: impl Into<String>) -> Self {
        Self(value.into())
    }

    /// Returns the package name as a string slice.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::PackageName;
    ///
    /// let name = PackageName::new("axum");
    /// assert_eq!(name.as_str(), "axum");
    /// ```
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consumes the `PackageName`, returning the wrapped `String`.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::PackageName;
    ///
    /// let name = PackageName::new("axum");
    /// let owned: String = name.into_string();
    /// assert_eq!(owned, "axum");
    /// ```
    #[must_use]
    pub fn into_string(self) -> String {
        self.0
    }

    /// Renders this name for `tracing`/log output, redacting it via
    /// [`crate::redact::redact_declaration_key`] first (#1209).
    ///
    /// A manifest can hold a credential in a name-shaped field (e.g. a Maven
    /// `group:artifact:secret@host` coordinate produced by property
    /// interpolation), and this type's raw accessors ([`Self::as_str`], [`Self::as_ref`],
    /// [`Self::into_string`]) return the string verbatim — so any `tracing` field or span
    /// built from a `PackageName` must go through this method instead. (`?name` and
    /// `Debug`-derived output are already safe — see [`Self`]'s `Debug` impl — but `%name`,
    /// which requires `Display`, does not compile at all, since `PackageName` has none.) An
    /// ordinary package name (including scoped ones like `@types/node` or
    /// `com.google.guava:guava`) passes through unchanged.
    ///
    /// The result is also swept for control/format characters (`\n`, `\r`, a raw ESC byte, and
    /// the wider Unicode `Cc`/`Cf`/`Zl`/`Zp` set), via
    /// [`redact_declaration_key`](crate::redact::redact_declaration_key)'s own final pass — a
    /// manifest-controlled name has no credential shape to trigger the redaction above, but could
    /// otherwise forge a whole `tracing` log line or terminal escape sequence verbatim (#1469).
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::PackageName;
    ///
    /// let name = PackageName::new("com.google.guava:guava");
    /// assert_eq!(name.for_tracing(), "com.google.guava:guava");
    ///
    /// let name = PackageName::new("com.google.guava:deploy:TOKEN@git.internal.corp");
    /// assert_eq!(name.for_tracing(), "***@git.internal.corp");
    ///
    /// let name = PackageName::new("lodash\nERROR deps_lsp: FORGED\x1b[31mRED");
    /// assert_eq!(name.for_tracing(), "lodash ERROR deps_lsp: FORGED [31mRED");
    /// ```
    #[must_use]
    pub fn for_tracing(&self) -> String {
        crate::redact::redact_declaration_key(&self.0).into_owned()
    }
}

impl fmt::Debug for PackageName {
    /// Forwards to the redacted text's own `Debug` (a quoted string), not a struct-wrapper
    /// rendering — mirrors [`crate::redact::RedactedName`]'s `Debug` impl. This makes
    /// `?name`, and any `#[derive(Debug)]` struct/enum that embeds a `PackageName`, safe by
    /// construction against the credential-in-a-name-shaped-field case [`Self::for_tracing`]
    /// documents (#1217).
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&crate::redact::redact_declaration_key(&self.0), f)
    }
}

impl From<String> for PackageName {
    fn from(value: String) -> Self {
        Self(value)
    }
}

impl From<&str> for PackageName {
    fn from(value: &str) -> Self {
        Self(value.to_string())
    }
}

impl AsRef<str> for PackageName {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

/// Enables `&str` lookups into `HashMap<PackageName, _>`/`HashSet<PackageName>`.
///
/// Sound because derived `Hash`/`Eq` on `PackageName(String)` delegate to
/// `String`'s implementations, which in turn are defined to match `str`'s
/// exactly (`String: Borrow<str>` in `std` rests on the same guarantee) — so
/// `PackageName` and the `str` it borrows always hash and compare equal.
impl Borrow<str> for PackageName {
    fn borrow(&self) -> &str {
        &self.0
    }
}

impl PartialEq<str> for PackageName {
    fn eq(&self, other: &str) -> bool {
        self.0 == other
    }
}

impl PartialEq<&str> for PackageName {
    fn eq(&self, other: &&str) -> bool {
        self.0 == *other
    }
}

/// A package name that failed a [`PackageNaming::validate_package_name`] lint.
///
/// This is not a construction-time gate — [`PackageName::new`] stays infallible — it
/// only carries *why* a name looks wrong so an LSP diagnostic can say something more
/// specific than "invalid name".
///
/// Also the payload of [`DepsError::InvalidPackageName`] (#1514): `deps-go`'s
/// `validate_module_path` returns this type directly, propagated into `DepsError` via
/// `#[from]`, so a malformed Go module path shares this same "why was the name rejected"
/// carrier instead of a second, ecosystem-local error type.
///
/// [`PackageNaming::validate_package_name`]: crate::lsp_helpers::PackageNaming::validate_package_name
/// [`DepsError::InvalidPackageName`]: crate::DepsError::InvalidPackageName
///
/// # Examples
///
/// ```
/// use deps_core::InvalidPackageName;
///
/// let err = InvalidPackageName::new("name is longer than 214 characters");
/// assert_eq!(err.reason(), "name is longer than 214 characters");
/// assert_eq!(err.to_string(), "name is longer than 214 characters");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("{0}")]
pub struct InvalidPackageName(std::borrow::Cow<'static, str>);

impl InvalidPackageName {
    /// Creates an `InvalidPackageName` carrying `reason` as the explanation.
    pub fn new(reason: impl Into<std::borrow::Cow<'static, str>>) -> Self {
        Self(reason.into())
    }

    /// Returns why the name was rejected.
    #[must_use]
    pub fn reason(&self) -> &str {
        &self.0
    }
}

/// A version requirement string as it appears in a manifest file.
///
/// This is deliberately permissive: it stores whatever bytes the manifest
/// contained (e.g. `"^1.0"`, `">=2.0,<3.0"`, `"*"`), including the empty
/// string. No parsing, validation, trimming, or normalization is performed
/// by this type — ecosystems that need to parse a requirement (via `semver`,
/// `node-semver`, `pep440_rs`, etc.) do so from [`VersionReq::as_str`], not
/// from this type. Note that `deps-go`'s `GoDependency.version` also uses this
/// type even though it holds an exact pinned version (e.g. `"v1.9.1"`), not a
/// range or constraint — Go modules don't have a separate "requirement"
/// concept, so the exact version doubles as the requirement.
///
/// # Examples
///
/// ```
/// use deps_core::VersionReq;
///
/// let req = VersionReq::new("^1.0");
/// assert_eq!(req.as_str(), "^1.0");
/// assert_eq!(req, "^1.0");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct VersionReq(String);

impl VersionReq {
    /// Wraps `value` as a `VersionReq`, unchanged.
    ///
    /// This never fails and never modifies its input: an empty string is a
    /// valid `VersionReq`, as is a string with surrounding whitespace.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::VersionReq;
    ///
    /// let req = VersionReq::new(String::from(">=1.0"));
    /// assert_eq!(req.as_str(), ">=1.0");
    /// ```
    pub fn new(value: impl Into<String>) -> Self {
        Self(value.into())
    }

    /// Returns the version requirement as a string slice.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::VersionReq;
    ///
    /// let req = VersionReq::new("~1.2");
    /// assert_eq!(req.as_str(), "~1.2");
    /// ```
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consumes the `VersionReq`, returning the wrapped `String`.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::VersionReq;
    ///
    /// let req = VersionReq::new("~1.2");
    /// let owned: String = req.into_string();
    /// assert_eq!(owned, "~1.2");
    /// ```
    #[must_use]
    pub fn into_string(self) -> String {
        self.0
    }
}

impl fmt::Display for VersionReq {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl From<String> for VersionReq {
    fn from(value: String) -> Self {
        Self(value)
    }
}

impl From<&str> for VersionReq {
    fn from(value: &str) -> Self {
        Self(value.to_string())
    }
}

impl AsRef<str> for VersionReq {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl PartialEq<str> for VersionReq {
    fn eq(&self, other: &str) -> bool {
        self.0 == other
    }
}

impl PartialEq<&str> for VersionReq {
    fn eq(&self, other: &&str) -> bool {
        self.0 == *other
    }
}

/// A concrete, resolved version string as returned by a registry.
///
/// This is deliberately permissive: it stores whatever bytes the registry
/// returned (e.g. `"1.2.3"`, `"2.0.0-beta.1"`), including the empty string.
/// No parsing, validation, trimming, or normalization is performed by this
/// type — ecosystems that need to parse a version (via `semver`,
/// `node-semver`, `pep440_rs`, etc.) do so from [`ConcreteVersion::as_str`],
/// not from this type. It is distinct from [`VersionReq`]: a `VersionReq` is
/// a constraint written in a manifest (`"^1.0"`), while a `ConcreteVersion`
/// is a single resolved version (`"1.0.4"`).
///
/// # Examples
///
/// ```
/// use deps_core::ConcreteVersion;
///
/// let version = ConcreteVersion::new("1.2.3");
/// assert_eq!(version.as_str(), "1.2.3");
/// assert_eq!(version, "1.2.3");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ConcreteVersion(String);

impl ConcreteVersion {
    /// Wraps `value` as a `ConcreteVersion`, unchanged.
    ///
    /// This never fails and never modifies its input: an empty string is a
    /// valid `ConcreteVersion`, as is a string with surrounding whitespace.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::ConcreteVersion;
    ///
    /// let version = ConcreteVersion::new(String::from("1.0.0"));
    /// assert_eq!(version.as_str(), "1.0.0");
    /// ```
    pub fn new(value: impl Into<String>) -> Self {
        Self(value.into())
    }

    /// Returns the concrete version as a string slice.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::ConcreteVersion;
    ///
    /// let version = ConcreteVersion::new("4.5.6");
    /// assert_eq!(version.as_str(), "4.5.6");
    /// ```
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consumes the `ConcreteVersion`, returning the wrapped `String`.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::ConcreteVersion;
    ///
    /// let version = ConcreteVersion::new("4.5.6");
    /// let owned: String = version.into_string();
    /// assert_eq!(owned, "4.5.6");
    /// ```
    #[must_use]
    pub fn into_string(self) -> String {
        self.0
    }

    /// Whether `self` and `other` are the same version once semver build metadata
    /// (`+...`, which carries no precedence) is ignored.
    ///
    /// Follows SemVer 2.0.0 precedence only; ecosystems where a `+N` suffix denotes a
    /// distinct release (e.g. pub.dev build numbers) are out of scope.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::ConcreteVersion;
    ///
    /// let resolved = ConcreteVersion::new("1.2.3");
    /// assert!(resolved.eq_ignoring_build_metadata(&ConcreteVersion::new("1.2.3+build.7")));
    /// assert!(!resolved.eq_ignoring_build_metadata(&ConcreteVersion::new("1.2.4+build.7")));
    /// ```
    #[must_use]
    pub fn eq_ignoring_build_metadata(&self, other: &Self) -> bool {
        strip_build_metadata(&self.0) == strip_build_metadata(&other.0)
    }
}

impl fmt::Display for ConcreteVersion {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl From<String> for ConcreteVersion {
    fn from(value: String) -> Self {
        Self(value)
    }
}

impl From<&str> for ConcreteVersion {
    fn from(value: &str) -> Self {
        Self(value.to_string())
    }
}

impl AsRef<str> for ConcreteVersion {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl PartialEq<str> for ConcreteVersion {
    fn eq(&self, other: &str) -> bool {
        self.0 == other
    }
}

impl PartialEq<&str> for ConcreteVersion {
    fn eq(&self, other: &&str) -> bool {
        self.0 == *other
    }
}

/// `version` without its semver build metadata (`+...`), which carries no precedence.
pub(crate) fn strip_build_metadata(version: &str) -> &str {
    version
        .split_once('+')
        .map_or(version, |(precedence, _)| precedence)
}

/// Length, in bytes, of an `@scope/pkg` or unscoped `pkg` name at the start of `rest`.
///
/// Follows the scoped-package grammar shared by npm-style ecosystems: the name runs up to
/// (but excludes) the first `@` or `/` after it, without mistaking a scoped name's own
/// leading `@` or inner `/` for that boundary.
///
/// Shared by `deps-npm`'s `npm:` alias parsing (issue #654) and `deps-deno`'s
/// `jsr:`/`npm:` specifier grammar (`deps_deno::specifier::parse_specifier`) — both need
/// the identical scope-aware boundary, and a per-crate reimplementation had drifted looser
/// than this one (accepting `"@/pkg"`, `"@scope/"`, and a lone `"@"` as valid names).
///
/// Returns `None` for a malformed scoped name (empty scope `"@/pkg"`, missing `/` `"@std"`,
/// or an empty package segment `"@std/"`) or an empty unscoped name (`rest` is empty, or
/// starts with `@`/`/`).
///
/// # Examples
///
/// ```
/// use deps_core::package::npm_style_name_boundary;
///
/// assert_eq!(npm_style_name_boundary("react@^18.0.0"), Some(5));
/// assert_eq!(npm_style_name_boundary("@scope/pkg@^1.0.0"), Some(10));
/// assert_eq!(npm_style_name_boundary("@scope/pkg"), Some(10));
/// assert_eq!(npm_style_name_boundary("@/pkg"), None);
/// assert_eq!(npm_style_name_boundary("@scope/"), None);
/// assert_eq!(npm_style_name_boundary("@"), None);
/// assert_eq!(npm_style_name_boundary(""), None);
/// ```
#[expect(
    clippy::string_slice,
    reason = "slash_rel comes from str::find('/'), an ASCII byte, so slash_rel + 1 is always \
              a char boundary"
)]
#[must_use]
pub fn npm_style_name_boundary(rest: &str) -> Option<usize> {
    if let Some(after_at) = rest.strip_prefix('@') {
        let slash_rel = after_at.find('/')?;
        if slash_rel == 0 {
            return None; // empty scope, e.g. "@/pkg"
        }
        let after_slash = &after_at[slash_rel + 1..];
        let pkg_end_rel = after_slash.find(['@', '/']).unwrap_or(after_slash.len());
        if pkg_end_rel == 0 {
            return None; // empty pkg name, e.g. "@scope/"
        }
        Some(1 + slash_rel + 1 + pkg_end_rel)
    } else {
        let end = rest.find(['@', '/']).unwrap_or(rest.len());
        (end > 0).then_some(end)
    }
}

#[cfg(test)]
mod tests {
    use super::{ConcreteVersion, PackageName, VersionReq};

    #[test]
    fn eq_ignoring_build_metadata_cases() {
        for (a, b, expected) in [
            ("1.2.3", "1.2.3", true),
            ("1.2.3+a", "1.2.3+b", true),
            ("1.2.3", "1.2.3+b", true),
            ("1.2.3+a", "1.2.3", true),
            ("1.2.3", "1.2.4+b", false),
            ("1.2.3-beta.1", "1.2.3+b", false),
            ("1.2.3-beta.1+a", "1.2.3-beta.1+b", true),
            ("1.2.3+", "1.2.3", true),
            ("1.2.3+a+b", "1.2.3+c", true),
            ("1.2.3+a+b", "1.2.4+a+b", false),
        ] {
            assert_eq!(
                ConcreteVersion::new(a).eq_ignoring_build_metadata(&ConcreteVersion::new(b)),
                expected,
                "{a} vs {b}"
            );
        }
    }

    #[test]
    fn package_name_round_trips_empty_string() {
        let name = PackageName::new("");
        assert_eq!(name.as_str(), "");
        assert_eq!(name, "");
    }

    #[test]
    fn package_name_round_trips_surrounding_whitespace() {
        let name = PackageName::new("  serde  ");
        assert_eq!(name.as_str(), "  serde  ");
        assert_eq!(name, "  serde  ");
    }

    #[test]
    fn package_name_round_trips_non_ascii() {
        let name = PackageName::new("パッケージ");
        assert_eq!(name.as_str(), "パッケージ");
        assert_eq!(name, "パッケージ");
    }

    #[test]
    fn package_name_compares_byte_wise_like_string() {
        assert_ne!(PackageName::new("Foo"), PackageName::new("foo"));
        assert_eq!(
            PackageName::new("Foo") == PackageName::new("foo"),
            "Foo" == "foo"
        );
    }

    #[test]
    fn package_name_into_string_roundtrip() {
        let original = String::from("tokio");
        let name = PackageName::new(original.clone());
        assert_eq!(name.into_string(), original);
    }

    #[test]
    fn package_name_debug_redacts_credential_shape() {
        let name = PackageName::new("com.google.guava:deploy:TOKEN@git.internal.corp");
        assert_eq!(format!("{name:?}"), "\"***@git.internal.corp\"");
    }

    #[test]
    fn package_name_debug_leaves_ordinary_name_untouched() {
        let name = PackageName::new("com.google.guava:guava");
        assert_eq!(format!("{name:?}"), "\"com.google.guava:guava\"");
    }

    /// #1469 (CWE-117/CWE-150): a manifest-controlled name with no credential shape at all still
    /// carries `\n`/`\r`/ESC through untouched, letting it forge a fake `tracing` log line or
    /// terminal escape sequence in `deps-lsp`'s stderr output. Adapted from the issue's PoC.
    #[test]
    fn for_tracing_neutralizes_control_characters() {
        for forged in [
            "lodash\nERROR deps_lsp: FORGED\x1b[31mRED",
            "ok\r\nWARN forged2",
        ] {
            let rendered = PackageName::new(forged).for_tracing();
            assert!(
                !rendered.contains('\n'),
                "{rendered:?} must not contain \\n"
            );
            assert!(
                !rendered.contains('\r'),
                "{rendered:?} must not contain \\r"
            );
            assert!(
                !rendered.contains('\x1b'),
                "{rendered:?} must not contain ESC"
            );
        }
    }

    /// #1469: the same sweep must also apply once the credential-shape gate fires, so a
    /// control character hiding past a redacted credential can't survive either.
    #[test]
    fn for_tracing_neutralizes_control_characters_alongside_credential_redaction() {
        let rendered =
            PackageName::new("com.google.guava:deploy:TOKEN@git.internal\ncorp").for_tracing();
        assert!(!rendered.contains('\n'));
        assert!(!rendered.contains("TOKEN"));
    }

    #[test]
    fn package_name_hashmap_reachable_by_str_and_by_package_name() {
        use std::collections::HashMap;

        let mut map: HashMap<PackageName, u32> = HashMap::new();
        map.insert(PackageName::new("serde"), 1);

        assert_eq!(map.get("serde"), Some(&1));
        assert_eq!(map.get(&PackageName::new("serde")), Some(&1));
    }

    #[test]
    fn version_req_round_trips_empty_string() {
        let req = VersionReq::new("");
        assert_eq!(req.as_str(), "");
        assert_eq!(req, "");
    }

    #[test]
    fn version_req_round_trips_surrounding_whitespace() {
        let req = VersionReq::new("  ^1.0  ");
        assert_eq!(req.as_str(), "  ^1.0  ");
        assert_eq!(req, "  ^1.0  ");
    }

    #[test]
    fn version_req_round_trips_non_ascii() {
        let req = VersionReq::new("非対応");
        assert_eq!(req.as_str(), "非対応");
        assert_eq!(req, "非対応");
    }

    #[test]
    fn version_req_compares_byte_wise_like_string() {
        assert_ne!(VersionReq::new("^1.0"), VersionReq::new("^1.0 "));
    }

    #[test]
    fn version_req_into_string_roundtrip() {
        let original = String::from("~2.3.4");
        let req = VersionReq::new(original.clone());
        assert_eq!(req.into_string(), original);
    }

    #[test]
    fn concrete_version_round_trips_empty_string() {
        let version = ConcreteVersion::new("");
        assert_eq!(version.as_str(), "");
        assert_eq!(version, "");
    }

    #[test]
    fn concrete_version_round_trips_surrounding_whitespace() {
        let version = ConcreteVersion::new("  1.0.0  ");
        assert_eq!(version.as_str(), "  1.0.0  ");
        assert_eq!(version, "  1.0.0  ");
    }

    #[test]
    fn concrete_version_round_trips_non_ascii() {
        let version = ConcreteVersion::new("バージョン");
        assert_eq!(version.as_str(), "バージョン");
        assert_eq!(version, "バージョン");
    }

    #[test]
    fn concrete_version_compares_byte_wise_like_string() {
        assert_ne!(
            ConcreteVersion::new("1.0.0"),
            ConcreteVersion::new("1.0.0 ")
        );
    }

    #[test]
    fn concrete_version_into_string_roundtrip() {
        let original = String::from("2.3.4");
        let version = ConcreteVersion::new(original.clone());
        assert_eq!(version.into_string(), original);
    }
}