skif-js 0.2.0

JavaScript and TypeScript module graph and dependency rules for skif, built on oxc.
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
//! Per-package analysis settings: configured, default and plugin-provided globs merged once.

use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use globset::{Glob, GlobBuilder, GlobMatcher};
use indexmap::IndexMap;
use skif_config::{Config, IgnoreExportsUsedInFile, JsWorkspace, PackageJs};
use skif_core::FileSystem;
use skif_js_syntax::{Export, ExportKind, Registration};
use skif_workspace::{Package, PackageId, Workspace, map_ordered};

use crate::ancestors;
use crate::config_check::relative_tsconfig;
use crate::deps::member_dirs;
use crate::globs::{Globs, Names};
use crate::graph::ModuleGraph;
use crate::input::{
    BuildDir, CustomElementLibrary, IncompleteCause, IncompleteEntries, IncompleteScope, InputRequest, InputSource,
    PathAlias, WorkspaceInputs,
};
use crate::listed::{self, Listed};
use crate::resolve::join_normalized;
use crate::scripts::{self, ScriptBinary, ScriptFacts};
use crate::tsconfig_files;

const EXTENSIONS: &str = "{js,mjs,cjs,jsx,ts,tsx,mts,cts}";

/// The extensions of project files: scripts and the single-file components the resolver follows.
const PROJECT_EXTENSIONS: &str = "{js,mjs,cjs,jsx,ts,tsx,mts,cts,vue,svelte,astro}";

fn default_entry() -> Vec<String> {
    vec![
        format!("{{index,cli,main}}.{EXTENSIONS}"),
        format!("src/{{index,cli,main}}.{EXTENSIONS}"),
    ]
}

/// Ambient declaration files load without being imported.
fn ambient_declarations() -> Vec<String> {
    vec!["**/*.d.{ts,mts,cts}".to_owned()]
}

/// Directories that hold tests and end-to-end suites, which tools run without any file importing them. They are
/// entries only through a test-runner plugin; here they are excluded from the project in production mode.
fn test_directories() -> Vec<String> {
    vec![
        format!("{{test,tests,e2e,cypress}}/**/*.{EXTENSIONS}"),
        format!("src/{{test,tests,e2e}}/**/*.{EXTENSIONS}"),
        format!("**/__mocks__/**/*.{EXTENSIONS}"),
    ]
}

fn default_project() -> Vec<String> {
    vec![format!("**/*.{PROJECT_EXTENSIONS}")]
}

/// Test file names, excluded from the project in production mode.
fn test_files() -> Vec<String> {
    vec![
        format!("**/*.{{test,spec}}.{EXTENSIONS}"),
        format!("**/__tests__/**/*.{EXTENSIONS}"),
    ]
}

/// What the user configured for one package.
#[derive(Default)]
struct Configured {
    entry: Vec<String>,
    project: Vec<String>,
    ignore: Vec<String>,
    ignore_files: Vec<String>,
    ignore_dependencies: Vec<String>,
    ignore_binaries: Vec<String>,
    ignore_unresolved: Vec<String>,
    ignore_members: Vec<String>,
    include_entry_exports: Option<bool>,
    ignore_exports_used_in_file: Option<IgnoreExportsUsedInFile>,
    paths: IndexMap<String, Vec<String>>,
}

fn normalize_dir(dir: &str) -> &str {
    let dir = dir.trim_start_matches("./").trim_end_matches('/');
    if dir.is_empty() { "." } else { dir }
}

impl Configured {
    /// Applies the `js` keys of an override: the plain keys replace what is there, the `extend-` keys append.
    fn fold(&mut self, js: &PackageJs) {
        let replace = |target: &mut Vec<String>, value: &Option<Vec<String>>| {
            if let Some(value) = value {
                target.clone_from(value);
            }
        };
        replace(&mut self.entry, &js.entry);
        replace(&mut self.project, &js.project);
        replace(&mut self.ignore, &js.ignore);
        replace(&mut self.ignore_dependencies, &js.ignore_dependencies);
        replace(&mut self.ignore_binaries, &js.ignore_binaries);
        replace(&mut self.ignore_unresolved, &js.ignore_unresolved);
        self.ignore_unresolved
            .extend(js.extend_ignore_unresolved.iter().cloned());
        self.ignore.extend(js.extend_ignore.iter().cloned());
        self.ignore_dependencies
            .extend(js.extend_ignore_dependencies.iter().cloned());
        self.ignore_binaries.extend(js.extend_ignore_binaries.iter().cloned());
    }
}

