Skip to main content

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