Skip to main content

dmc/engine/
utils.rs

1use serde_json::{Map, Value, json};
2use std::path::{Component, Path, PathBuf};
3
4use crate::engine::{compile::CompileOutput, config::EngineConfig};
5
6/// Build outcome: per-collection summaries plus non-fatal errors.
7#[derive(Debug, Default)]
8pub struct EngineReport {
9  pub collections: Vec<CollectionReport>,
10  pub errors: Vec<EngineError>,
11}
12
13/// One non-fatal compile failure (read fail, schema reject, ...). The
14/// build continues unless `EngineConfig.strict` is set.
15#[derive(Debug)]
16pub struct EngineError {
17  pub file: PathBuf,
18  pub message: String,
19}
20
21/// Per-collection summary: record count and output path.
22#[derive(Debug, Default)]
23pub struct CollectionReport {
24  pub name: String,
25  pub records: usize,
26  pub output_path: PathBuf,
27}
28
29/// `dmc_schema::Ctx` from a compiled doc. What schema `transform`/`refine`
30/// predicates see (HTML, MDX body, TOC, plain text, path, ...).
31pub fn build_schema_ctx(path: &Path, root: &Path, compiled: &CompileOutput, cfg: &EngineConfig) -> dmc_schema::Ctx {
32  let mut ctx = dmc_schema::Ctx::new(path.to_path_buf(), root.to_path_buf(), compiled.content.clone());
33  ctx.html = Some(compiled.html.clone());
34  ctx.mdx_body = Some(compiled.body.clone());
35  ctx.toc = Some(serde_json::to_value(&compiled.toc).unwrap_or(Value::Array(vec![])));
36  ctx.plain_text = Some(compiled.excerpt.clone());
37  if let (Some(dir), Some(base)) = (&cfg.compile.output_assets, &cfg.compile.output_base) {
38    let mut p = dmc_schema::AssetPipeline::new(dir.into(), base.into());
39    if let Some(t) = &cfg.output_name {
40      p.name_template = t.into();
41    }
42    ctx.assets = Some(p);
43  }
44  ctx
45}
46
47/// Pack one compiled doc into a velite-shaped JSON record:
48/// `{ ...frontmatter, code, raw, slug, permalink, path, ...optional html }`.
49pub fn build_velite_record(
50  compiled: CompileOutput,
51  frontmatter: Value,
52  path: &Path,
53  base: &Path,
54  collection: &str,
55  include_html: bool,
56) -> Value {
57  let rel = path.strip_prefix(base).unwrap_or(path);
58  let rel_str = rel.to_string_lossy().to_string();
59  let source_file_path = path.to_string_lossy().to_string();
60  let source_file_name = path.file_name().map(|s| s.to_string_lossy().to_string()).unwrap_or_default();
61  let source_file_dir = path
62    .parent()
63    .map(|p| {
64      let mut comps: Vec<String> = p.components().map(|c| c.as_os_str().to_string_lossy().to_string()).collect();
65      if comps.len() >= 2 {
66        let last2 = comps.split_off(comps.len() - 2);
67        last2.join("/")
68      } else {
69        comps.join("/")
70      }
71    })
72    .unwrap_or_default();
73  let content_type = path.extension().map(|s| s.to_string_lossy().to_string()).unwrap_or_default();
74  let permalink = velite_permalink(&source_file_path, &rel_str, collection);
75  let flattened_path = permalink.clone();
76  let slug = if permalink.is_empty() {
77    collection.to_lowercase()
78  } else {
79    format!("{}/{}", collection.to_lowercase(), permalink)
80  };
81
82  let mut map: Map<String, Value> = Map::new();
83  if let Value::Object(fm) = frontmatter {
84    for (k, v) in fm {
85      map.insert(k, v);
86    }
87  }
88
89  map.insert("body".into(), Value::String(compiled.body));
90  map.insert("content".into(), Value::String(compiled.content));
91  if include_html {
92    map.insert("html".into(), Value::String(compiled.html.clone()));
93  }
94  map.insert("excerpt".into(), Value::String(compiled.excerpt));
95  map.insert("metadata".into(), serde_json::to_value(&compiled.metadata).unwrap_or(json!({})));
96  map.insert("toc".into(), serde_json::to_value(&compiled.toc).unwrap_or(Value::Array(vec![])));
97  map.insert("contentType".into(), Value::String(content_type));
98  map.insert("flattenedPath".into(), Value::String(flattened_path));
99  map.insert("permalink".into(), Value::String(permalink));
100  map.insert("slug".into(), Value::String(slug));
101  map.insert("sourceFileDir".into(), Value::String(source_file_dir));
102  map.insert("sourceFileName".into(), Value::String(source_file_name));
103  map.insert("sourceFilePath".into(), Value::String(source_file_path));
104
105  Value::Object(map)
106}
107
108/// Wrap the raw MDX body in an ES-module shell, hoisting frontmatter
109/// imports above the function. Consumers `import` the default export.
110pub fn wrap_mdx_module(body: &str, imports: &[String]) -> String {
111  // Strip user imports from the body - they re-emit at module scope.
112  let mut stripped = body.to_string();
113  for imp in imports {
114    let trimmed = imp.trim_end_matches('\n');
115    if !trimmed.is_empty() {
116      stripped = stripped.replacen(trimmed, "", 1);
117    }
118  }
119  // Strip the trailing factory invocation; we'll re-call it ourselves.
120  let stripped = stripped
121    .trim_end_matches('\n')
122    .trim_end_matches("return _createMdxContent(arguments[0]);")
123    .trim_end_matches("return _createMdxContent(arguments[0])")
124    .trim_end()
125    .to_string();
126  // Replace `arguments[0]` references inside the function body with the
127  // module-scoped __runtime constant.
128  let stripped = stripped.replace("arguments[0]", "__runtime");
129
130  let mut out = String::new();
131  out.push_str("import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from 'react/jsx-runtime'\n");
132  for i in imports {
133    out.push_str(i);
134    if !i.ends_with('\n') {
135      out.push('\n');
136    }
137  }
138  out.push_str("const __runtime = { Fragment: _Fragment, jsx: _jsx, jsxs: _jsxs };\n");
139  out.push_str(&stripped);
140  out.push_str("\nexport default function MDXContent(props) { return _createMdxContent(props); }\n");
141  out
142}
143
144/// Best-effort JS minifier: strips comments, collapses whitespace, drops
145/// blank lines. Not a full parser; corner cases (regex literals,
146/// multi-line strings) are skipped over.
147pub fn minify_js(src: &str) -> String {
148  #[derive(Clone, Copy, PartialEq)]
149  enum St {
150    Code,
151    Squote,
152    Dquote,
153    Btick,
154    LineComment,
155    BlockComment,
156  }
157  let mut out = String::with_capacity(src.len());
158  let mut st = St::Code;
159  let mut prev_ws = false;
160  let mut chars = src.chars().peekable();
161  while let Some(c) = chars.next() {
162    match st {
163      St::Code => {
164        if c == '/' {
165          if matches!(chars.peek(), Some('/')) {
166            chars.next();
167            st = St::LineComment;
168            continue;
169          }
170          if matches!(chars.peek(), Some('*')) {
171            chars.next();
172            st = St::BlockComment;
173            continue;
174          }
175        }
176        if c == '"' {
177          st = St::Dquote;
178          out.push(c);
179          prev_ws = false;
180          continue;
181        }
182        if c == '\'' {
183          st = St::Squote;
184          out.push(c);
185          prev_ws = false;
186          continue;
187        }
188        if c == '`' {
189          st = St::Btick;
190          out.push(c);
191          prev_ws = false;
192          continue;
193        }
194        if c == '\n' || c == '\t' || c == ' ' {
195          if prev_ws {
196            continue;
197          }
198          prev_ws = true;
199          out.push(' ');
200          continue;
201        }
202        prev_ws = false;
203        out.push(c);
204      },
205      St::Squote => {
206        out.push(c);
207        if c == '\\' {
208          if let Some(n) = chars.next() {
209            out.push(n);
210          }
211          continue;
212        }
213        if c == '\'' {
214          st = St::Code;
215        }
216      },
217      St::Dquote => {
218        out.push(c);
219        if c == '\\' {
220          if let Some(n) = chars.next() {
221            out.push(n);
222          }
223          continue;
224        }
225        if c == '"' {
226          st = St::Code;
227        }
228      },
229      St::Btick => {
230        out.push(c);
231        if c == '\\' {
232          if let Some(n) = chars.next() {
233            out.push(n);
234          }
235          continue;
236        }
237        if c == '`' {
238          st = St::Code;
239        }
240      },
241      St::LineComment => {
242        if c == '\n' {
243          st = St::Code;
244        }
245      },
246      St::BlockComment => {
247        if c == '*' && matches!(chars.peek(), Some('/')) {
248          chars.next();
249          st = St::Code;
250        }
251      },
252    }
253  }
254  out
255}
256
257/// Velite's permalink algorithm: collection name + `slug` (or file stem
258/// when no slug). Returns the public URL for one record.
259fn velite_permalink(abs: &str, rel: &str, collection: &str) -> String {
260  let lc = collection.to_lowercase();
261  let needle = format!("/{lc}/");
262  let after = if let Some(idx) = abs.rfind(&needle) { &abs[idx + needle.len()..] } else { rel };
263  after.trim_end_matches(".mdx").trim_end_matches(".md").to_string()
264}
265
266/// True when `s` is a bare JS identifier (safe to emit unquoted).
267pub fn is_js_ident(s: &str) -> bool {
268  let mut chars = s.chars();
269  match chars.next() {
270    Some(c) if c.is_ascii_alphabetic() || c == '_' || c == '$' => {},
271    _ => return false,
272  }
273  chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')
274}
275
276/// `kebab-case` / `snake_case` / `space case` -> `PascalCase`. Empty
277/// input -> `"Doc"` so the caller can always concatenate a suffix.
278pub fn pascal_case(name: &str) -> String {
279  let mut out = String::with_capacity(name.len());
280  let mut upper = true;
281  for ch in name.chars() {
282    if ch == '-' || ch == '_' || ch == ' ' {
283      upper = true;
284      continue;
285    }
286    if upper {
287      out.extend(ch.to_uppercase());
288      upper = false;
289    } else {
290      out.push(ch);
291    }
292  }
293  if out.is_empty() { "Doc".into() } else { out }
294}
295
296/// POSIX-style relative path from `from_dir` to `target`. Canonicalises
297/// when possible; always emits forward slashes (TS/ESM specifier shape).
298pub fn relative_from(from_dir: &Path, target: &Path) -> String {
299  let from_abs = from_dir.canonicalize().unwrap_or_else(|_| from_dir.to_path_buf());
300  let to_abs = target.canonicalize().unwrap_or_else(|_| target.to_path_buf());
301  let from_parts: Vec<Component<'_>> = from_abs.components().collect();
302  let to_parts: Vec<Component<'_>> = to_abs.components().collect();
303  let common = from_parts.iter().zip(&to_parts).take_while(|(a, b)| a == b).count();
304  let ups = from_parts.len().saturating_sub(common);
305  let mut out = String::new();
306  for _ in 0..ups {
307    out.push_str("../");
308  }
309  if ups == 0 {
310    out.push_str("./");
311  }
312  let tail: Vec<String> = to_parts[common..]
313    .iter()
314    .filter_map(|c| match c {
315      Component::Normal(s) => Some(s.to_string_lossy().into_owned()),
316      _ => None,
317    })
318    .collect();
319  out.push_str(&tail.join("/"));
320  out
321}