impl From<&JsWorkspace> for Configured {
    fn from(workspace: &JsWorkspace) -> Self {
        Self {
            entry: workspace.entry.clone(),
            project: workspace.project.clone(),
            ignore: workspace.ignore.clone(),
            ignore_files: workspace.ignore_files.clone(),
            ignore_dependencies: workspace.ignore_dependencies.clone(),
            ignore_binaries: workspace.ignore_binaries.clone(),
            ignore_unresolved: workspace.ignore_unresolved.clone(),
            ignore_members: workspace.ignore_members.clone(),
            include_entry_exports: workspace.include_entry_exports,
            ignore_exports_used_in_file: workspace.ignore_exports_used_in_file.clone(),
            paths: workspace.paths.clone(),
        }
    }
}

impl Configured {
    /// Applies the `"."` table of the root workspace on top of the top-level `[js]` keys: a list it sets replaces the
    /// top-level one, the ignore lists add to the top-level ones (those apply to every workspace anyway).
    fn fold_root(&mut self, root: Configured) {
        let replace = |target: &mut Vec<String>, value: Vec<String>| {
            if !value.is_empty() {
                *target = value;
            }
        };
        replace(&mut self.entry, root.entry);
        replace(&mut self.project, root.project);
        self.ignore.extend(root.ignore);
        self.ignore_files.extend(root.ignore_files);
        self.ignore_dependencies.extend(root.ignore_dependencies);
        self.ignore_binaries.extend(root.ignore_binaries);
        self.ignore_unresolved.extend(root.ignore_unresolved);
        self.ignore_members.extend(root.ignore_members);
        self.include_entry_exports = root.include_entry_exports.or(self.include_entry_exports);
        self.ignore_exports_used_in_file = root
            .ignore_exports_used_in_file
            .or(self.ignore_exports_used_in_file.take());
        self.paths.extend(root.paths);
    }
}

/// What the configuration sets for the package `name` in `abs_dir`: the root package takes the top-level `[js]` and the
/// `"."` table of `[js.workspaces]`, any other the matching `[js.workspaces]` table (an exact key wins over a glob
/// key), then the `js` of each `[[overrides]]` block that selects the package, in configuration order.
///
/// The top-level `ignore-dependencies`, `ignore-binaries`, `ignore-unresolved` and `ignore-members` apply to every
/// package through the global lists and are not copied into the root's own.
fn configured(
    config: &Config,
    keys: &WorkspaceKeys,
    name: &str,
    abs_dir: &Path,
    dir: &str,
    is_root: bool,
) -> Configured {
    let js = &config.js;
    let mut user = if is_root {
        let mut root = Configured {
            entry: js.entry.clone(),
            project: js.project.clone(),
            ignore: js.ignore.clone(),
            ..Configured::default()
        };
        if let Some(table) = keys.table(&js.workspaces, ".") {
            root.fold_root(Configured::from(table));
        }
        root
    } else {
        keys.table(&js.workspaces, dir)
            .map(Configured::from)
            .unwrap_or_default()
    };
    for scoped in config
        .overrides
        .iter()
        .filter(|scoped| !scoped.js.is_empty() && scoped.applies_to(Some((name, abs_dir)), None))
    {
        user.fold(&scoped.js);
    }
    user
}

/// The `[js.workspaces]` keys, each compiled once: an exact key wins over a glob key such as `packages/*`, and among
/// several glob keys that select a directory the first in file order wins. Like every other glob, `*` stops at `/`.
#[derive(Debug, Clone, Default)]
pub(crate) struct WorkspaceKeys {
    keys: Vec<WorkspaceKey>,
}

#[derive(Debug, Clone)]
struct WorkspaceKey {
    /// The key without a leading `./` or a trailing `/`.
    dir: String,
    /// The compiled glob, for a key that is one.
    glob: Option<GlobMatcher>,
}

impl WorkspaceKey {
    fn selects(&self, dir: &str) -> bool {
        self.dir == dir || (dir != "." && self.glob.as_ref().is_some_and(|glob| glob.is_match(dir)))
    }
}

impl WorkspaceKeys {
    pub(crate) fn new(workspaces: &IndexMap<String, JsWorkspace>) -> Self {
        let keys = workspaces
            .keys()
            .map(|key| {
                let dir = normalize_dir(key);
                let glob = dir
                    .contains(['*', '?', '[', '{'])
                    .then(|| GlobBuilder::new(dir).literal_separator(true).build().ok())
                    .flatten()
                    .map(|glob| glob.compile_matcher());
                WorkspaceKey {
                    dir: dir.to_owned(),
                    glob,
                }
            })
            .collect();
        Self { keys }
    }

