Skip to main content

specta_typescript/
typescript.rs

1use std::{borrow::Cow, path::Path};
2
3use specta::{Format, Types};
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    /// Add raw TypeScript code that is exported as part of the bindings.
50    pub fn with_raw(self, raw: impl Into<Cow<'static, str>>) -> Self {
51        Self(self.0.with_raw(raw))
52    }
53
54    /// Configure how `specta_typescript::branded!` types are rendered.
55    ///
56    /// See [`Exporter::branded_type_impl`] for details.
57    pub fn branded_type_impl(
58        self,
59        builder: impl for<'a> Fn(BrandedTypeExporter<'a>, &Branded) -> Result<Cow<'static, str>, Error>
60        + Send
61        + Sync
62        + 'static,
63    ) -> Self {
64        Self(self.0.branded_type_impl(builder))
65    }
66
67    /// Export the files into a single string.
68    ///
69    /// Note: This returns an error if the format is `Format::Files`.
70    pub fn export(&self, types: &Types, format: impl Format) -> Result<String, Error> {
71        self.0.export(types, format)
72    }
73
74    /// Export the types to a specific file/folder.
75    ///
76    /// When configured when `format` is `Format::Files`, you must provide a directory path.
77    /// Otherwise, you must provide the path of a single file.
78    ///
79    pub fn export_to(
80        &self,
81        path: impl AsRef<Path>,
82        types: &Types,
83        format: impl Format,
84    ) -> Result<(), Error> {
85        self.0.export_to(path, types, format)
86    }
87}
88
89impl AsRef<Exporter> for Typescript {
90    fn as_ref(&self) -> &Exporter {
91        &self.0
92    }
93}
94
95impl AsMut<Exporter> for Typescript {
96    fn as_mut(&mut self) -> &mut Exporter {
97        &mut self.0
98    }
99}