Skip to main content

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