    /// The table of `workspaces` that stands for `dir` (`"."` or empty for the root). `workspaces` is the map the
    /// keys were compiled from.
    pub(crate) fn table<'a>(
        &self,
        workspaces: &'a IndexMap<String, JsWorkspace>,
        dir: &str,
    ) -> Option<&'a JsWorkspace> {
        self.entry(workspaces, dir).map(|(_, workspace)| workspace)
    }

    /// The key, as written in `workspaces`, whose table stands for `dir`, as [`Self::table`] picks it.
    pub(crate) fn key<'a>(&self, workspaces: &'a IndexMap<String, JsWorkspace>, dir: &str) -> Option<&'a String> {
        self.entry(workspaces, dir).map(|(key, _)| key)
    }

    fn entry<'a>(
        &self,
        workspaces: &'a IndexMap<String, JsWorkspace>,
        dir: &str,
    ) -> Option<(&'a String, &'a JsWorkspace)> {
        let dir = if dir.is_empty() { "." } else { dir };
        let position = self
            .keys
            .iter()
            .position(|key| key.dir == dir)
            .or_else(|| self.keys.iter().position(|key| key.selects(dir)))?;
        workspaces.get_index(position)
    }

    /// The keys, as written in `workspaces`, that select none of `dirs`.
    fn unmatched<'a>(&self, workspaces: &'a IndexMap<String, JsWorkspace>, dirs: &[String]) -> Vec<&'a String> {
        workspaces
            .keys()
            .zip(&self.keys)
            .filter(|(_, key)| !dirs.iter().any(|dir| key.selects(dir)))
            .map(|(text, _)| text)
            .collect()
    }
}

/// The `paths` map of a configuration as module aliases: `alias/*` becomes the prefix `alias` pointing at the target
/// directory, one alias per target.
fn path_aliases(paths: &IndexMap<String, Vec<String>>) -> Vec<PathAlias> {
    let trim = |pattern: &str| {
        let pattern = pattern
            .strip_suffix("/*")
            .or_else(|| pattern.strip_suffix('*'))
            .unwrap_or(pattern);
        pattern.trim_start_matches("./").to_owned()
    };
    paths
        .iter()
        .flat_map(|(alias, targets)| {
            let find = trim(alias);
            targets.iter().map(move |target| {
                let target = trim(target);
                PathAlias {
                    find: find.clone(),
                    target: Some(if target.is_empty() { ".".to_owned() } else { target }),
                }
            })
        })
        .collect()
}

/// Whether `setting` covers the kind of `export`.
pub(crate) fn ignores_in_file_use(setting: &IgnoreExportsUsedInFile, export: &Export) -> bool {
    match setting {
        IgnoreExportsUsedInFile::All(all) => *all,
        IgnoreExportsUsedInFile::Kinds(kinds) => match export.kind {
            ExportKind::Value => kinds.variable,
            ExportKind::Function => kinds.function,
            ExportKind::Class => kinds.class,
            ExportKind::Enum => kinds.enumeration,
            ExportKind::Namespace => kinds.namespace,
            ExportKind::Type => kinds.type_alias || kinds.interface,
            _ => false,
        },
        _ => false,
    }
}

/// The settings of one workspace package.
pub(crate) struct PackageSetup {
    pub id: PackageId,
    /// Absolute package directory.
    pub dir: PathBuf,
    pub entry: Globs,
    /// Entry globs that point outside the package directory (`../shared/setup.ts`), relative to the workspace root.
    pub external_entry: Globs,
    /// Entry globs from plugins and tool configuration. Unlike the defaults they also match files that belong to a
    /// workspace package nested below this one: a root `playwright.config.ts` names the tests of the packages.
    pub shared_entry: Globs,
    /// The entry globs plugins provide inside the package, for the `entry-redundant` hint of `stale-js-config`.
    pub plugin_entry: Globs,
    /// The tool configuration of the package could not be fully read, so its entry files are not all known.
    /// Files and dependencies cannot be judged unused then.
    pub entries_incomplete: bool,
    /// Why the entry files are incomplete; not empty when they are.
    pub incomplete_reasons: Vec<IncompleteEntries>,
    /// When the entry files are incomplete, the globs (relative to the package directory) of the only files that may
    /// be unknown entries; `None` when they may be anywhere. The matching project files are treated as entries and
    /// every other file is judged unused as usual (ADR 0065).
    pub incomplete_scope: Option<IncompleteScopeGlobs>,
    /// The module (relative to the workspace root) and 1-based line of a computed `import()` or `require()` in the
    /// package, which may load any of its files: the narrowed scope a config gave then leaves the package unjudged
    /// as a whole (see [`Self::unjudged_package_wide`]).
    pub widened_by: Option<(PathBuf, u32)>,
    pub project: Globs,
    /// Files whose issues are not reported, relative to the package directory.
    pub ignore: Globs,
    /// Files never reported unused, relative to the package directory (`ignore-files` of the workspace).
    pub ignore_files: Globs,
    /// Dependencies and binaries plugins say are never reported.
    pub ignore_dependencies: Names,
    pub ignore_binaries: Names,
    /// The `ignore-dependencies`, `ignore-binaries`, `ignore-unresolved` and `ignore-members` of this workspace.
    pub user_ignore_dependencies: Listed,
    pub user_ignore_binaries: Listed,
    pub ignore_unresolved: Listed,
    pub ignore_members: Listed,
    /// The `entry`, `project` and `ignore` patterns the configuration gives this package (no plugin or default
    /// ones), for the configuration hints of `stale-js-config`.
    pub user_patterns: UserPatterns,
    /// Whether unused exports of entry files are reported (`include-entry-exports`, workspace over top level).
    pub include_entry_exports: bool,
    /// Which exports used in their own file are not reported.
    pub used_in_file: IgnoreExportsUsedInFile,
    /// Packages referenced by plugins and by scripts.
    pub referenced_dependencies: Vec<String>,
    /// Binaries run by plugins.
    pub referenced_binaries: Vec<String>,
    pub scripts: ScriptFacts,
    /// Tool configuration files, absolute.
    pub config_files: Vec<PathBuf>,
    /// Aliases declared by the package's tool configuration.
    pub aliases: Vec<PathAlias>,
    pub build_dirs: Vec<BuildDir>,
    /// Extra `exports` conditions that select source files.
    pub conditions: Vec<String>,
    /// Directories bare specifiers are looked up in, relative to the package directory.
    pub module_dirs: Vec<String>,
    /// File extensions (with the leading dot) imports may omit, from bundler `resolve.extensions`.
    pub extensions: Vec<String>,
    /// Custom element libraries of the enabled plugins, whose registered classes are used.
    pub custom_elements: Vec<CustomElementLibrary>,
}

