fallow-core 3.43.2

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
//! Expansion of wildcard subpath `exports` targets to entry points.

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

use fallow_config::PackageJson;
use fallow_graph::resolve::{MISSING_ONLY_OUTPUT_DIRS, OUTPUT_DIRS};
use fallow_types::discover::{DiscoveredFile, EntryPoint, EntryPointSource};
use rustc_hash::FxHashMap;

use crate::plugins::config_parser::lexical_normalize;

/// Expand a wildcard subpath export target to the discovered files it matches.
///
/// Follows the Node subpath pattern rule: every `*` in the target stands for
/// the same substring, and that substring can contain `/`. So the target
/// `./src/*.ts` matches `src/top.ts` and also `src/nested/deep.ts`.
///
/// A target in build output also matches its source files, with the rule of
/// [`wildcard_source_patterns`].
///
/// A target at the package root with a JavaScript output suffix, such as
/// `./*.js`, matches every file of that type in the package: configs,
/// scripts and tests too. When its source pattern in `src` matches files,
/// those files are entries, and of the direct matches only the files directly
/// in the package root stay entries. A package that publishes its build output
/// as the package root has no committed JavaScript files there, but a
/// hand-written package exports its root files and keeps helpers in `src`.
pub(super) fn expand_wildcard_entries(
    base: &Path,
    pattern: &str,
    files: &[DiscoveredFile],
    entries: &mut Vec<EntryPoint>,
) {
    if is_root_output_target(pattern) {
        let before = entries.len();
        for source_pattern in wildcard_source_patterns(pattern, false) {
            push_wildcard_matches(base, &source_pattern, files, entries, Capture::Any);
        }
        let capture = if entries.len() == before {
            Capture::Any
        } else {
            Capture::SingleSegment
        };
        push_wildcard_matches(base, pattern, files, entries, capture);
        return;
    }
    let before = entries.len();
    push_wildcard_matches(base, pattern, files, entries, Capture::Any);
    let has_direct_match = entries.len() > before;
    for source_pattern in wildcard_source_patterns(pattern, has_direct_match) {
        push_wildcard_matches(base, &source_pattern, files, entries, Capture::Any);
    }
}

/// Whether `pattern` has its first `*` at the package root and ends in a
/// JavaScript output suffix, such as `./*.js` or `./*.d.ts`.
fn is_root_output_target(pattern: &str) -> bool {
    let relative = pattern.trim_start_matches("./");
    relative
        .split('/')
        .next()
        .is_some_and(|first| first.contains('*'))
        && relative.rsplit_once('*').is_some_and(|(_, suffix)| {
            WILDCARD_OUTPUT_SUFFIXES
                .iter()
                .any(|output| suffix.ends_with(output))
        })
}

/// JavaScript output file suffixes that a build makes from a source file.
const WILDCARD_OUTPUT_SUFFIXES: &[&str] =
    &[".d.ts", ".d.mts", ".d.cts", ".js", ".mjs", ".cjs", ".jsx"];

/// Source extensions that a JavaScript output file can come from.
const WILDCARD_SOURCE_EXTENSIONS: &[&str] = &["ts", "tsx", "mts", "cts", "js", "jsx", "mjs", "cjs"];

