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
//! Config-value dependency crediting.
//!
//! Some packages are loaded at runtime only because a config value names them,
//! with no import anywhere in the project. Crediting them keeps a declared
//! dependency out of the unused-dependency report.
//!
//! The rules are data, not code: the `(surface, value) -> credits` rows live in
//! `crates/core/data/config_value_credits.toml`, embedded via `include_str!`
//! and parsed once at startup. There is no regeneration step. Adding a rule for
//! an existing surface is a one-entry change. See `CONTRIBUTING.md`.
use rustc_hash::FxHashMap;
use super::PluginResult;
/// Embedded catalogue source. Because it is `include_str!`-embedded at compile
/// time, a green `catalogue_parses` test guarantees the released binary parses.
const CATALOGUE_TOML: &str = include_str!("../../data/config_value_credits.toml");
/// The config locations a credited value can be read from.
///
/// The set is closed on purpose: every surface has a call site that knows how
/// to normalize the value before the lookup, so an unknown surface in the TOML
/// is a bug rather than a new rule. Serde rejects unknown variants, which makes
/// the catalogue parse fail loudly.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum CreditSurface {
/// Jest `testEnvironment` / Vitest `test.environment`, after the runner
/// prefix is stripped. Credits are additive: the environment package itself
/// is credited by the runner plugin.
TestEnvironmentOptionalPeer,
/// Vitest `test.environment` values that name a built-in environment rather
/// than an installable package. Credits replace the name-derived
/// dependencies entirely.
VitestBuiltinEnvironment,
/// Vite `css.transformer` / `build.cssMinify`, naming the CSS
/// implementation package Vite loads but does not ship.
ViteCssImplementation,
}
#[derive(serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct CatalogueFile {
#[serde(default)]
credit: Vec<CreditEntry>,
}
#[derive(serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct CreditEntry {
surface: CreditSurface,
/// The exact config value, after surface-specific normalization.
value: String,
/// Packages credited as referenced. Must be non-empty; an empty list would
/// be a silently inert row.
credits: Vec<String>,
/// Optional human context; does not affect matching.
#[expect(
dead_code,
reason = "documentation field, surfaced via the catalogue source"
)]
#[serde(default)]
notes: Option<String>,
}
type Catalogue = FxHashMap<(CreditSurface, String), Vec<String>>;
/// Parse and validate catalogue source.
///
/// # Errors
///
/// Returns a human-readable message when the TOML is malformed, an entry names
/// an unknown surface, a value or credit is empty or whitespace, or two entries
/// claim the same `(surface, value)` key.
fn parse(source: &str) -> Result<Catalogue, String> {
let parsed: CatalogueFile = toml::from_str(source).map_err(|e| e.to_string())?;
let mut catalogue = Catalogue::default();
for entry in parsed.credit {
if entry.value.trim().is_empty() {
return Err(format!(
"credit entry for {:?} has an empty value",
entry.surface
));
}
if entry.credits.is_empty() {
return Err(format!(
"credit entry {:?} / {:?} credits no packages",
entry.surface, entry.value
));
}
if let Some(blank) = entry.credits.iter().find(|c| c.trim().is_empty()) {
return Err(format!(
"credit entry {:?} / {:?} has an empty credit {blank:?}",
entry.surface, entry.value
));
}
let key = (entry.surface, entry.value);
if catalogue.contains_key(&key) {
return Err(format!("duplicate credit entry: {:?} / {:?}", key.0, key.1));
}
catalogue.insert(key, entry.credits);
}
Ok(catalogue)
}
/// Parse and cache the embedded catalogue once. Panics with a clear message if
/// the embedded TOML is invalid; this is unreachable in a released binary
/// because the bytes are compile-time-embedded and gated by `catalogue_parses`.
#[expect(
clippy::expect_used,
reason = "embedded credit catalogue is compile-time data pinned by catalogue_parses"
)]
fn catalogue() -> &'static Catalogue {
static CATALOGUE: std::sync::OnceLock<Catalogue> = std::sync::OnceLock::new();
CATALOGUE.get_or_init(|| {
parse(CATALOGUE_TOML).expect(
"embedded crates/core/data/config_value_credits.toml must be valid; run \
`cargo test -p fallow-core config_value_credits` to see the error",
)
})
}
/// Packages credited because `value` was read from `surface`.
///
/// Returns `None` when no rule matches, which callers distinguish from a rule
/// crediting nothing: a row always credits at least one package.
#[must_use]
pub fn credited_packages(surface: CreditSurface, value: &str) -> Option<&'static [String]> {
catalogue()
.get(&(surface, value.to_string()))
.map(Vec::as_slice)
}
/// Credit the optional peer dependencies a test environment loads at runtime.
///
/// The rules are data: see the `test-environment-optional-peer` rows in
/// `crates/core/data/config_value_credits.toml`. `jsdom` requires its optional
/// peer `canvas` lazily when it is installed, so a project installing it for
/// real canvas support has no import of it anywhere and would see the
/// dependency reported as unused (issue #2005). Environments without such a
/// peer, like `happy-dom`, have no row.
///
/// Only names already declared in the manifest can be credited, so this never
/// invents an unlisted dependency.
pub(super) fn credit_environment_optional_peers(environment: &str, result: &mut PluginResult) {
credit_config_value(
CreditSurface::TestEnvironmentOptionalPeer,
canonical_test_environment(environment),
result,
);
}
/// Record the catalogue credits for a config value, if any.
///
/// Returns whether a rule matched, which callers use when the credited packages
/// replace the dependencies derived from the value itself.
pub(super) fn credit_config_value(
surface: CreditSurface,
value: &str,
result: &mut PluginResult,
) -> bool {
let Some(packages) = credited_packages(surface, value) else {
return false;
};
result
.referenced_dependencies
.extend(packages.iter().cloned());
true
}
/// Strip the runner prefix from a test environment specifier.
///
/// Both runners accept the bare name and the package it resolves to, so
/// `testEnvironment: "jest-environment-jsdom"` and `environment: "jsdom"` select
/// the same environment. A match on the short name only missed the fully
/// qualified form that the Jest docs use, so that form lost its credit.
pub(super) fn canonical_test_environment(environment: &str) -> &str {
environment
.strip_prefix("jest-environment-")
.or_else(|| environment.strip_prefix("vitest-environment-"))
.unwrap_or(environment)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn catalogue_parses() {
let cat = catalogue();
assert!(!cat.is_empty(), "catalogue must have entries");
}
#[test]
fn jsdom_credits_canvas() {
assert_eq!(
credited_packages(CreditSurface::TestEnvironmentOptionalPeer, "jsdom"),
Some(["canvas".to_string()].as_slice())
);
}
#[test]
fn edge_runtime_credits_vm_package() {
assert_eq!(
credited_packages(CreditSurface::VitestBuiltinEnvironment, "edge-runtime"),
Some(["@edge-runtime/vm".to_string()].as_slice())
);
}
#[test]
fn lightningcss_credits_itself() {
assert_eq!(
credited_packages(CreditSurface::ViteCssImplementation, "lightningcss"),
Some(["lightningcss".to_string()].as_slice())
);
}
#[test]
fn happy_dom_has_no_optional_peer_credit() {
assert!(
credited_packages(CreditSurface::TestEnvironmentOptionalPeer, "happy-dom").is_none()
);
}
#[test]
fn surfaces_do_not_leak_into_each_other() {
assert!(credited_packages(CreditSurface::ViteCssImplementation, "jsdom").is_none());
assert!(
credited_packages(CreditSurface::TestEnvironmentOptionalPeer, "lightningcss").is_none()
);
}
#[test]
fn unknown_surface_is_rejected() {
let err = parse(
r#"
[[credit]]
surface = "vite-postcss-plugin"
value = "x"
credits = ["y"]
"#,
)
.expect_err("unknown surface must fail");
assert!(err.contains("vite-postcss-plugin"), "got: {err}");
}
#[test]
fn unknown_field_is_rejected() {
let err = parse(
r#"
[[credit]]
surface = "vite-css-implementation"
value = "x"
credits = ["y"]
ecosystem = "css"
"#,
)
.expect_err("unknown field must fail");
assert!(err.contains("ecosystem"), "got: {err}");
}
#[test]
fn empty_value_is_rejected() {
parse(
r#"
[[credit]]
surface = "vite-css-implementation"
value = " "
credits = ["y"]
"#,
)
.expect_err("empty value must fail");
}
#[test]
fn empty_credits_are_rejected() {
parse(
r#"
[[credit]]
surface = "vite-css-implementation"
value = "x"
credits = []
"#,
)
.expect_err("empty credits must fail");
}
#[test]
fn blank_credit_is_rejected() {
parse(
r#"
[[credit]]
surface = "vite-css-implementation"
value = "x"
credits = [""]
"#,
)
.expect_err("blank credit must fail");
}
#[test]
fn duplicate_entry_is_rejected() {
let err = parse(
r#"
[[credit]]
surface = "vite-css-implementation"
value = "x"
credits = ["y"]
[[credit]]
surface = "vite-css-implementation"
value = "x"
credits = ["z"]
"#,
)
.expect_err("duplicate entry must fail");
assert!(err.contains("duplicate"), "got: {err}");
}
#[test]
fn missing_required_field_is_rejected() {
parse(
r#"
[[credit]]
surface = "vite-css-implementation"
credits = ["y"]
"#,
)
.expect_err("missing value must fail");
}
}