/// The narrowed scope of an incomplete package; see [`PackageSetup::incomplete_scope`].
pub(crate) struct IncompleteScopeGlobs {
    /// The globs as the input sources gave them, for `explain-usage`.
    pub patterns: Vec<String>,
    pub globs: Globs,
}

impl PackageSetup {
    /// Whether `rel` (relative to the package directory) may be an entry that a config of the package hides, so it
    /// is treated as an entry; never when the hidden entries may be anywhere.
    pub(crate) fn in_incomplete_scope(&self, rel: &str) -> bool {
        self.entries_incomplete
            && self
                .incomplete_scope
                .as_ref()
                .is_some_and(|scope| scope.globs.is_match(rel))
    }

    /// Whether no file of the package can be judged unused: its entries are incomplete and may be anywhere, or a
    /// computed load may reach any of its files.
    pub(crate) fn unjudged_package_wide(&self) -> bool {
        self.entries_incomplete && (self.incomplete_scope.is_none() || self.widened_by.is_some())
    }
}

/// The `entry`, `project` and `ignore` patterns a package is configured with, as written.
#[derive(Debug, Clone, Default)]
pub(crate) struct UserPatterns {
    pub entry: Vec<String>,
    pub project: Vec<String>,
    pub ignore: Vec<String>,
    pub ignore_files: Vec<String>,
}

/// Settings for the whole workspace.
#[allow(
    clippy::struct_excessive_bools,
    reason = "each bool is an independent switch of the analysis"
)]
pub(crate) struct Setup {
    /// Indexed by package; `None` for packages excluded with `ignore-packages`.
    pub packages: Vec<Option<PackageSetup>>,
    /// `[js] ignore`, relative to the workspace root.
    pub global_ignore: Globs,
    /// `[js] ignore-files`, relative to the workspace root.
    pub global_ignore_files: Globs,
    /// Root-level `ignore-dependencies`, `ignore-binaries`, `ignore-unresolved` and `ignore-members` apply to every
    /// package.
    pub global_ignore_dependencies: Listed,
    pub global_ignore_binaries: Listed,
    pub global_ignore_unresolved: Listed,
    pub global_ignore_members: Listed,
    /// `[js] ignore-workspaces`, matched against package directories.
    pub ignore_workspaces: Listed,
    /// Packages the JavaScript analysis skips because `ignore-workspaces` names them.
    pub js_ignored: HashSet<PackageId>,
    /// `[js.workspaces]` keys that select no package.
    pub unmatched_workspace_keys: Vec<String>,
    pub production: bool,
    /// `[js] tsconfig`, absolute: the TypeScript configuration of the root package in place of its `tsconfig.json`.
    pub root_tsconfig: Option<PathBuf>,
    /// knip's strict mode (`--strict`): each package uses only what its own manifest lists, production code only its
    /// `dependencies` and `peerDependencies`, and type-only imports use no package.
    pub isolate_workspaces: bool,
    pub include_entry_exports: bool,
    /// `[js] include-fixtures`: files in fixture directories are reported as unused like any other.
    pub include_fixtures: bool,
    /// `[js] ignore-exports-used-in-file`.
    pub used_in_file: IgnoreExportsUsedInFile,
    /// `JSDoc` tags that exempt an export from `unused-exports` and `unused-types`.
    pub ignore_tags: Vec<String>,
    /// `JSDoc` tags an export must carry to be reported at all; empty reports every export (knip's `+tag`).
    pub include_tags: Vec<String>,
    /// `[js.cycles]`.
    pub cycles: skif_config::JsCycles,
    /// `[js] ignore-global-binaries`: binaries assumed to be installed globally are never reported unlisted.
    pub ignore_global_binaries: bool,
}