/// Map a wildcard export target in build output to source patterns.
///
/// The rule is the same as for a package entry without a wildcard:
///
/// - The last output directory (`dist`, `esm`, ...) before the first `*`
///   becomes `src`, so `./esm/*.mjs` maps to `./src/*.ts`.
/// - A `lib` directory becomes `src` only when the target matches no file.
/// - A target at the package root, such as `./*.js`, maps into `src`. A
///   package that publishes its build directory as the package root has
///   this shape. When `src` has a match for a root target with a
///   JavaScript output suffix, [`expand_wildcard_entries`] keeps only the
///   direct matches in the package root. For other root targets, the mapping applies only when the
///   target matches no file.
///
/// A JavaScript output suffix (`.js`, `.d.ts`, ...) becomes each source
/// extension. Other suffixes stay. The result is empty when no rule applies.
fn wildcard_source_patterns(pattern: &str, has_direct_match: bool) -> Vec<String> {
    let relative = pattern.trim_start_matches("./");
    let segments: Vec<&str> = relative.split('/').collect();
    let literal_count = segments
        .iter()
        .position(|segment| segment.contains('*'))
        .unwrap_or(segments.len());
    let literal = &segments[..literal_count];
    let source_segments: Vec<&str> = if let Some(position) = literal
        .iter()
        .rposition(|segment| OUTPUT_DIRS.contains(segment))
    {
        replace_segment_with_src(&segments, position)
    } else if has_direct_match {
        return Vec::new();
    } else if let Some(position) = literal
        .iter()
        .rposition(|segment| MISSING_ONLY_OUTPUT_DIRS.contains(segment))
    {
        replace_segment_with_src(&segments, position)
    } else if literal_count == 0 {
        std::iter::once("src")
            .chain(segments.iter().copied())
            .collect()
    } else {
        return Vec::new();
    };
    let source_pattern = format!("./{}", source_segments.join("/"));

    let Some(star) = source_pattern.rfind('*') else {
        return Vec::new();
    };
    let (head, suffix) = source_pattern.split_at(star + 1);
    match WILDCARD_OUTPUT_SUFFIXES
        .iter()
        .find_map(|output| suffix.strip_suffix(output))
    {
        Some(stem) => WILDCARD_SOURCE_EXTENSIONS
            .iter()
            .map(|extension| format!("{head}{stem}.{extension}"))
            .collect(),
        None => vec![source_pattern],
    }
}

fn replace_segment_with_src<'a>(segments: &[&'a str], position: usize) -> Vec<&'a str> {
    let mut source = segments.to_vec();
    source[position] = "src";
    source
}

/// The substrings that a `*` of a wildcard target can stand for.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Capture {
    /// Any non-empty substring, also with `/`, as Node resolves it.
    Any,
    /// A non-empty substring without `/`.
    SingleSegment,
}

/// Push the discovered files that match one wildcard target.
fn push_wildcard_matches(
    base: &Path,
    pattern: &str,
    files: &[DiscoveredFile],
    entries: &mut Vec<EntryPoint>,
    capture: Capture,
) {
    let target = lexical_normalize(&base.join(pattern));
    let literal_dir: PathBuf = target
        .components()
        .take_while(|component| !component.as_os_str().to_string_lossy().contains('*'))
        .collect();
    let target = target.to_string_lossy().replace('\\', "/");
    let parts: Vec<&str> = target.split('*').collect();
    let package_root = lexical_normalize(base);
    let mut nested_packages = FxHashMap::default();
    for file in files {
        if !file.path.starts_with(&literal_dir) {
            continue;
        }
        let path = file.path.to_string_lossy().replace('\\', "/");
        let Some(captured) = subpath_capture(&path, &parts) else {
            continue;
        };
        if (capture == Capture::Any || !captured.contains('/'))
            && !is_in_nested_package(&file.path, &package_root, &mut nested_packages)
        {
            entries.push(EntryPoint {
                path: file.path.clone(),
                source: EntryPointSource::PackageJsonExports,
            });
        }
    }
}

/// Whether `file` belongs to a package below `package_root`: a directory
/// between the two has a `package.json` with a `name`. A `*` can match `/`,
/// so `./*.js` of the root package also matches the files of nested workspace
/// packages, which the root package does not export.
///
/// A `package.json` without a `name` is not a package. Component libraries
/// put one in each component directory to set `sideEffects` or `main`, and
/// the files of that directory stay part of the package.
fn is_in_nested_package(
    file: &Path,
    package_root: &Path,
    cache: &mut FxHashMap<PathBuf, bool>,
) -> bool {
    let mut dir = file.parent();
    while let Some(current) = dir {
        if current == package_root || !current.starts_with(package_root) {
            return false;
        }
        let is_package = *cache
            .entry(current.to_path_buf())
            .or_insert_with(|| is_named_package(current));
        if is_package {
            return true;
        }
        dir = current.parent();
    }
    false
}

