Skip to main content

dmc/engine/
mod.rs

1use std::path::Path;
2
3use dmc_diagnostic::{Code, DiagResult};
4use duck_diagnostic::{DiagnosticEngine, diag};
5use rayon::prelude::*;
6
7use crate::engine::config::EngineConfig;
8
9pub mod accumulator;
10pub mod cache;
11pub mod collection;
12pub mod compile;
13pub mod config;
14pub mod index;
15pub mod schema_ts;
16pub mod sidecar;
17pub mod utils;
18
19pub struct Engine;
20
21impl Engine {
22  /// One build: optional clean, per-collection rayon parallel, then
23  /// emit `index.js` + `index.d.ts` re-exporting each `<name>.json`.
24  /// A TS/JS `config_path` makes `index.d.ts` infer types via `typeof import(...)`.
25  pub fn run(cfg: &EngineConfig, config_path: Option<&Path>, diag_engine: &mut DiagnosticEngine<Code>) -> DiagResult {
26    if cfg.clean && cfg.output_dir.exists() {
27      let paths: Vec<_> = ["index.js", "index.d.ts", "index.cjs"]
28        .iter()
29        .map(|n| cfg.output_dir.join(n))
30        .chain(cfg.collections.iter().map(|c| cfg.output_dir.join(format!("{}.json", c.name))))
31        .collect();
32
33      let errors: Vec<_> = paths
34        .par_iter()
35        .filter_map(|p| match std::fs::remove_file(p) {
36          Err(e) if e.kind() != std::io::ErrorKind::NotFound => Some(e),
37          _ => None,
38        })
39        .collect();
40
41      for e in errors {
42        diag_engine.emit(diag!(Code::IoWrite, format!("clean: remove failed: {e}")));
43      }
44    }
45
46    std::fs::create_dir_all(&cfg.output_dir).map_err(|e| {
47      diag!(
48        Code::Custom { code: String::from("N001"), severity: duck_diagnostic::Severity::Note },
49        format!("output_dir error: {}", e.to_string())
50      )
51    })?;
52
53    let math_cache_path = cfg.output_dir.join(".cache").join("math.json");
54    #[cfg(feature = "math")]
55    if cfg.cache_enabled {
56      dmc_transform::Math::load_cache(&math_cache_path)?;
57    }
58
59    for c in &cfg.collections {
60      let _ = c.process(cfg, diag_engine);
61    }
62
63    #[cfg(feature = "math")]
64    if cfg.cache_enabled {
65      dmc_transform::Math::save_cache(&math_cache_path)?;
66    }
67    let _ = math_cache_path;
68
69    let format = cfg.output_format.as_deref().unwrap_or("esm");
70    index::write_index(&cfg.output_dir, &cfg.collections, format, config_path)?;
71
72    Ok(())
73  }
74}