/// The TypeScript configuration of the package in `dir`: `root_tsconfig` (`[js] tsconfig`) for the root package,
/// `tsconfig.json` otherwise.
pub(crate) fn tsconfig_path(root_tsconfig: Option<&Path>, dir: &Path, is_root: bool) -> PathBuf {
    match root_tsconfig {
        Some(config) if is_root => config.to_path_buf(),
        _ => dir.join("tsconfig.json"),
    }
}

/// `pattern`, written relative to the package directory `dir`, relative to the workspace root instead. `None` when it
/// leaves the workspace. A leading `!` is kept.
fn workspace_relative(dir: &str, pattern: &str) -> Option<String> {
    let (negation, body) = pattern.strip_prefix('!').map_or(("", pattern), |rest| ("!", rest));
    let mut parts: Vec<&str> = Vec::new();
    for segment in dir.split('/').chain(body.split('/')) {
        match segment {
            "" | "." => {}
            ".." => {
                parts.pop()?;
            }
            other => parts.push(other),
        }
    }
    Some(format!("{negation}{}", parts.join("/")))
}

/// Whether a workspace named by a script (`yarn workspace web`, `pnpm --filter "@scope/*"`, `npm -w packages/web`)
/// is `package`: by name, by name pattern or by directory. Exclusions (`!web`) select nothing.
fn names_package(target: &str, package: &skif_workspace::Package) -> bool {
    let target = target.trim_start_matches("...").trim_end_matches("...");
    if target.starts_with('!') {
        return false;
    }
    if package.name.as_deref() == Some(target) {
        return true;
    }
    if target.starts_with('.') || (target.contains('/') && !target.starts_with('@')) {
        let dir = package.dir.to_string_lossy().replace('\\', "/");
        if normalize_dir(target) == dir {
            return true;
        }
    }
    package.name.as_deref().is_some_and(|name| {
        target.contains(['*', '?', '[', '{'])
            && Glob::new(target).is_ok_and(|glob| glob.compile_matcher().is_match(name))
    })
}

/// Credits the binaries a package's scripts run in other, named workspaces to those workspaces, as binaries a listed
/// provider is used for and that are never unlisted: whether the name is a binary or a script of the target is
/// not known from the caller.
fn forward_workspace_binaries(packages: &mut [Option<PackageSetup>], workspace: &Workspace) {
    let mut credits: Vec<(PackageId, ScriptBinary)> = Vec::new();
    for setup in packages.iter().flatten() {
        for forwarded in &setup.scripts.forwarded {
            for (id, target) in workspace.iter() {
                let runs_script = target
                    .manifest
                    .value()
                    .get("scripts")
                    .and_then(|scripts| scripts.get(&forwarded.binary.name))
                    .is_some();
                if !runs_script && forwarded.targets.iter().any(|name| names_package(name, target)) {
                    credits.push((id, forwarded.binary.clone()));
                }
            }
        }
    }
    for (id, binary) in credits {
        if let Some(Some(setup)) = packages.get_mut(id.index())
            && !setup.scripts.binaries.contains(&binary)
            && !setup.scripts.ephemeral_binaries.contains(&binary)
        {
            setup.scripts.ephemeral_binaries.push(binary);
        }
    }
}

/// Whether an entry glob from a plugin may match files of nested workspace packages. A glob that starts with `**/`
/// is a per-package default (every package has its own test files) and one that leaves the package is handled as
/// an external entry.
fn is_shared_pattern(pattern: &str) -> bool {
    let body = pattern.trim_start_matches('!').trim_start_matches("./");
    !body.starts_with("**/") && !body.starts_with("../") && !body.starts_with('/')
}

/// Options of `unused-exports`, which `unused-types` shares.
#[derive(Debug, Default, serde::Deserialize)]
#[serde(default, deny_unknown_fields, rename_all = "kebab-case")]
pub(crate) struct UnusedExportsOptions {
    /// `JSDoc` tags that exempt an export.
    pub ignore_tags: Vec<String>,
    /// `JSDoc` tags that limit the report to the exports carrying one of them.
    pub include_tags: Vec<String>,
}

