Skip to main content

specta_typescript/
typescript.rs

1use std::{borrow::Cow, path::Path};
2
3use specta::ResolvedTypes;
4
5use crate::{Branded, BrandedTypeExporter, Error, Exporter, Layout};
6
7/// JSDoc language exporter.
8#[derive(Debug, Clone)]
9#[non_exhaustive]
10pub struct Typescript(Exporter);
11
12impl Default for Typescript {
13    fn default() -> Self {
14        Exporter::default().into()
15    }
16}
17
18impl From<Typescript> for Exporter {
19    fn from(value: Typescript) -> Self {
20        value.0
21    }
22}
23
24impl From<Exporter> for Typescript {
25    fn from(mut value: Exporter) -> Self {
26        value.jsdoc = false;
27        Self(value)
28    }
29}
30
31impl Typescript {
32    /// Construct a new JSDoc exporter with the default options configured.
33    pub fn new() -> Self {
34        Default::default()
35    }
36
37    /// Configure a header for the file.
38    ///
39    /// This is perfect for configuring lint ignore rules or other file-level comments.
40    pub fn header(self, header: impl Into<Cow<'static, str>>) -> Self {
41        Self(self.0.header(header))
42    }
43
44    /// Configure the layout of the generated file
45    pub fn layout(self, layout: Layout) -> Self {
46        Self(self.0.layout(layout))
47    }
48
49    /// Configure how `specta_typescript::branded!` types are rendered.
50    ///
51    /// See [`Exporter::branded_type_impl`] for details.
52    pub fn branded_type_impl(
53        self,
54        builder: impl for<'a> Fn(BrandedTypeExporter<'a>, &Branded) -> Result<Cow<'static, str>, Error>
55        + Send
56        + Sync
57        + 'static,
58    ) -> Self {
59        Self(self.0.branded_type_impl(builder))
60    }
61
62    /// Export the files into a single string.
63    ///
64    /// Note: This returns an error if the format is `Format::Files`.
65    pub fn export(&self, types: &ResolvedTypes) -> Result<String, Error> {
66        self.0.export(types)
67    }
68
69    /// Export the types to a specific file/folder.
70    ///
71    /// When configured when `format` is `Format::Files`, you must provide a directory path.
72    /// Otherwise, you must provide the path of a single file.
73    ///
74    pub fn export_to(&self, path: impl AsRef<Path>, types: &ResolvedTypes) -> Result<(), Error> {
75        self.0.export_to(path, types)
76    }
77}
78
79impl AsRef<Exporter> for Typescript {
80    fn as_ref(&self) -> &Exporter {
81        &self.0
82    }
83}
84
85impl AsMut<Exporter> for Typescript {
86    fn as_mut(&mut self) -> &mut Exporter {
87        &mut self.0
88    }
89}