use std::{borrow::Cow, collections::BTreeMap, path::Path};
use crate::{
ts::{self, ExportConfig, ExportError},
TypeMap,
};
use super::get_types;
pub fn ts<P: AsRef<Path>>(path: P) -> Result<(), ExportError> {
ts_with_cfg(path, Cow::Borrowed(""), &ExportConfig::default())
}
pub fn ts_with_cfg<P: AsRef<Path>>(
path: P,
header: Cow<'static, str>,
conf: &ExportConfig,
) -> Result<(), ExportError> {
let mut out = format!("{header} // This file has been generated by Specta. DO NOT EDIT.\n\n");
let types = get_types().collect::<BTreeMap<_, _>>();
let mut map = BTreeMap::new();
for (sid, dt) in &types {
if let Some(ext) = &dt.ext {
if let Some((existing_sid, existing_impl_location)) =
map.insert(dt.name.clone(), (sid, ext.impl_location))
{
if existing_sid != sid {
return Err(ExportError::DuplicateTypeName(
dt.name.clone(),
ext.impl_location,
existing_impl_location,
));
}
}
}
}
for (_, typ) in types.iter() {
out += &ts::export_named_datatype(
conf,
typ,
&TypeMap {
map: types
.iter()
.map(|(k, v)| (*k, Some(v.clone())))
.collect::<BTreeMap<_, _>>(),
flatten_stack: vec![],
},
)?;
out += "\n\n";
}
std::fs::write(path, out).map_err(Into::into)
}