impl Setup {
    pub(crate) fn new(
        workspace: &Workspace,
        config: &Config,
        fs: &Arc<dyn FileSystem>,
        sources: &[Arc<dyn InputSource>],
        sequential: bool,
    ) -> Self {
        let js = &config.js;
        let production = js.production;
        let ancestor_dependencies = ancestors::external_dependencies(fs.as_ref(), &workspace.root);
        let UnusedExportsOptions {
            ignore_tags,
            include_tags,
        } = config
            .rule("unused-exports")
            .and_then(|rule| skif_lint::parse_options::<UnusedExportsOptions>(&rule.options).ok())
            .unwrap_or_default();
        let ignore_workspaces = Listed::directories(&js.ignore_workspaces, production);
        let workspace_keys = WorkspaceKeys::new(&js.workspaces);
        let js_ignored: HashSet<PackageId> = workspace
            .iter()
            .filter(|(_, package)| !package.is_root)
            .filter(|(_, package)| ignore_workspaces.is_match(&package.dir.to_string_lossy().replace('\\', "/")))
            .map(|(id, _)| id)
            .collect();
        let package_dirs: Vec<String> = workspace
            .iter()
            .map(|(_, package)| {
                if package.is_root {
                    ".".to_owned()
                } else {
                    package.dir.to_string_lossy().replace('\\', "/")
                }
            })
            .collect();
        let unmatched_workspace_keys: Vec<String> = workspace_keys
            .unmatched(&js.workspaces, &package_dirs)
            .into_iter()
            .cloned()
            .collect();
        let root_tsconfig = js
            .tsconfig
            .as_deref()
            .and_then(relative_tsconfig)
            .map(|path| join_normalized(&workspace.root, &path));
        let named_members = if js.use_tsconfig_files {
            member_dirs(workspace)
        } else {
            Vec::new()
        };
        let members: Vec<(PackageId, &Package)> = workspace.iter().collect();
        let mut packages: Vec<Option<PackageSetup>> = map_ordered(&members, sequential, |&(id, package)| {
            if workspace.is_ignored(id) || js_ignored.contains(&id) {
                return None;
            }
            let dir_name = package.dir.to_string_lossy().replace('\\', "/");
            let abs_dir = workspace.root.join(&package.dir);
            let match_dir = if package.is_root {
                workspace.root.as_path()
            } else {
                abs_dir.as_path()
            };
            let user = configured(
                config,
                &workspace_keys,
                package.display_name(),
                match_dir,
                &dir_name,
                package.is_root,
            );
            let mut plugin = WorkspaceInputs::default();
            let request = InputRequest {
                workspace,
                package,
                fs: fs.as_ref(),
                ancestor_dependencies: &ancestor_dependencies,
            };
            for source in sources {
                plugin.extend(source.inputs(&request));
            }
            let scripts = scripts::analyze(package);

            let mut entry = listed::user_globs(&user.entry, production, &default_entry());
            entry.extend(ambient_declarations());
            let mut shared_sources: Vec<&String> = plugin.production_entry.iter().collect();
            if !production {
                shared_sources.extend(plugin.entry.iter());
            }
            let shared_entry: Vec<String> = shared_sources
                .into_iter()
                .filter(|pattern| is_shared_pattern(pattern))
                .cloned()
                .collect();
            let mut plugin_entry: Vec<String> = plugin.production_entry.clone();
            if !production {
                plugin_entry.extend(plugin.entry.iter().cloned());
                entry.extend(plugin.entry);
            }
            entry.extend(plugin.production_entry);
            plugin_entry.retain(|pattern| !pattern.trim_start_matches('!').starts_with("../"));

            let tsconfig_project = js
                .use_tsconfig_files
                .then(|| {
                    let config = tsconfig_path(root_tsconfig.as_deref(), &abs_dir, package.is_root);
                    tsconfig_files::project_globs(fs.as_ref(), &named_members, &config, &abs_dir)
                })
                .flatten();
            let from_tsconfig = tsconfig_project.is_some();
            let (mut project, mut named_files) = match tsconfig_project {
                Some(selected) => (selected.patterns, selected.files),
                None => (
                    listed::user_globs(&user.project, production, &default_project()),
                    Vec::new(),
                ),
            };
            if production {
                let mut exclusions = listed::production_exclusions(&plugin.project);
                exclusions.extend(listed::non_production_entries(&user.entry));
                exclusions.extend(
                    test_files()
                        .into_iter()
                        .chain(test_directories())
                        .map(|glob| format!("!{glob}")),
                );
                // Production mode leaves out tests and the like even when a `tsconfig` names them in `files`.
                if !named_files.is_empty() {
                    named_files.extend(exclusions.iter().cloned());
                }
                project.extend(exclusions);
            } else if !from_tsconfig {
                // knip adds no plugin project globs to the files a `tsconfig` selects either.
                project.extend(plugin.project);
            }

            let user_patterns = UserPatterns {
                entry: user.entry.clone(),
                project: user.project.clone(),
                ignore: user.ignore.clone(),
                ignore_files: user.ignore_files.clone(),
            };
            let mut ignore = user.ignore;
            ignore.extend(plugin.ignore);
            let mut ignore_dependencies = plugin.ignore_dependencies;
            ignore_dependencies.extend(plugin.virtual_modules);
            let ignore_binaries = plugin.ignore_binaries;
            let mut aliases = path_aliases(&user.paths);
            aliases.extend(plugin.aliases);

            let mut referenced_dependencies = plugin.dependencies;
            referenced_dependencies.extend(scripts.dependencies.iter().cloned());
            let (outside, entry): (Vec<String>, Vec<String>) = entry
                .into_iter()
                .partition(|pattern| pattern.trim_start_matches('!').starts_with("../"));
            let external_entry = Globs::new(
                outside
                    .iter()
                    .filter_map(|pattern| workspace_relative(&dir_name, pattern)),
            );
            Some(PackageSetup {
                id,
                dir: abs_dir,
                entry: Globs::new(entry),
                external_entry,
                shared_entry: Globs::new(shared_entry),
                plugin_entry: Globs::new(plugin_entry),
                entries_incomplete: plugin.entries_incomplete,
                incomplete_scope: match &plugin.incomplete_scope {
                    IncompleteScope::Within(patterns) if plugin.entries_incomplete => Some(IncompleteScopeGlobs {
                        globs: Globs::new(patterns),
                        patterns: patterns.clone(),
                    }),
                    _ => None,
                },
                widened_by: None,
                incomplete_reasons: if plugin.entries_incomplete && plugin.incomplete_reasons.is_empty() {
                    vec![IncompleteEntries {
                        cause: IncompleteCause::Unspecified,
                        plugin: None,
                        file: None,
                    }]
                } else {
                    plugin.incomplete_reasons
                },
                project: Globs::new(project).or(Globs::new(named_files)),
                ignore: Globs::new(ignore),
                ignore_files: Globs::new(&user.ignore_files),
                ignore_dependencies: Names::new(ignore_dependencies),
                ignore_binaries: Names::new(ignore_binaries),
                user_ignore_dependencies: Listed::new(&user.ignore_dependencies, production),
                user_ignore_binaries: Listed::new(&user.ignore_binaries, production),
                ignore_unresolved: Listed::new(&user.ignore_unresolved, production),
                ignore_members: Listed::new(&user.ignore_members, production),
                user_patterns,
                include_entry_exports: user.include_entry_exports.unwrap_or(js.include_entry_exports),
                used_in_file: user
                    .ignore_exports_used_in_file
                    .unwrap_or_else(|| js.ignore_exports_used_in_file.clone()),
                referenced_dependencies,
                referenced_binaries: plugin.binaries,
                scripts,
                config_files: plugin.config_files,
                aliases,
                build_dirs: plugin.build_dirs,
                conditions: plugin.conditions,
                module_dirs: plugin.module_dirs,
                extensions: plugin.extensions,
                custom_elements: plugin.custom_elements,
            })
        });
        forward_workspace_binaries(&mut packages, workspace);
        Self {
            packages,
            global_ignore: Globs::new(&js.ignore),
            global_ignore_files: Globs::new(&js.ignore_files),
            global_ignore_dependencies: Listed::new(&js.ignore_dependencies, production),
            global_ignore_binaries: Listed::new(&js.ignore_binaries, production),
            global_ignore_unresolved: Listed::new(&js.ignore_unresolved, production),
            global_ignore_members: Listed::new(&js.ignore_members, production),
            ignore_workspaces,
            js_ignored,
            unmatched_workspace_keys,
            production,
            root_tsconfig,
            isolate_workspaces: js.isolate_workspaces,
            include_entry_exports: js.include_entry_exports,
            include_fixtures: js.include_fixtures,
            used_in_file: js.ignore_exports_used_in_file.clone(),
            ignore_tags,
            include_tags,
            cycles: js.cycles.clone(),
            ignore_global_binaries: js.ignore_global_binaries,
        }
    }

