use std::path::{Path, PathBuf};
use std::sync::Arc;
use rustc_hash::{FxHashMap, FxHashSet};
use super::{
MAX_EXTENDS_DEPTH, MAX_EXTENDS_ENTRIES, MAX_EXTENDS_READS, PROJECT_BUDGET_ROOTS,
is_local_extends, normalize_path, resolve_extends_path,
};
const CONFIG_DIR_TOKEN: &str = "${configDir}";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TsconfigValue {
value: serde_json::Value,
origin: PathBuf,
}
impl TsconfigValue {
#[must_use]
pub const fn value(&self) -> &serde_json::Value {
&self.value
}
#[must_use]
pub fn origin(&self) -> &Path {
&self.origin
}
#[must_use]
pub fn as_str(&self) -> Option<&str> {
self.value.as_str()
}
#[must_use]
pub fn strings(&self) -> Option<Vec<&str>> {
self.value
.as_array()
.map(|items| items.iter().filter_map(serde_json::Value::as_str).collect())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TsconfigFileSet {
Files,
Include,
Exclude,
}
impl TsconfigFileSet {
const fn key(self) -> &'static str {
match self {
Self::Files => "files",
Self::Include => "include",
Self::Exclude => "exclude",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum TsconfigExtendsIssue {
Missing {
config: PathBuf,
specifier: String,
},
Malformed(PathBuf),
InvalidExtends(PathBuf),
InvalidCompilerOptions(PathBuf),
Cycle(PathBuf),
Limit(PathBuf),
}
pub type SourceLoader<'a> = dyn Fn(&Path) -> Option<Arc<serde_json::Value>> + 'a;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TsconfigPattern {
pub base: PathBuf,
pub pattern: String,
}
#[derive(Debug, Clone)]
pub struct MergedTsconfig {
config_dir: PathBuf,
merged: Arc<Merged>,
}
#[derive(Debug, Clone)]
pub struct TsconfigPaths<'a> {
pub patterns: &'a serde_json::Map<String, serde_json::Value>,
pub base_dir: PathBuf,
pub origin_dir: PathBuf,
}
impl TsconfigPaths<'_> {
pub fn base_dirs(&self) -> impl Iterator<Item = &Path> {
let origin = (self.origin_dir != self.base_dir).then_some(self.origin_dir.as_path());
std::iter::once(self.base_dir.as_path()).chain(origin)
}
}
impl MergedTsconfig {
#[must_use]
pub fn read(config_path: &Path) -> Option<Self> {
ExtendsWalk::new().read(config_path, None)
}
#[must_use]
pub fn read_with_source(config_path: &Path, source: &str) -> Option<Self> {
let value = parse_source(source)?;
ExtendsWalk::new().read(config_path, Some(Arc::new(value)))
}
#[must_use]
pub fn read_with_loader(config_path: &Path, load: &SourceLoader<'_>) -> Option<Self> {
let mut walk = ExtendsWalk::new();
walk.loader = Some(load);
walk.read(config_path, None)
}
#[must_use]
pub fn config_dir(&self) -> &Path {
&self.config_dir
}
#[must_use]
pub fn compiler_option(&self, name: &str) -> Option<&TsconfigValue> {
self.merged.compiler_options.get(name)
}
#[must_use]
pub fn compiler_option_str(&self, name: &str) -> Option<&str> {
self.compiler_option(name)?.as_str()
}
#[must_use]
pub fn file_set(&self, field: TsconfigFileSet) -> Option<&TsconfigValue> {
self.merged.file_sets.get(field.key())
}
#[must_use]
pub fn resolve_path(&self, value: &str, origin: &Path) -> Option<PathBuf> {
if value.is_empty() {
return None;
}
let (base, value) = self.split_config_dir(value, origin);
let path = Path::new(value);
if path.is_absolute() {
normalize_path(path)
} else {
normalize_path(&base.join(path))
}
}
fn split_config_dir<'v>(&'v self, value: &'v str, origin: &'v Path) -> (&'v Path, &'v str) {
match value.strip_prefix(CONFIG_DIR_TOKEN) {
Some(rest) => (&self.config_dir, rest.trim_start_matches(['/', '\\'])),
None => (origin, value),
}
}
#[must_use]
pub fn file_set_patterns(&self, field: TsconfigFileSet) -> Option<Vec<TsconfigPattern>> {
let value = self.file_set(field)?;
Some(
value
.strings()?
.into_iter()
.map(|pattern| {
let (base, pattern) = self.split_config_dir(pattern, value.origin());
TsconfigPattern {
base: base.to_path_buf(),
pattern: pattern.to_owned(),
}
})
.collect(),
)
}
#[must_use]
pub fn path_option(&self, name: &str) -> Option<PathBuf> {
let option = self.compiler_option(name)?;
self.resolve_path(option.as_str()?, option.origin())
}
#[must_use]
pub fn path_list_option(&self, name: &str) -> Option<Vec<PathBuf>> {
let option = self.compiler_option(name)?;
Some(
option
.strings()?
.into_iter()
.filter_map(|item| self.resolve_path(item, option.origin()))
.collect(),
)
}
#[must_use]
pub fn paths(&self) -> Option<TsconfigPaths<'_>> {
let paths = self.compiler_option("paths")?;
let patterns = paths.value().as_object()?;
let origin_dir = paths.origin().to_path_buf();
let base_dir = self
.path_option("baseUrl")
.unwrap_or_else(|| origin_dir.clone());
Some(TsconfigPaths {
patterns,
base_dir,
origin_dir,
})
}
#[must_use]
pub fn issues(&self) -> &[TsconfigExtendsIssue] {
&self.merged.issues
}
#[must_use]
pub fn is_complete(&self) -> bool {
self.merged.issues.is_empty()
}
#[must_use]
pub fn has_malformed_parent(&self) -> bool {
self.merged
.issues
.iter()
.any(|issue| matches!(issue, TsconfigExtendsIssue::Malformed(_)))
}
}
#[derive(Debug, Clone, Default)]
struct Merged {
compiler_options: FxHashMap<String, TsconfigValue>,
file_sets: FxHashMap<&'static str, TsconfigValue>,
issues: Vec<TsconfigExtendsIssue>,
seen_issues: FxHashSet<TsconfigExtendsIssue>,
}
impl Merged {
fn with_issue(issue: TsconfigExtendsIssue) -> Self {
let mut merged = Self::default();
merged.push_issue(issue);
merged
}
fn inherit(&mut self, parent: &Self) {
for (name, value) in &parent.compiler_options {
self.compiler_options.insert(name.clone(), value.clone());
}
for (name, value) in &parent.file_sets {
self.file_sets.insert(name, value.clone());
}
for issue in &parent.issues {
self.push_issue(issue.clone());
}
}
fn push_issue(&mut self, issue: TsconfigExtendsIssue) {
if self.seen_issues.insert(issue.clone()) {
self.issues.push(issue);
}
}
fn is_transient(&self) -> bool {
self.issues.iter().any(|issue| {
matches!(
issue,
TsconfigExtendsIssue::Cycle(_) | TsconfigExtendsIssue::Limit(_)
)
})
}
}
fn parse_source(source: &str) -> Option<serde_json::Value> {
crate::jsonc::parse_to_value(source.trim_start_matches('\u{FEFF}')).ok()
}
pub(super) struct ExtendsWalk<'a> {
in_progress: FxHashSet<PathBuf>,
resolved: FxHashMap<PathBuf, (Arc<Merged>, usize)>,
targets: FxHashMap<PathBuf, FxHashMap<String, Option<PathBuf>>>,
sources: FxHashMap<PathBuf, Option<Arc<serde_json::Value>>>,
loader: Option<&'a SourceLoader<'a>>,
real_package_paths: bool,
reads: WorkBudget,
entries: WorkBudget,
}
struct WorkBudget {
root_limit: usize,
root: usize,
project: usize,
}
impl WorkBudget {
const fn new(root_limit: usize) -> Self {
Self {
root_limit,
root: 0,
project: 0,
}
}
fn start_root(&mut self) {
self.root = 0;
}
fn project_spent(&self) -> bool {
self.project >= self.root_limit * PROJECT_BUDGET_ROOTS
}
fn take(&mut self) -> bool {
if self.root >= self.root_limit || self.project_spent() {
return false;
}
self.root += 1;
self.project += 1;
true
}
}
impl ExtendsWalk<'_> {
pub(super) fn new() -> Self {
Self {
in_progress: FxHashSet::default(),
resolved: FxHashMap::default(),
targets: FxHashMap::default(),
sources: FxHashMap::default(),
loader: None,
real_package_paths: false,
reads: WorkBudget::new(MAX_EXTENDS_READS),
entries: WorkBudget::new(MAX_EXTENDS_ENTRIES),
}
}
pub(super) fn with_real_package_paths() -> Self {
Self {
real_package_paths: true,
..Self::new()
}
}
pub(super) fn read(
&mut self,
config_path: &Path,
leaf_source: Option<Arc<serde_json::Value>>,
) -> Option<MergedTsconfig> {
self.in_progress.clear();
self.reads.start_root();
self.entries.start_root();
if self.reads.project_spent() || self.entries.project_spent() {
tracing::debug!(
config = %config_path.display(),
"tsconfig extends walk spent the budget of the project; ignoring the config"
);
return None;
}
let config_path = normalize_path(config_path).unwrap_or_else(|| config_path.to_path_buf());
let config_dir = config_path.parent()?.to_path_buf();
if let Some(source) = leaf_source {
self.sources.insert(config_path.clone(), Some(source));
} else {
self.source(&config_path)?;
}
let (merged, _) = self.merge(&config_path, 0);
Some(MergedTsconfig { config_dir, merged })
}
fn merge(&mut self, config_path: &Path, depth: usize) -> (Arc<Merged>, usize) {
let issue = |issue: fn(PathBuf) -> TsconfigExtendsIssue| {
(
Arc::new(Merged::with_issue(issue(config_path.to_path_buf()))),
0,
)
};
if depth >= MAX_EXTENDS_DEPTH {
return issue(TsconfigExtendsIssue::Limit);
}
if let Some((merged, height)) = self.resolved.get(config_path) {
if depth + height <= MAX_EXTENDS_DEPTH {
return (Arc::clone(merged), *height);
}
return issue(TsconfigExtendsIssue::Limit);
}
let identity =
dunce::canonicalize(config_path).unwrap_or_else(|_| config_path.to_path_buf());
if !self.in_progress.insert(identity.clone()) {
return issue(TsconfigExtendsIssue::Cycle);
}
if !self.reads.take() {
self.in_progress.remove(&identity);
tracing::debug!(
config = %config_path.display(),
limit = MAX_EXTENDS_READS,
"tsconfig extends walk reads too many configs; ignoring the rest of the chain"
);
return issue(TsconfigExtendsIssue::Limit);
}
let (merged, height) = self.parse(config_path, depth);
self.in_progress.remove(&identity);
let merged = Arc::new(merged);
if !merged.is_transient() {
self.resolved
.insert(config_path.to_path_buf(), (Arc::clone(&merged), height));
}
(merged, height)
}
fn parse(&mut self, config_path: &Path, depth: usize) -> (Merged, usize) {
let Some(value) = self.source(config_path) else {
return (
Merged::with_issue(TsconfigExtendsIssue::Malformed(config_path.to_path_buf())),
0,
);
};
let mut merged = Merged::default();
let specifiers = match value.get("extends") {
Some(serde_json::Value::String(extends)) => vec![extends.as_str()],
Some(serde_json::Value::Array(items)) => {
if items.iter().any(|item| !item.is_string()) {
merged.push_issue(TsconfigExtendsIssue::InvalidExtends(
config_path.to_path_buf(),
));
}
items.iter().filter_map(serde_json::Value::as_str).collect()
}
Some(_) => {
merged.push_issue(TsconfigExtendsIssue::InvalidExtends(
config_path.to_path_buf(),
));
Vec::new()
}
None => Vec::new(),
};
let parents = self.resolve_parents(config_path, &specifiers, &mut merged);
let mut parent_height = 0;
for parent in parents {
let (parent_merged, height) = self.merge(&parent, depth + 1);
parent_height = parent_height.max(height);
merged.inherit(&parent_merged);
}
let Some(config_dir) = config_path.parent() else {
return (merged, parent_height + 1);
};
match value.get("compilerOptions") {
Some(serde_json::Value::Object(options)) => {
for (name, option) in options {
merged.compiler_options.insert(
name.clone(),
TsconfigValue {
value: option.clone(),
origin: config_dir.to_path_buf(),
},
);
}
}
Some(_) => merged.push_issue(TsconfigExtendsIssue::InvalidCompilerOptions(
config_path.to_path_buf(),
)),
None => {}
}
for field in [
TsconfigFileSet::Files,
TsconfigFileSet::Include,
TsconfigFileSet::Exclude,
] {
if let Some(file_set) = value.get(field.key()) {
merged.file_sets.insert(
field.key(),
TsconfigValue {
value: file_set.clone(),
origin: config_dir.to_path_buf(),
},
);
}
}
(merged, parent_height + 1)
}
fn resolve_parents(
&mut self,
config_path: &Path,
specifiers: &[&str],
merged: &mut Merged,
) -> Vec<PathBuf> {
let Some(config_dir) = config_path.parent() else {
return Vec::new();
};
let mut seen_specifiers = FxHashSet::default();
let mut seen_parents = FxHashSet::default();
let mut parents = Vec::new();
for &specifier in specifiers.iter().rev() {
if !seen_specifiers.insert(specifier) {
continue;
}
if !self.entries.take() {
tracing::debug!(
config = %config_path.display(),
limit = MAX_EXTENDS_ENTRIES,
"tsconfig extends walk follows too many entries; ignoring the rest of the chain"
);
merged.push_issue(TsconfigExtendsIssue::Limit(config_path.to_path_buf()));
break;
}
match self.resolve_target(config_path, config_dir, specifier) {
Some(parent) => {
if seen_parents.insert(parent.clone()) {
parents.push(parent);
}
}
None => merged.push_issue(TsconfigExtendsIssue::Missing {
config: config_path.to_path_buf(),
specifier: specifier.to_owned(),
}),
}
}
parents.reverse();
parents
}
fn resolve_target(
&mut self,
config_path: &Path,
config_dir: &Path,
specifier: &str,
) -> Option<PathBuf> {
if let Some(target) = self
.targets
.get(config_dir)
.and_then(|targets| targets.get(specifier))
{
return target.clone();
}
let target = resolve_extends_path(config_path, specifier).and_then(|path| {
if self.real_package_paths && !is_local_extends(specifier) {
dunce::canonicalize(path).ok()
} else {
Some(path)
}
});
self.targets
.entry(config_dir.to_path_buf())
.or_default()
.insert(specifier.to_owned(), target.clone());
target
}
fn source(&mut self, config_path: &Path) -> Option<Arc<serde_json::Value>> {
if let Some(source) = self.sources.get(config_path) {
return source.clone();
}
let source = match self.loader {
Some(load) => load(config_path),
None => std::fs::read_to_string(config_path)
.ok()
.and_then(|content| parse_source(&content))
.map(Arc::new),
};
self.sources
.insert(config_path.to_path_buf(), source.clone());
source
}
}
#[cfg(test)]
#[path = "tsconfig_merged_tests.rs"]
mod tests;