diff --git a/Cargo.toml b/Cargo.toml index 08752ee..ed8b3ec 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,2 +1,2 @@ [workspace] -members = ["macros", "ts-rs", "example"] \ No newline at end of file +members = ["config", "macros", "ts-rs", "example"] \ No newline at end of file diff --git a/config/Cargo.toml b/config/Cargo.toml new file mode 100644 index 0000000..72af957 --- /dev/null +++ b/config/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "ts-rs-config" +version = "5.1.0" +edition = "2021" + +[dependencies] +serde = { version = "1", features = ["derive"] } +toml = "0.5" +anyhow = "1" +once_cell = "1.8" \ No newline at end of file diff --git a/config/README.md b/config/README.md new file mode 100644 index 0000000..25ce333 --- /dev/null +++ b/config/README.md @@ -0,0 +1,5 @@ +# ts-rs-config +This crate contains the config for future ts-rs versions. +Currently, it's not really possible no use the config within the proc macro due to issues regarding incremental compilation. +A workaround would be to have `include_str!("ts.toml")` everywhere, but I don't think we should do that. +Instead, let's wait for https://github.com/rust-lang/rust/issues/73921 \ No newline at end of file diff --git a/config/src/lib.rs b/config/src/lib.rs new file mode 100644 index 0000000..50b86d9 --- /dev/null +++ b/config/src/lib.rs @@ -0,0 +1,62 @@ +use std::{ + path::{Path, PathBuf}, + sync::Arc, +}; + +use anyhow::Result; +use once_cell::sync::OnceCell; +use serde::{Deserialize, Serialize}; + +#[derive(Serialize, Deserialize)] +pub struct Config { + ambient_declarations: bool, + out_dir: String, +} + +impl Default for Config { + fn default() -> Self { + Self { + ambient_declarations: false, + out_dir: "typescript".to_owned(), + } + } +} + +static CONFIG_INSTANCE: OnceCell> = OnceCell::new(); + +impl Config { + const FILE_NAME: &'static str = "ts.toml"; + + pub fn get() -> Result> { + match CONFIG_INSTANCE.get() { + None => { + let cfg = Arc::new(Self::load()?); + CONFIG_INSTANCE.set(cfg.clone()).ok(); + Ok(cfg) + } + Some(cfg) => Ok(cfg.clone()), + } + } + + fn load() -> Result { + let manifest_dir = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR")?); + let config = Self::try_load_from_dir(&manifest_dir)?.unwrap_or_default(); + Ok(config) + } + + fn try_load_from_dir(dir: &Path) -> Result> { + let path = { + let mut path = PathBuf::from(dir); + path.push(Self::FILE_NAME); + path + }; + match path.is_file() { + true => { + let content = std::fs::read_to_string(path)?; + let parsed = toml::from_str::(&content)?; + Ok(Some(parsed)) + } + false => Ok(None), + } + } +} diff --git a/example/src/lib.rs b/example/src/lib.rs index abd4bcd..66e2485 100644 --- a/example/src/lib.rs +++ b/example/src/lib.rs @@ -4,12 +4,12 @@ use std::{collections::BTreeSet, rc::Rc}; use chrono::NaiveDateTime; use serde::Serialize; -use ts_rs::{export, TS}; +use ts_rs::TS; use uuid::Uuid; #[derive(Serialize, TS)] #[ts(rename_all = "lowercase")] -#[ts(export)] +#[ts(export, export_to = "bindings/UserRole.ts")] enum Role { User, #[ts(rename = "administrator")] @@ -104,21 +104,3 @@ struct ComplexStruct { #[serde(skip_serializing_if = "Option::is_none")] pub string_tree: Option>>, } - -// this will export [Role] to `role.ts` and [User] to `user.ts` when running `cargo test`. -// `export!` will also take care of including imports in typescript files. -export! { - Role => "role.ts", - User => "user.ts", - // any type can be used here in place of the generic, but it has to match the one used - // in other structs to generate the dependencies correctly: - Point => "point.ts", - Series => "series.ts", - Vehicle => "vehicle.ts", - ComplexEnum => "complex_enum.ts", - InlineComplexEnum => "inline_complex_enum.ts", - SimpleEnum => "simple_enum.ts", - ComplexStruct => "complex_struct.ts", - // this exports an ambient declaration (`declare interface`) instead of an `export interface`. - (declare) Gender => "gender.d.ts", -} diff --git a/macros/src/attr/enum.rs b/macros/src/attr/enum.rs index 87fddec..0f71919 100644 --- a/macros/src/attr/enum.rs +++ b/macros/src/attr/enum.rs @@ -1,7 +1,7 @@ use syn::{Attribute, Ident, Result}; use crate::{ - attr::{parse_assign_inflection, parse_assign_str, parse_opt_assign_str, Inflection}, + attr::{parse_assign_inflection, parse_assign_str, Inflection}, utils::parse_attrs, }; @@ -9,7 +9,8 @@ use crate::{ pub struct EnumAttr { pub rename_all: Option, pub rename: Option, - pub export: Option>, + pub export_to: Option, + pub export: bool, tag: Option, untagged: bool, content: Option, @@ -56,6 +57,7 @@ impl EnumAttr { tag, content, untagged, + export_to, export, }: EnumAttr, ) { @@ -64,7 +66,8 @@ impl EnumAttr { self.tag = self.tag.take().or(tag); self.untagged = self.untagged || untagged; self.content = self.content.take().or(content); - self.export = self.export.take().or(export); + self.export = self.export || export; + self.export_to = self.export_to.take().or(export_to); } } @@ -72,7 +75,8 @@ impl_parse! { EnumAttr(input, out) { "rename" => out.rename = Some(parse_assign_str(input)?), "rename_all" => out.rename_all = Some(parse_assign_inflection(input)?), - "export" => out.export = Some(parse_opt_assign_str(input)?) + "export_to" => out.export_to = Some(parse_assign_str(input)?), + "export" => out.export = true } } diff --git a/macros/src/attr/mod.rs b/macros/src/attr/mod.rs index bfc30e1..553434f 100644 --- a/macros/src/attr/mod.rs +++ b/macros/src/attr/mod.rs @@ -61,14 +61,6 @@ fn parse_assign_str(input: ParseStream) -> Result { } } -fn parse_opt_assign_str(input: ParseStream) -> Result> { - if input.is_empty() || !input.peek(Token![=]) { - Ok(None) - } else { - parse_assign_str(input).map(Some) - } -} - fn parse_assign_inflection(input: ParseStream) -> Result { parse_assign_str(input).and_then(Inflection::try_from) } diff --git a/macros/src/attr/struct.rs b/macros/src/attr/struct.rs index 735732d..33794c7 100644 --- a/macros/src/attr/struct.rs +++ b/macros/src/attr/struct.rs @@ -3,7 +3,7 @@ use std::convert::TryFrom; use syn::{Attribute, Ident, Result}; use crate::{ - attr::{parse_assign_str, parse_opt_assign_str, Inflection}, + attr::{parse_assign_str, Inflection}, utils::parse_attrs, }; @@ -11,7 +11,8 @@ use crate::{ pub struct StructAttr { pub rename_all: Option, pub rename: Option, - pub export: Option>, + pub export_to: Option, + pub export: bool, } #[cfg(feature = "serde-compat")] @@ -33,11 +34,13 @@ impl StructAttr { rename_all, rename, export, + export_to, }: StructAttr, ) { self.rename = self.rename.take().or(rename); self.rename_all = self.rename_all.take().or(rename_all); - self.export = self.export.take().or(export); + self.export_to = self.export_to.take().or(export_to); + self.export = self.export || export; } } @@ -45,7 +48,8 @@ impl_parse! { StructAttr(input, out) { "rename" => out.rename = Some(parse_assign_str(input)?), "rename_all" => out.rename_all = Some(parse_assign_str(input).and_then(Inflection::try_from)?), - "export" => out.export = Some(parse_opt_assign_str(input)?) + "export" => out.export = true, + "export_to" => out.export_to = Some(parse_assign_str(input)?) } } diff --git a/macros/src/deps.rs b/macros/src/deps.rs index d7554ff..209d462 100644 --- a/macros/src/deps.rs +++ b/macros/src/deps.rs @@ -19,7 +19,9 @@ impl Dependencies { if <#ty as ts_rs::TS>::transparent() { dependencies.append(&mut <#ty as ts_rs::TS>::dependencies()); } else { - dependencies.push(ts_rs::Dependency::from_ty::<#ty>()); + if let Some(dep) = ts_rs::Dependency::from_ty::<#ty>() { + dependencies.push(dep); + } } }); } diff --git a/macros/src/lib.rs b/macros/src/lib.rs index b8f81c6..7490b51 100644 --- a/macros/src/lib.rs +++ b/macros/src/lib.rs @@ -19,88 +19,39 @@ struct DerivedTS { decl: TokenStream, inline_flattened: Option, dependencies: Dependencies, - export: Option>, + + export: bool, + export_to: Option, } impl DerivedTS { - fn generate_export_test( - &self, - rust_ty: &Ident, - generics: &Generics, - path: &str, - ) -> Option { + fn generate_export_test(&self, rust_ty: &Ident, generics: &Generics) -> Option { let test_fn = format_ident!("export_bindings_{}", &self.name.to_lowercase()); let generic_params = generics .params .iter() .filter(|param| matches!(param, GenericParam::Type(_))) .map(|_| quote! { () }); + let ty = quote!(<#rust_ty<#(#generic_params),*> as ts_rs::TS>); - let rust_ty = quote!(#rust_ty<#(#generic_params),*>); - let expanded = quote! { + Some(quote! { #[cfg(test)] #[test] fn #test_fn() { - use std::{ - path::Path, - fmt::Write, - collections::BTreeSet, - any::TypeId, - }; - use ts_rs::export::{FmtCfg, fmt_ts}; - - let path = Path::new(#path); - let mut buffer = String::with_capacity(1024); - - let deps = <#rust_ty as ts_rs::TS>::dependencies() - .into_iter() - .filter(|dep| dep.type_id != TypeId::of::<#rust_ty>()) - .collect::>(); - for dep in deps { - let exported_to = match dep.exported_to { - None => continue, - Some(to) => Path::new(to), - }; - let rel_path = ts_rs::export::import_path( - path, - exported_to, - ); - write!(&mut buffer, "import {{ {} }} from {:?};\n", &dep.ts_name, rel_path).unwrap(); - } - buffer.push_str("\n"); - - buffer.push_str("export "); - buffer.push_str( - &<#rust_ty as ts_rs::TS>::decl() - ); - - let buffer = fmt_ts( - &path, - &buffer, - &FmtCfg::new().deno().build() - ) - .expect("could not format output"); - - if let Some(parent) = path.parent() { - std::fs::create_dir_all(parent).expect("could not create directory"); - } - std::fs::write(path, &buffer).expect("could not write bindings to file"); + #ty::export().expect("could not export type"); } - }; - Some(expanded) + }) } fn into_impl(self, rust_ty: Ident, generics: Generics) -> TokenStream { let export_to = self - .export + .export_to .clone() - .map(|export| export.unwrap_or_else(|| format!("bindings/{}.ts", &self.name))); - let export = export_to - .as_ref() - .map(|to| self.generate_export_test(&rust_ty, &generics, to)); - let export_to = export_to - .map(|to| quote!(Some(#to))) - .unwrap_or_else(|| quote!(None)); + .unwrap_or_else(|| format!("bindings/{}.ts", self.name)); + let export = match self.export { + true => Some(self.generate_export_test(&rust_ty, &generics)), + false => None, + }; let DerivedTS { name, @@ -130,7 +81,7 @@ impl DerivedTS { let where_clause = add_ts_trait_bound(&generics); quote! { impl #lt_token #params #gt_token ts_rs::TS for #rust_ty #lt_token #params #gt_token #where_clause { - const EXPORTED_TO: Option<&'static str> = #export_to; + const EXPORT_TO: Option<&'static str> = Some(#export_to); fn decl() -> String { #decl @@ -156,14 +107,14 @@ impl DerivedTS { } fn add_ts_trait_bound(generics: &Generics) -> Option { - let generic_types: Vec<_> = generics + let generic_types = generics .params .iter() .filter_map(|gp| match gp { GenericParam::Type(ty) => Some(ty.ident.clone()), _ => None, }) - .collect(); + .collect::>(); if generic_types.is_empty() { return generics.where_clause.clone(); } diff --git a/macros/src/types/enum.rs b/macros/src/types/enum.rs index 92869e1..07532d2 100644 --- a/macros/src/types/enum.rs +++ b/macros/src/types/enum.rs @@ -38,6 +38,7 @@ pub(crate) fn r#enum_def(s: &ItemEnum) -> syn::Result { dependencies, name, export: enum_attr.export, + export_to: enum_attr.export_to, }) } @@ -71,7 +72,7 @@ fn format_variant( (None, Some(rn)) => rn.apply(&variant.ident.to_string()), }; - let variant_type = types::type_def(&name, &None, &variant.fields, generics, None)?; + let variant_type = types::type_def(&name, &None, &variant.fields, generics, false, None)?; let variant_dependencies = variant_type.dependencies; let inline_type = variant_type.inline; diff --git a/macros/src/types/mod.rs b/macros/src/types/mod.rs index 899ad91..181c192 100644 --- a/macros/src/types/mod.rs +++ b/macros/src/types/mod.rs @@ -20,10 +20,18 @@ pub(crate) fn struct_def(s: &ItemStruct) -> Result { rename_all, rename, export, + export_to, } = StructAttr::from_attrs(&s.attrs)?; let name = rename.unwrap_or_else(|| to_ts_ident(&s.ident)); - type_def(&name, &rename_all, &s.fields, &s.generics, export) + type_def( + &name, + &rename_all, + &s.fields, + &s.generics, + export, + export_to, + ) } fn type_def( @@ -31,18 +39,19 @@ fn type_def( rename_all: &Option, fields: &Fields, generics: &Generics, - export: Option>, + export: bool, + export_to: Option, ) -> Result { match fields { Fields::Named(named) => match named.named.len() { - 0 => unit::unit(name, rename_all, export), - _ => named::named(name, rename_all, named, generics, export), + 0 => unit::unit(name, rename_all, export, export_to), + _ => named::named(name, rename_all, named, generics, export, export_to), }, Fields::Unnamed(unnamed) => match unnamed.unnamed.len() { - 0 => unit::unit(name, rename_all, export), - 1 => newtype::newtype(name, rename_all, unnamed, generics, export), - _ => tuple::tuple(name, rename_all, unnamed, generics, export), + 0 => unit::unit(name, rename_all, export, export_to), + 1 => newtype::newtype(name, rename_all, unnamed, generics, export, export_to), + _ => tuple::tuple(name, rename_all, unnamed, generics, export, export_to), }, - Fields::Unit => unit::unit(name, rename_all, export), + Fields::Unit => unit::unit(name, rename_all, export, export_to), } } diff --git a/macros/src/types/named.rs b/macros/src/types/named.rs index d5dbe07..b1eaf4a 100644 --- a/macros/src/types/named.rs +++ b/macros/src/types/named.rs @@ -15,7 +15,8 @@ pub(crate) fn named( rename_all: &Option, fields: &FieldsNamed, generics: &Generics, - export: Option>, + export: bool, + export_to: Option, ) -> Result { let mut formatted_fields = vec![]; let mut dependencies = Dependencies::default(); @@ -44,6 +45,7 @@ pub(crate) fn named( name: name.to_owned(), dependencies, export, + export_to, }) } diff --git a/macros/src/types/newtype.rs b/macros/src/types/newtype.rs index 0afc274..19667fb 100644 --- a/macros/src/types/newtype.rs +++ b/macros/src/types/newtype.rs @@ -13,7 +13,8 @@ pub(crate) fn newtype( rename_all: &Option, fields: &FieldsUnnamed, generics: &Generics, - export: Option>, + export: bool, + export_to: Option, ) -> Result { if rename_all.is_some() { syn_err!("`rename_all` is not applicable to newtype structs"); @@ -57,5 +58,6 @@ pub(crate) fn newtype( name: name.to_owned(), dependencies, export, + export_to, }) } diff --git a/macros/src/types/tuple.rs b/macros/src/types/tuple.rs index 380bbff..cb47e00 100644 --- a/macros/src/types/tuple.rs +++ b/macros/src/types/tuple.rs @@ -14,7 +14,8 @@ pub(crate) fn tuple( rename_all: &Option, fields: &FieldsUnnamed, generics: &Generics, - export: Option>, + export: bool, + export_to: Option, ) -> Result { if rename_all.is_some() { syn_err!("`rename_all` is not applicable to tuple structs"); @@ -46,6 +47,7 @@ pub(crate) fn tuple( name: name.to_owned(), dependencies, export, + export_to, }) } diff --git a/macros/src/types/unit.rs b/macros/src/types/unit.rs index beac25e..734519b 100644 --- a/macros/src/types/unit.rs +++ b/macros/src/types/unit.rs @@ -6,7 +6,8 @@ use crate::{attr::Inflection, deps::Dependencies, DerivedTS}; pub(crate) fn unit( name: &str, rename_all: &Option, - export: Option>, + export: bool, + export_to: Option, ) -> Result { if rename_all.is_some() { syn_err!("`rename_all` is not applicable to unit structs"); @@ -19,5 +20,6 @@ pub(crate) fn unit( name: name.to_owned(), dependencies: Dependencies::default(), export, + export_to, }) } diff --git a/ts-rs/Cargo.toml b/ts-rs/Cargo.toml index a8bbf50..b7f96cf 100644 --- a/ts-rs/Cargo.toml +++ b/ts-rs/Cargo.toml @@ -28,4 +28,5 @@ dprint-plugin-typescript = { version = "0.43" } chrono = { version = "0.4.19", optional = true } bigdecimal = {version = ">=0.0.13, < 0.4.0", features=["serde"], optional = true} uuid = { version = "0.8.2", optional = true } -bytes = { version = "1.0", optional = true } \ No newline at end of file +bytes = { version = "1.0", optional = true } +thiserror = "1" diff --git a/ts-rs/src/export.rs b/ts-rs/src/export.rs index 8a52640..263cc2f 100644 --- a/ts-rs/src/export.rs +++ b/ts-rs/src/export.rs @@ -1,189 +1,71 @@ use std::{ any::TypeId, - collections::{BTreeMap, BTreeSet}, + collections::BTreeSet, fmt::Write, path::{Component, Path, PathBuf}, }; +pub use dprint_plugin_typescript::{configuration::ConfigurationBuilder, format_text}; +use thiserror::Error; + use crate::TS; -/// Expands to a test function which exports typescript bindings to one or multiple files when -/// running `cargo test`. -/// If a type depends on an other type which is exported to a different file, an appropriate import -/// will be included. -/// If a file already exists, it will be overriden. -/// Missing parent directories of the file(s) will be created. -/// Paths are interpreted as being relative to the project root. -/// ```rust -/// # use ts_rs::{export, TS}; -/// #[derive(TS)] struct A; -/// #[derive(TS)] struct B; -/// #[derive(TS)] struct C; -/// -/// export! { -/// A, B => "bindings/a.ts", -/// C => "bindings/b.ts" -/// } -/// ``` -/// When running `cargo test`, bindings for `A`, `B` and `C` will be exported to `bindings/a.ts` -/// and `bindings/b.ts`. -/// -/// By default, `export!` always uses `export type/interface`. -/// If you wish, you can also use ambient declarations (`declare type/interface`): -/// ```rust -/// # use ts_rs::{export, TS}; -/// #[derive(TS)] struct Declared; -/// #[derive(TS)] struct Normal(Declared); -/// -/// export! { -/// (declare) Declared => "bindings/declared.d.ts", -/// Normal => "bindings/normal.ts" -/// } -/// ``` -/// Since `Declared` is now an ambient declaration, `bindings/normal.ts` will not include an import -/// for `bindings/declared.d.ts`. -#[macro_export] -macro_rules! export { - ($($arg:tt)*) => { - #[cfg(test)] - #[test] - fn export_typescript() { - ts_rs::export_here!($($arg)*) - } - }; +/// An error which may occur when exporting a type +#[derive(Error, Debug)] +pub enum ExportError { + #[error("this type cannot be exported")] + CannotBeExported, + #[error("an error occurred while formatting the generated typescript output")] + Formatting(String), + #[error("an error occurred while performing IO")] + Io(#[from] std::io::Error), } -/// Like `export!` but instead of creating a test function it executes the binding generation right here. -/// This may be useful if you'd like to run the binding generation in any other context than a test. -#[macro_export] -macro_rules! export_here { - ($($(($decl:ident))? $($p:path),+ => $l:expr),* $(,)?) => { - { - use std::fmt::Write; - use std::collections::{BTreeMap as __BTreeMap, BTreeSet as __BTreeSet}; +/// Export `T` to the file specified by the `#[ts(export = ..)]` attribute and/or the `out_dir` +/// setting in the `ts.toml` config file. +pub(crate) fn export_type() -> Result<(), ExportError> { + let path = Path::new(T::EXPORT_TO.ok_or(ExportError::CannotBeExported)?); - let manifest_var = std::env::var("CARGO_MANIFEST_DIR").unwrap(); - let manifest_dir = std::path::Path::new(&manifest_var); + let mut buffer = String::with_capacity(1024); + generate_imports::(&mut buffer)?; + generate_decl::(&mut buffer); - // {TypeId} -> {PathBuf} - let mut files = __BTreeMap::new(); - $( - let path = manifest_dir.join($l); + // format output + let fmt_cfg = ConfigurationBuilder::new().deno().build(); + let buffer = format_text(path, &buffer, &fmt_cfg).map_err(ExportError::Formatting)?; - // if the type(s) should be `declare`d, then they should not be imported. - let mut declared = false; - $( ts_rs::check_declare!($decl); declared = true; )*; - - if !declared { - $({ - if let Some(_) = files.insert(std::any::TypeId::of::<$p>(), path.clone()) { - panic!( - "{} cannot be exported to multiple files using `export!`", - stringify!($p), - ); - } - })* - } - )* - - let mut buffer = String::with_capacity(8192); - let mut imports = __BTreeMap::>::new(); - let fmt_config = ts_rs::export::FmtCfg::new() .deno().build(); - - $({ - // clear buffers - buffer.clear(); - imports.clear(); - - // create output directory - let out = manifest_dir.join($l); - std::fs::create_dir_all(out.parent().unwrap()) - .expect("could not create directory"); - - // write imports - $( ts_rs::export::imports::<$p>(&files, &mut imports, &out); )* - ts_rs::export::write_imports(&imports, &mut buffer); - buffer.push_str("\n"); - - // write declarations - - // check if `export` or `declare` should be used - let mut prefix = "export "; - $( ts_rs::check_declare!($decl); prefix = "declare "; )*; - - $( - buffer.push_str(prefix); - buffer.push_str(&<$p as ts_rs::TS>::decl()); - buffer.push_str("\n\n"); - )* - - // format output - let buffer = ts_rs::export::fmt_ts(&out, &buffer, &fmt_config) - .expect("could not format output"); - - std::fs::write(&out, buffer.trim()) - .expect("could not write file"); - })* - } - }; -} - -// checks that the given argument is `declare`, emitting a compile_error! if it isn't. -#[doc(hidden)] -#[macro_export] -macro_rules! check_declare { - (declare) => {}; - ($x:ident) => { - compile_error!(concat!( - "expected `(declare)`, got `(", - stringify!($x), - ")`" - )); - }; -} - -pub use dprint_plugin_typescript::{ - configuration::ConfigurationBuilder as FmtCfg, format_text as fmt_ts, -}; - -pub fn write_imports(imports: &BTreeMap>, out: &mut impl Write) { - for (path, types) in imports { - writeln!( - out, - "import {{{}}} from {:?};", - types.iter().cloned().collect::>().join(", "), - path - ) - .unwrap(); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; } + std::fs::write(path, &buffer)?; + Ok(()) } -pub fn imports( - exported_files: &BTreeMap, - imports: &mut BTreeMap>, - out_path: &Path, -) { - T::dependencies() +/// Push the declaration of `T` +fn generate_decl(out: &mut String) { + out.push_str("export "); + out.push_str(&T::decl()); +} + +/// Push an import statement for all dependencies of `T` +fn generate_imports(out: &mut String) -> Result<(), ExportError> { + let path = Path::new(T::EXPORT_TO.ok_or(ExportError::CannotBeExported)?); + + let deps = T::dependencies() .into_iter() - .flat_map(|dep| { - let path = exported_files.get(&dep.type_id)?; - if path == out_path { - None - } else { - Some((import_path(out_path, path), dep.ts_name)) - } - }) - .for_each(|(path, name)| { - imports - .entry(path) - .or_insert_with(BTreeSet::<_>::new) - .insert(name); - }); + .filter(|dep| dep.type_id != TypeId::of::()) + .collect::>(); + + for dep in deps { + let rel_path = import_path(path, Path::new(dep.exported_to)); + writeln!(out, "import {{ {} }} from {:?};", &dep.ts_name, rel_path).unwrap(); + } + writeln!(out).unwrap(); + Ok(()) } /// Returns the required import path for importing `import` from the file `from` -#[doc(hidden)] -pub fn import_path(from: &Path, import: &Path) -> String { +fn import_path(from: &Path, import: &Path) -> String { let rel_path = diff_paths(import, from.parent().unwrap()).expect("failed to calculate import path"); match rel_path.components().next() { diff --git a/ts-rs/src/lib.rs b/ts-rs/src/lib.rs index a750c0a..1010f7f 100644 --- a/ts-rs/src/lib.rs +++ b/ts-rs/src/lib.rs @@ -21,19 +21,18 @@ use std::{ any::TypeId, collections::{BTreeMap, BTreeSet, HashMap, HashSet}, - fs::OpenOptions, - io::{BufWriter, Write}, - path::Path, }; pub use ts_rs_macros::TS; -#[doc(hidden)] -pub mod export; +pub use crate::export::ExportError; + +mod export; /// A type which can be represented in TypeScript. /// Most of the time, you'd want to derive this trait instead of implementing it manually. -/// ts-rs comes with implementations for all numeric types, `String`, `Vec`, `Option` and tuples. +/// ts-rs comes with implementations for all primitives, most collections, tuples, +/// arrays and containers. /// /// ## get started /// [TS](TS) can easily be derived for structs and enums: @@ -41,25 +40,16 @@ pub mod export; /// use ts_rs::TS; /// /// #[derive(TS)] +/// #[ts(export)] /// struct User { /// first_name: String, /// last_name: String, /// } /// ``` -/// To actually obtain the bindings, you can call `User::dump` to write the bindings to a file. -/// ```rust -/// # use ts_rs::TS; -/// # #[derive(TS)] -/// # struct User { -/// # first_name: String, -/// # last_name: String, -/// # } -/// std::fs::remove_file("bindings.ts").ok(); -/// User::dump("bindings.ts").unwrap(); -/// ``` -/// -/// Preferrably, you should use the [export!](export!) macro, which takes care of dependencies -/// between types and allows you to decide between `export` and `declare`. +/// `#[ts(export)]` will generate a test for you, in which the bindings are exported. +/// After running `cargo test`, there should be a new file, `User.ts` in the `typescript/` directory. +/// This behaviour can be customized by adding `#[ts(export_to = "..")]` to the type and/or configuring +/// the output directory in `ts.toml`. /// /// ### struct attributes /// @@ -108,7 +98,7 @@ pub mod export; /// Skip this variant pub trait TS: 'static { - const EXPORTED_TO: Option<&'static str> = None; + const EXPORT_TO: Option<&'static str> = None; /// Declaration of this type, e.g. `interface User { user_id: number, ... }`. /// This function will panic if the type has no declaration. @@ -144,40 +134,41 @@ pub trait TS: 'static { /// This is used for resolving imports when using the `export!` macro. fn transparent() -> bool; - /// Dumps the declaration of this type to a file. - /// If the file does not exist, it will be created. - /// If it does, the declaration will be appended. + /// Manually export this type to a file. + /// The output file can be specified by annotating the type with `#[ts(export_to = ".."]`. + /// By default, the filename will be derived from the types name. /// - /// This function will panicked when called on a type which does not have a declaration. - fn dump(out: impl AsRef) -> std::io::Result<()> { - let out = out.as_ref(); - let file = OpenOptions::new() - .append(true) - .create(true) - .truncate(false) - .open(out)?; - let mut writer = BufWriter::new(file); - writer.write_all(Self::decl().as_bytes())?; - writer.write_all(b"\n\n")?; - writer.flush()?; - Ok(()) + /// When a type is annotated with `#[ts(export)]`, it is exported automatically within a test. + /// This function is only usefull if you need to export the type outside of the context of a + /// test. + fn export() -> Result<(), ExportError> { + export::export_type::() } } +/// A typescript type which is depended upon by other types. +/// This information is required for generating the correct import statements. #[derive(Eq, PartialEq, Ord, PartialOrd)] pub struct Dependency { + /// Type ID of the rust type pub type_id: TypeId, + /// Name of the type in TypeScript pub ts_name: String, - pub exported_to: Option<&'static str>, + /// Path to where the type would be exported. By default a filename is derived from the types + /// name, which can be customized with `#[ts(export_to = "..")]`. + pub exported_to: &'static str, } impl Dependency { - pub fn from_ty() -> Self { - Dependency { + /// Constructs a [`Dependency`] from the given type `T`. + /// If `T` is not exportable (meaning `T::EXPORT_TO` is `None`), this function will return + /// `None` + pub fn from_ty() -> Option { + Some(Dependency { type_id: TypeId::of::(), ts_name: T::name(), - exported_to: T::EXPORTED_TO, - } + exported_to: T::EXPORT_TO?, + }) } } @@ -218,9 +209,12 @@ macro_rules! impl_tuples { ) } fn dependencies() -> Vec { - vec![$( + [$( Dependency::from_ty::<$i>() ),*] + .into_iter() + .flatten() + .collect() } fn transparent() -> bool { true @@ -394,7 +388,7 @@ impl TS for Option { } fn dependencies() -> Vec { - vec![Dependency::from_ty::()] + [Dependency::from_ty::()].into_iter().flatten().collect() } fn transparent() -> bool { @@ -417,7 +411,7 @@ impl TS for Vec { } fn dependencies() -> Vec { - vec![Dependency::from_ty::()] + [Dependency::from_ty::()].into_iter().flatten().collect() } fn transparent() -> bool { @@ -435,7 +429,7 @@ impl TS for HashSet { } fn dependencies() -> Vec { - vec![Dependency::from_ty::()] + [Dependency::from_ty::()].into_iter().flatten().collect() } fn transparent() -> bool { @@ -453,7 +447,7 @@ impl TS for BTreeSet { } fn dependencies() -> Vec { - vec![Dependency::from_ty::()] + [Dependency::from_ty::()].into_iter().flatten().collect() } fn transparent() -> bool { @@ -471,7 +465,10 @@ impl TS for HashMap { } fn dependencies() -> Vec { - vec![Dependency::from_ty::(), Dependency::from_ty::()] + [Dependency::from_ty::(), Dependency::from_ty::()] + .into_iter() + .flatten() + .collect() } fn transparent() -> bool { @@ -489,7 +486,10 @@ impl TS for BTreeMap { } fn dependencies() -> Vec { - vec![Dependency::from_ty::(), Dependency::from_ty::()] + [Dependency::from_ty::(), Dependency::from_ty::()] + .into_iter() + .flatten() + .collect() } fn transparent() -> bool { @@ -507,7 +507,7 @@ impl TS for [T; N] { } fn dependencies() -> Vec { - vec![Dependency::from_ty::()] + [Dependency::from_ty::()].into_iter().flatten().collect() } fn transparent() -> bool { diff --git a/ts-rs/tests/export_here.rs b/ts-rs/tests/export_here.rs index e478c7a..8c2379c 100644 --- a/ts-rs/tests/export_here.rs +++ b/ts-rs/tests/export_here.rs @@ -1,10 +1,11 @@ #![allow(dead_code)] -use std::{concat, env, fs}; +use std::{concat, fs}; use ts_rs::TS; #[derive(TS)] +#[ts(export_to = "export_here_test.ts")] struct User { name: String, age: i32, @@ -13,19 +14,17 @@ struct User { #[test] fn test_export_here() { - let dir = env::temp_dir(); - let file_path = dir.join("User.ts"); - ts_rs::export_here!(User => file_path.to_str().unwrap()); + User::export().unwrap(); let expected_content = concat!( "export interface User {\n", " name: string;\n", " age: number;\n", " active: boolean;\n", - "}" + "}\n" ); - let actual_content = fs::read_to_string(file_path).unwrap(); + let actual_content = fs::read_to_string("export_here_test.ts").unwrap(); assert_eq!(actual_content, expected_content); }