    /// The TypeScript configuration of `package`: `[js] tsconfig` for the root, `tsconfig.json` otherwise.
    pub(crate) fn tsconfig_of(&self, workspace: &Workspace, package: &Package) -> PathBuf {
        tsconfig_path(
            self.root_tsconfig.as_deref(),
            &workspace.root.join(&package.dir),
            package.is_root,
        )
    }

    pub(crate) fn package(&self, id: PackageId) -> Option<&PackageSetup> {
        self.packages.get(id.index()).and_then(Option::as_ref)
    }

    /// Records, for each incomplete package with a narrowed scope, the first module that loads a module by a computed
    /// path: the scope bounds what its configs may hide, but such a load may reach any file of the package, so none
    /// can be judged unused. The files of the scope stay entries.
    pub(crate) fn widen_incomplete_scopes(&mut self, graph: &ModuleGraph) {
        for module in graph
            .modules()
            .iter()
            .filter(|module| module.in_project && !module.foreign)
        {
            let Some(span) = module.info.unresolved_dynamic.first() else {
                continue;
            };
            if let Some(Some(package)) = self.packages.get_mut(module.owner.index())
                && package.incomplete_scope.is_some()
                && package.widened_by.is_none()
            {
                package.widened_by = Some((module.path.clone(), span.start_line));
            }
        }
    }