fn is_named_package(dir: &Path) -> bool {
    let manifest = dir.join("package.json");
    manifest.is_file() && PackageJson::load(&manifest).is_ok_and(|pkg| pkg.name.is_some())
}

/// The substring that stands for every `*` when `path` matches a target split
/// at its `*` characters. Every `*` must stand for the same non-empty
/// substring.
fn subpath_capture<'a>(path: &'a str, parts: &[&str]) -> Option<&'a str> {
    let [prefix, .., suffix] = parts else {
        return None;
    };
    if !path.starts_with(prefix) || !path.ends_with(suffix) {
        return None;
    }
    let literal_len: usize = parts.iter().map(|part| part.len()).sum();
    let stars = parts.len() - 1;
    let captured_len = path.len().checked_sub(literal_len)?;
    if captured_len == 0 || captured_len % stars != 0 {
        return None;
    }
    let capture = path.get(prefix.len()..prefix.len() + captured_len / stars)?;
    (stars == 1 || parts.join(capture) == path).then_some(capture)
}

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

    fn discovered_files_under(root: &Path) -> Vec<DiscoveredFile> {
        let mut paths = Vec::new();
        let mut pending = vec![root.to_path_buf()];
        while let Some(dir) = pending.pop() {
            for entry in std::fs::read_dir(&dir).unwrap().flatten() {
                let path = entry.path();
                if path.is_dir() {
                    pending.push(path);
                } else {
                    paths.push(path);
                }
            }
        }
        paths.sort();
        paths
            .into_iter()
            .enumerate()
            .map(|(index, path)| DiscoveredFile {
                id: FileId(u32::try_from(index).unwrap()),
                path,
                size_bytes: 1,
            })
            .collect()
    }

    fn entry_names(entries: &[EntryPoint], root: &Path) -> Vec<String> {
        let mut names: Vec<String> = entries
            .iter()
            .map(|ep| {
                ep.path
                    .strip_prefix(root)
                    .unwrap()
                    .to_string_lossy()
                    .replace('\\', "/")
            })
            .collect();
        names.sort();
        names
    }

    #[test]
    fn expands_wildcard_css_entries() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let themes = dir.path().join("src").join("themes");
        std::fs::create_dir_all(&themes).unwrap();
        std::fs::write(themes.join("dark.css"), ":root { --bg: #000; }").unwrap();
        std::fs::write(themes.join("light.css"), ":root { --bg: #fff; }").unwrap();

        let files = discovered_files_under(dir.path());
        let mut entries = Vec::new();
        expand_wildcard_entries(dir.path(), "./src/themes/*.css", &files, &mut entries);

        assert_eq!(entries.len(), 2, "should expand wildcard to 2 CSS files");
        let paths: Vec<String> = entries
            .iter()
            .map(|ep| ep.path.file_name().unwrap().to_string_lossy().to_string())
            .collect();
        assert!(paths.contains(&"dark.css".to_string()));
        assert!(paths.contains(&"light.css".to_string()));
        assert!(
            entries
                .iter()
                .all(|ep| matches!(ep.source, EntryPointSource::PackageJsonExports))
        );
    }

    #[test]
    fn wildcard_does_not_match_nonexistent_files() {
        let dir = tempfile::tempdir().expect("create temp dir");
        std::fs::create_dir_all(dir.path().join("src/themes")).unwrap();

        let files = discovered_files_under(dir.path());
        let mut entries = Vec::new();
        expand_wildcard_entries(dir.path(), "./src/themes/*.css", &files, &mut entries);

        assert!(
            entries.is_empty(),
            "should return empty when no files match the wildcard"
        );
    }

    #[test]
    fn wildcard_only_matches_specified_extension() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let themes = dir.path().join("src").join("themes");
        std::fs::create_dir_all(&themes).unwrap();
        std::fs::write(themes.join("dark.css"), ":root {}").unwrap();
        std::fs::write(themes.join("index.ts"), "export {};").unwrap();

        let files = discovered_files_under(dir.path());
        let mut entries = Vec::new();
        expand_wildcard_entries(dir.path(), "./src/themes/*.css", &files, &mut entries);

        assert_eq!(entries.len(), 1, "should only match CSS files");
        assert!(
            entries[0]
                .path
                .file_name()
                .unwrap()
                .to_string_lossy()
                .ends_with(".css")
        );
    }

    #[test]
    fn wildcard_matches_files_in_nested_directories() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let src = dir.path().join("src");
        std::fs::create_dir_all(src.join("nested/deeper")).unwrap();
        std::fs::write(src.join("top.ts"), "export {};").unwrap();
        std::fs::write(src.join("nested/deep.ts"), "export {};").unwrap();
        std::fs::write(src.join("nested/deeper/leaf.ts"), "export {};").unwrap();
        std::fs::write(src.join("nested/helper.js"), "export {};").unwrap();
        std::fs::write(dir.path().join("outside.ts"), "export {};").unwrap();

        let files = discovered_files_under(dir.path());
        let mut entries = Vec::new();
        expand_wildcard_entries(dir.path(), "./src/*.ts", &files, &mut entries);

        assert_eq!(
            entry_names(&entries, dir.path()),
            vec![
                "src/nested/deep.ts",
                "src/nested/deeper/leaf.ts",
                "src/top.ts"
            ],
        );
    }

    #[test]
    fn wildcard_without_suffix_matches_every_nested_file() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let src = dir.path().join("src");
        std::fs::create_dir_all(src.join("a/b")).unwrap();
        std::fs::write(src.join("top.ts"), "export {};").unwrap();
        std::fs::write(src.join("a/b/orphan.tsx"), "export {};").unwrap();
        std::fs::write(dir.path().join("index.ts"), "export {};").unwrap();

        let files = discovered_files_under(dir.path());
        let mut entries = Vec::new();
        expand_wildcard_entries(dir.path(), "./src/*", &files, &mut entries);

        assert_eq!(
            entry_names(&entries, dir.path()),
            vec!["src/a/b/orphan.tsx", "src/top.ts"],
        );
    }

    #[test]
    fn wildcard_source_patterns_map_output_dirs_to_src() {
        assert_eq!(
            wildcard_source_patterns("./dist/*.d.ts", true)[0],
            "./src/*.ts"
        );
        assert_eq!(
            wildcard_source_patterns("./esm/*.mjs", false),
            WILDCARD_SOURCE_EXTENSIONS
                .iter()
                .map(|extension| format!("./src/*.{extension}"))
                .collect::<Vec<_>>()
        );
        assert_eq!(
            wildcard_source_patterns("./packages/ui/dist/*", true),
            vec!["./packages/ui/src/*"]
        );
    }

    #[test]
    fn wildcard_source_patterns_keep_present_lib_and_root_targets() {
        assert!(wildcard_source_patterns("./lib/*.js", true).is_empty());
        assert_eq!(
            wildcard_source_patterns("./lib/*.js", false)[0],
            "./src/*.ts"
        );
        assert!(wildcard_source_patterns("./*.js", true).is_empty());
        assert_eq!(wildcard_source_patterns("./*.js", false)[0], "./src/*.ts");
        assert!(wildcard_source_patterns("./themes/*.css", false).is_empty());
    }

    #[test]
    fn wildcard_with_several_stars_requires_one_substring() {
        let dir = tempfile::tempdir().expect("create temp dir");
        std::fs::create_dir_all(dir.path().join("src/button")).unwrap();
        std::fs::create_dir_all(dir.path().join("src/card")).unwrap();
        std::fs::write(dir.path().join("src/button/button.ts"), "export {};").unwrap();
        std::fs::write(dir.path().join("src/card/other.ts"), "export {};").unwrap();

        let files = discovered_files_under(dir.path());
        let mut entries = Vec::new();
        expand_wildcard_entries(dir.path(), "./src/*/*.ts", &files, &mut entries);

        assert_eq!(
            entry_names(&entries, dir.path()),
            vec!["src/button/button.ts"],
        );
    }

    #[test]
    fn root_output_target_prefers_source_over_unrelated_js_files() {
        let dir = tempfile::tempdir().expect("create temp dir");
        std::fs::create_dir_all(dir.path().join("src")).unwrap();
        std::fs::create_dir_all(dir.path().join("scripts")).unwrap();
        std::fs::write(dir.path().join("src/middleware.ts"), "export {};").unwrap();
        std::fs::write(dir.path().join("scripts/orphan.js"), "export {};").unwrap();

        let files = discovered_files_under(dir.path());
        let mut entries = Vec::new();
        expand_wildcard_entries(dir.path(), "./*.js", &files, &mut entries);

        assert_eq!(entry_names(&entries, dir.path()), vec!["src/middleware.ts"],);
    }

    #[test]
    fn root_output_target_keeps_root_files_of_hand_written_package() {
        let dir = tempfile::tempdir().expect("create temp dir");
        std::fs::create_dir_all(dir.path().join("src")).unwrap();
        std::fs::create_dir_all(dir.path().join("scripts")).unwrap();
        std::fs::write(dir.path().join("foo.js"), "import './src/impl.js';").unwrap();
        std::fs::write(dir.path().join("bar.js"), "export {};").unwrap();
        std::fs::write(dir.path().join("src/impl.js"), "export {};").unwrap();
        std::fs::write(dir.path().join("scripts/orphan.js"), "export {};").unwrap();

        let files = discovered_files_under(dir.path());
        let mut entries = Vec::new();
        expand_wildcard_entries(dir.path(), "./*.js", &files, &mut entries);

        assert_eq!(
            entry_names(&entries, dir.path()),
            vec!["bar.js", "foo.js", "src/impl.js"],
        );
    }

    #[test]
    fn root_output_target_without_source_matches_files_on_disk() {
        let dir = tempfile::tempdir().expect("create temp dir");
        std::fs::write(dir.path().join("plugin.js"), "export {};").unwrap();

        let files = discovered_files_under(dir.path());
        let mut entries = Vec::new();
        expand_wildcard_entries(dir.path(), "./*.js", &files, &mut entries);

        assert_eq!(entry_names(&entries, dir.path()), vec!["plugin.js"]);
    }

    #[test]
    fn wildcard_keeps_files_under_package_json_without_name() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let button = dir.path().join("src/Button");
        std::fs::create_dir_all(&button).unwrap();
        std::fs::write(
            button.join("package.json"),
            r#"{"sideEffects":false,"main":"./index.ts"}"#,
        )
        .unwrap();
        std::fs::write(button.join("index.ts"), "export {};").unwrap();

        let files = discovered_files_under(dir.path());
        let mut entries = Vec::new();
        expand_wildcard_entries(dir.path(), "./src/*/index.ts", &files, &mut entries);

        assert_eq!(
            entry_names(&entries, dir.path()),
            vec!["src/Button/index.ts"],
        );
    }

    #[test]
    fn root_wildcard_skips_files_of_named_nested_packages() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let nested = dir.path().join("packages/a");
        std::fs::create_dir_all(&nested).unwrap();
        std::fs::create_dir_all(dir.path().join("src")).unwrap();
        std::fs::write(nested.join("package.json"), r#"{"name":"a"}"#).unwrap();
        std::fs::write(nested.join("index.js"), "export {};").unwrap();
        std::fs::write(dir.path().join("src/top.ts"), "export {};").unwrap();

        let files = discovered_files_under(dir.path());
        let mut entries = Vec::new();
        expand_wildcard_entries(dir.path(), "./*", &files, &mut entries);

        assert_eq!(entry_names(&entries, dir.path()), vec!["src/top.ts"]);
    }
}