    /// Marks the packages whose published entry points could not be mapped to source files.
    pub(crate) fn mark_entries_incomplete(&mut self, ids: &[PackageId]) {
        for id in ids {
            if let Some(Some(package)) = self.packages.get_mut(id.index()) {
                package.entries_incomplete = true;
                package.incomplete_scope = None;
                package.incomplete_reasons.push(IncompleteEntries {
                    cause: IncompleteCause::UnmappedPublished,
                    plugin: None,
                    file: Some(package.dir.join("package.json")),
                });
            }
        }
    }

    /// Whether the dependency `name` of package `id` is on an ignore list. Every list is consulted, so each entry that
    /// matches is recorded.
    pub(crate) fn ignores_dependency(&self, id: PackageId, name: &str) -> bool {
        let global = self.global_ignore_dependencies.is_match(name);
        let package = self.package(id).is_some_and(|setup| {
            let user = setup.user_ignore_dependencies.is_match(name);
            setup.ignore_dependencies.is_match(name) || user
        });
        global || package
    }

    /// Whether the binary `name` of package `id` is on an ignore list.
    pub(crate) fn ignores_binary(&self, id: PackageId, name: &str) -> bool {
        let global = self.global_ignore_binaries.is_match(name);
        let package = self.package(id).is_some_and(|setup| {
            let user = setup.user_ignore_binaries.is_match(name);
            setup.ignore_binaries.is_match(name) || user
        });
        global || package
    }

    /// Whether the import specifier `specifier` in package `id` is on an `ignore-unresolved` list.
    pub(crate) fn ignores_unresolved(&self, id: PackageId, specifier: &str) -> bool {
        let global = self.global_ignore_unresolved.is_match(specifier);
        let package = self
            .package(id)
            .is_some_and(|setup| setup.ignore_unresolved.is_match(specifier));
        global || package
    }

    /// Whether the enum or namespace member `name` in package `id` is on an `ignore-members` list.
    pub(crate) fn ignores_member(&self, id: PackageId, name: &str) -> bool {
        self.global_ignore_members.is_match(name)
            || self
                .package(id)
                .is_some_and(|setup| setup.ignore_members.is_match(name))
    }

    /// Whether unused exports of entry files owned by package `id` are reported.
    pub(crate) fn includes_entry_exports(&self, id: PackageId) -> bool {
        self.package(id)
            .map_or(self.include_entry_exports, |setup| setup.include_entry_exports)
    }

    /// Whether an export of package `id` that is used in its own file is left unreported.
    pub(crate) fn ignores_in_file_use(&self, id: PackageId, export: &Export) -> bool {
        let setting = self.package(id).map_or(&self.used_in_file, |setup| &setup.used_in_file);
        ignores_in_file_use(setting, export)
    }

    /// Whether `export` of a module of package `id` is a registered custom element (ADR 0062):
    /// `customElements.define` always counts, a decorator or base class only when it comes from the library of a
    /// plugin enabled for the package.
    pub(crate) fn is_registered(&self, id: PackageId, export: &Export) -> bool {
        let libraries = self
            .package(id)
            .map_or(&[][..], |setup| setup.custom_elements.as_slice());
        export.registrations.iter().any(|registration| match registration {
            Registration::Define => true,
            Registration::Decorator { module, name } => libraries
                .iter()
                .any(|library| library.decorator == *name && library.is_module(module)),
            Registration::BaseClassDefine { module, name } => libraries
                .iter()
                .any(|library| library.base_class.as_deref() == Some(name.as_str()) && library.is_module(module)),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::{is_shared_pattern, workspace_relative};

    #[test]
    fn only_rooted_plugin_globs_are_shared_with_nested_packages() {
        assert!(is_shared_pattern("apps/web/playwright/**/*.ts"));
        assert!(is_shared_pattern("!apps/web/legacy/**"));
        assert!(!is_shared_pattern("**/*.test.ts"));
        assert!(!is_shared_pattern("../shared/setup.ts"));
    }

    #[test]
    fn patterns_outside_the_package_become_workspace_relative() {
        assert_eq!(
            workspace_relative("apps/a", "../../shared/setup.ts").as_deref(),
            Some("shared/setup.ts")
        );
        assert_eq!(workspace_relative("a", "!../b/**").as_deref(), Some("!b/**"));
        assert_eq!(workspace_relative("a", "../../escape.ts"), None);
    }
}