Skip to main content

specta_typescript/
error.rs

1use std::{borrow::Cow, error, fmt, io, panic::Location, path::PathBuf};
2
3use specta::datatype::{NamedDataType, OpaqueReference, RecursiveInlineType};
4
5use crate::Layout;
6
7/// The error type for the TypeScript exporter.
8///
9/// ## BigInt Forbidden
10///
11/// Specta Typescript intentionally forbids exporting BigInt-style Rust integer types.
12/// This includes [usize], [isize], [i64], [u64], [u128], [i128] and [f128].
13///
14/// This guard exists because `JSON.parse` will truncate large integers to fit into a JavaScript `number` type so we explicitly forbid exporting them.
15///
16/// We take the stance that correctness matters more than developer experience as people using Rust generally strive for correctness.
17///
18/// If you encounter this error, there are a few common migration paths (in order of preference):
19///
20/// 1. Use a Specta-based framework which can handle these types
21///     - None currently exist but it would theoretically be possible refer to [#203](https://github.com/specta-rs/specta/issues/203#issuecomment-4387573925) for more information.
22///
23/// 2. Use a smaller integer types (any of `u8`/`i8`/`u16`/`i16`/`u32`/`i32`/`f64`).
24///    - Only possible when the biggest integer you need to represent is small enough to be represented by a `number` in JS.
25///    - This approach forces your application code to handle overflow/underflow values explicitly
26///    - Downside is that it can introduce annoying glue code and doesn't actually work if your need large values.
27///
28/// 3. Serialize the value as a string
29///     - This can be done using `#[specta(type = String)]` for the type combined with a Serde `#[serde(with = "...")]` attribute for runtime.
30///     - Downside is that it can introduce annoying glue code, both on in Rust and in JS as you will need to turn it back into a `new BigInt(myString)` in JS but this will support numbers of any size losslessly.
31///
32/// 4. **UNSAFE:** Accept precision loss on per-field basis
33///     - Accept that large numbers may be deserialized differently than they are in Rust and use `#[specta(type = specta_typescript::Number)]` to bypass this warning on a per-field basis.
34///     - Marking each field explicitly encodes the decision similar to an `unsafe` block, ensuring everyone working on your codebase is aware of the risk and where it exists within the codebase.
35///     - This doesn't work for external implementations like `serde_json::Value` which contain `BigInt`'s as you don't control the definition.
36///
37/// 5. **UNSAFE:** Accept precision loss using [`specta_util::Remapper`](https://docs.rs/specta-util/latest/specta_util/struct.Remapper.html)
38///     - You can apply a `Remapper` to your [`Types`](specta::Types) collection to override types. This would allow you to remap `usize`/`isize`/`i64`/`u64`/`i128`/`u128`/`f128` into `number`.
39///     - This is highly not recommended but it might be required if your using `serde_json::Value` or other built-in impls which contain `BigInt`'s as you can't override them.
40///     - Refer to discussion around this on [#481](https://github.com/specta-rs/specta/issues/481).
41///
42#[non_exhaustive]
43pub struct Error {
44    kind: ErrorKind,
45    named_datatype: Option<Box<NamedDataType>>,
46    trace: Vec<ErrorTraceFrame>,
47}
48
49/// Additional TypeScript exporter context for an [`Error`].
50#[derive(Debug, Clone)]
51#[non_exhaustive]
52pub enum ErrorTraceFrame {
53    /// The exporter was rendering a core-provided inline reference at `path` when the error occurred.
54    Inlined {
55        /// The named Rust type being inlined, if it could be resolved.
56        named_datatype: Option<Box<NamedDataType>>,
57        /// Field, variant, or variant-field path where the inline expansion occurred.
58        path: String,
59    },
60}
61
62type FrameworkSource = Box<dyn error::Error + Send + Sync + 'static>;
63const BIGINT_DOCS_URL: &str =
64    "https://docs.rs/specta-typescript/latest/specta_typescript/struct.Error.html#bigint-forbidden";
65
66#[allow(dead_code)]
67enum ErrorKind {
68    /// A map key type cannot be represented as a valid Typescript index signature.
69    ///
70    /// Typescript map keys must resolve to string-like, number-like, symbol-like, or literal key
71    /// types. Complex structural values cannot safely be represented as object keys.
72    InvalidMapKey {
73        path: String,
74        reason: Cow<'static, str>,
75    },
76    /// Attempted to export a bigint type but the configuration forbids it.
77    BigIntForbidden {
78        path: String,
79    },
80    /// A type's name conflicts with a reserved keyword in Typescript.
81    ForbiddenName {
82        path: String,
83        name: &'static str,
84    },
85    /// A type's name contains invalid characters or is not valid.
86    InvalidName {
87        path: String,
88        name: Cow<'static, str>,
89    },
90    /// A type's name is empty and cannot be emitted as a Typescript type name.
91    EmptyName {
92        path: String,
93    },
94    /// Anonymous enum variants cannot be represented by the Typescript exporter.
95    UnsupportedAnonymousEnumVariant {
96        path: String,
97        variant_kind: &'static str,
98    },
99    /// Detected multiple items within the same scope with the same name.
100    /// Typescript doesn't support this so we error out.
101    ///
102    /// Using anything other than [Layout::FlatFile] should make this basically impossible.
103    DuplicateTypeName {
104        name: Cow<'static, str>,
105        first: String,
106        second: String,
107    },
108    /// An filesystem IO error.
109    /// This is possible when using `Typescript::export_to` when writing to a file or formatting the file.
110    Io(io::Error),
111    /// Failed to read a directory while exporting files.
112    ReadDir {
113        path: PathBuf,
114        source: io::Error,
115    },
116    /// Failed to inspect filesystem metadata while exporting files.
117    Metadata {
118        path: PathBuf,
119        source: io::Error,
120    },
121    /// Failed to remove a stale file while exporting files.
122    RemoveFile {
123        path: PathBuf,
124        source: io::Error,
125    },
126    /// Failed to remove an empty directory while exporting files.
127    RemoveDir {
128        path: PathBuf,
129        source: io::Error,
130    },
131    /// Failed to create an output directory while exporting files.
132    CreateDir {
133        path: PathBuf,
134        source: io::Error,
135    },
136    /// Failed to write an output file while exporting files.
137    WriteFile {
138        path: PathBuf,
139        source: io::Error,
140    },
141    /// Failed to read a generated file while exporting files.
142    ReadFile {
143        path: PathBuf,
144        source: io::Error,
145    },
146    /// Found an opaque reference which the Typescript exporter doesn't know how to handle.
147    /// You may be referencing a type which is not supported by the Typescript exporter.
148    UnsupportedOpaqueReference {
149        path: String,
150        reference: OpaqueReference,
151    },
152    /// Found a named reference that cannot be resolved from the provided
153    /// [`Types`](specta::Types).
154    DanglingNamedReference {
155        path: String,
156        reference: String,
157    },
158    /// Found a recursive named reference marked by core inline resolution.
159    InfiniteRecursiveInlineType {
160        path: String,
161        reference: String,
162        cycle: RecursiveInlineType,
163    },
164    /// Reached the recursion limit while rendering an anonymous Typescript type.
165    InlineRecursionLimitExceeded {
166        path: String,
167    },
168    /// An error occurred in your exporter framework.
169    Framework {
170        message: Cow<'static, str>,
171        source: FrameworkSource,
172    },
173    /// An error occurred in a format callback.
174    Format {
175        message: Cow<'static, str>,
176        path: Option<String>,
177        source: FrameworkSource,
178    },
179    /// The requested export layout is not supported by the current exporter configuration.
180    ///
181    /// Some layouts require the higher-level [`Exporter`](crate::Exporter) APIs so imports,
182    /// file paths, and module boundaries can be coordinated correctly.
183    ExportRequiresExportTo(Layout),
184    JsdocNamespacesUnsupported,
185    /// The type is part of a recursive type-alias cycle (e.g. through
186    /// `#[serde(untagged)]` newtype variants) that TypeScript rejects
187    /// (TS2456) and that the exporter could not collapse into an
188    /// equivalent non-recursive alias.
189    UnrepresentableAliasCycle {
190        path: String,
191        reason: Cow<'static, str>,
192    },
193    /// A runtime semantic transform is required beneath a construct whose
194    /// wire shape cannot be discriminated without guessing (for example an
195    /// overlapping `#[serde(untagged)]` enum). Emitting a transform here
196    /// would risk the exported type and the runtime value diverging, so the
197    /// request is rejected instead.
198    UnsupportedSemanticTransform {
199        reason: Cow<'static, str>,
200    },
201}
202
203impl Error {
204    fn new(kind: ErrorKind) -> Self {
205        Self {
206            kind,
207            named_datatype: None,
208            trace: Vec::new(),
209        }
210    }
211
212    /// The named Rust type being exported when this error occurred, if known.
213    pub fn named_datatype(&self) -> Option<&NamedDataType> {
214        self.named_datatype.as_deref()
215    }
216
217    /// TypeScript exporter traversal context for this error.
218    pub fn trace(&self) -> &[ErrorTraceFrame] {
219        &self.trace
220    }
221
222    pub(crate) fn with_named_datatype(mut self, ndt: &NamedDataType) -> Self {
223        self.named_datatype
224            .get_or_insert_with(|| Box::new(ndt.clone()));
225        self
226    }
227
228    pub(crate) fn with_inline_trace(
229        mut self,
230        ndt: Option<&NamedDataType>,
231        path: impl Into<String>,
232    ) -> Self {
233        self.trace.push(ErrorTraceFrame::Inlined {
234            named_datatype: ndt.map(|ndt| Box::new(ndt.clone())),
235            path: path.into(),
236        });
237        self
238    }
239
240    pub(crate) fn invalid_map_key(
241        path: impl Into<String>,
242        reason: impl Into<Cow<'static, str>>,
243    ) -> Self {
244        Self::new(ErrorKind::InvalidMapKey {
245            path: path.into(),
246            reason: reason.into(),
247        })
248    }
249
250    /// Construct an error for framework-specific logic.
251    pub fn framework(
252        message: impl Into<Cow<'static, str>>,
253        source: impl Into<Box<dyn std::error::Error + Send + Sync>>,
254    ) -> Self {
255        Self::new(ErrorKind::Framework {
256            message: message.into(),
257            source: source.into(),
258        })
259    }
260
261    /// Construct an error for custom format callbacks.
262    pub(crate) fn format(
263        message: impl Into<Cow<'static, str>>,
264        source: impl Into<Box<dyn std::error::Error + Send + Sync>>,
265    ) -> Self {
266        Self::new(ErrorKind::Format {
267            message: message.into(),
268            path: None,
269            source: source.into(),
270        })
271    }
272
273    pub(crate) fn format_at(
274        message: impl Into<Cow<'static, str>>,
275        path: impl Into<String>,
276        source: impl Into<Box<dyn std::error::Error + Send + Sync>>,
277    ) -> Self {
278        Self::new(ErrorKind::Format {
279            message: message.into(),
280            path: Some(path.into()),
281            source: source.into(),
282        })
283    }
284
285    pub(crate) fn bigint_forbidden(path: String) -> Self {
286        Self::new(ErrorKind::BigIntForbidden { path })
287    }
288
289    pub(crate) fn invalid_name(path: String, name: impl Into<Cow<'static, str>>) -> Self {
290        Self::new(ErrorKind::InvalidName {
291            path,
292            name: name.into(),
293        })
294    }
295
296    pub(crate) fn empty_name(path: String) -> Self {
297        Self::new(ErrorKind::EmptyName { path })
298    }
299
300    pub(crate) fn unsupported_anonymous_enum_variant(
301        path: String,
302        variant_kind: &'static str,
303    ) -> Self {
304        Self::new(ErrorKind::UnsupportedAnonymousEnumVariant { path, variant_kind })
305    }
306
307    pub(crate) fn forbidden_name(path: String, name: &'static str) -> Self {
308        Self::new(ErrorKind::ForbiddenName { path, name })
309    }
310
311    pub(crate) fn duplicate_type_name(
312        name: Cow<'static, str>,
313        first: Location<'static>,
314        second: Location<'static>,
315    ) -> Self {
316        Self::new(ErrorKind::DuplicateTypeName {
317            name,
318            first: format_location(first),
319            second: format_location(second),
320        })
321    }
322
323    pub(crate) fn read_dir(path: PathBuf, source: io::Error) -> Self {
324        Self::new(ErrorKind::ReadDir { path, source })
325    }
326
327    pub(crate) fn metadata(path: PathBuf, source: io::Error) -> Self {
328        Self::new(ErrorKind::Metadata { path, source })
329    }
330
331    pub(crate) fn remove_file(path: PathBuf, source: io::Error) -> Self {
332        Self::new(ErrorKind::RemoveFile { path, source })
333    }
334
335    pub(crate) fn remove_dir(path: PathBuf, source: io::Error) -> Self {
336        Self::new(ErrorKind::RemoveDir { path, source })
337    }
338
339    pub(crate) fn create_dir(path: PathBuf, source: io::Error) -> Self {
340        Self::new(ErrorKind::CreateDir { path, source })
341    }
342
343    pub(crate) fn write_file(path: PathBuf, source: io::Error) -> Self {
344        Self::new(ErrorKind::WriteFile { path, source })
345    }
346
347    pub(crate) fn read_file(path: PathBuf, source: io::Error) -> Self {
348        Self::new(ErrorKind::ReadFile { path, source })
349    }
350
351    pub(crate) fn unsupported_opaque_reference(path: String, reference: OpaqueReference) -> Self {
352        Self::new(ErrorKind::UnsupportedOpaqueReference { path, reference })
353    }
354
355    pub(crate) fn dangling_named_reference(path: String, reference: String) -> Self {
356        Self::new(ErrorKind::DanglingNamedReference { path, reference })
357    }
358
359    pub(crate) fn infinite_recursive_inline_type(
360        path: String,
361        reference: String,
362        cycle: RecursiveInlineType,
363    ) -> Self {
364        Self::new(ErrorKind::InfiniteRecursiveInlineType {
365            path,
366            reference,
367            cycle,
368        })
369    }
370
371    pub(crate) fn inline_recursion_limit_exceeded(path: String) -> Self {
372        Self::new(ErrorKind::InlineRecursionLimitExceeded { path })
373    }
374
375    pub(crate) fn export_requires_export_to(layout: Layout) -> Self {
376        Self::new(ErrorKind::ExportRequiresExportTo(layout))
377    }
378
379    pub(crate) fn jsdoc_namespaces_unsupported() -> Self {
380        Self::new(ErrorKind::JsdocNamespacesUnsupported)
381    }
382
383    pub(crate) fn unrepresentable_alias_cycle(
384        path: String,
385        reason: impl Into<Cow<'static, str>>,
386    ) -> Self {
387        Self::new(ErrorKind::UnrepresentableAliasCycle {
388            path,
389            reason: reason.into(),
390        })
391    }
392
393    pub(crate) fn unsupported_semantic_transform(reason: impl Into<Cow<'static, str>>) -> Self {
394        Self::new(ErrorKind::UnsupportedSemanticTransform {
395            reason: reason.into(),
396        })
397    }
398}
399
400impl From<io::Error> for Error {
401    fn from(error: io::Error) -> Self {
402        Self::new(ErrorKind::Io(error))
403    }
404}
405
406impl fmt::Display for Error {
407    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
408        match &self.kind {
409            ErrorKind::InvalidMapKey { path, reason } => {
410                write!(f, "Invalid map key at '{path}': {reason}")
411            }
412            ErrorKind::BigIntForbidden { path } => write!(
413                f,
414                "Attempted to export {path:?} but Specta forbids exporting BigInt-style types (usize, isize, i64, u64, i128, u128) to avoid precision loss. See {BIGINT_DOCS_URL} for a full explanation."
415            ),
416            ErrorKind::ForbiddenName { path, name } => write!(
417                f,
418                "Attempted to export {} but was unable to due to name {name:?} conflicting with a reserved keyword in Typescript. Try renaming it or using `#[specta(rename = \"new name\")]`",
419                display_path(path)
420            ),
421            ErrorKind::InvalidName { path, name } => write!(
422                f,
423                "Attempted to export {} but was unable to due to name {name:?} containing an invalid character. Try renaming it or using `#[specta(rename = \"new name\")]`",
424                display_path(path)
425            ),
426            ErrorKind::EmptyName { path } => write!(
427                f,
428                "Attempted to export {} but was unable to because the Typescript type name is empty. Try renaming it or using `#[specta(rename = \"new name\")]`",
429                display_path(path)
430            ),
431            ErrorKind::UnsupportedAnonymousEnumVariant { path, variant_kind } => write!(
432                f,
433                "Attempted to export {} but anonymous {variant_kind} enum variants cannot be exported to Typescript. Try giving the variant a name or changing the enum representation.",
434                display_path(path)
435            ),
436            ErrorKind::DuplicateTypeName {
437                name,
438                first,
439                second,
440            } => write!(
441                f,
442                "Detected multiple types with the same name: {name:?} at {first} and {second}"
443            ),
444            ErrorKind::Io(err) => write!(f, "IO error: {err}"),
445            ErrorKind::ReadDir { path, source } => {
446                write!(f, "Failed to read directory '{}': {source}", path.display())
447            }
448            ErrorKind::Metadata { path, source } => {
449                write!(
450                    f,
451                    "Failed to read metadata for '{}': {source}",
452                    path.display()
453                )
454            }
455            ErrorKind::RemoveFile { path, source } => {
456                write!(f, "Failed to remove file '{}': {source}", path.display())
457            }
458            ErrorKind::RemoveDir { path, source } => {
459                write!(
460                    f,
461                    "Failed to remove directory '{}': {source}",
462                    path.display()
463                )
464            }
465            ErrorKind::CreateDir { path, source } => {
466                write!(
467                    f,
468                    "Failed to create directory '{}': {source}",
469                    path.display()
470                )
471            }
472            ErrorKind::WriteFile { path, source } => {
473                write!(f, "Failed to write file '{}': {source}", path.display())
474            }
475            ErrorKind::ReadFile { path, source } => {
476                write!(f, "Failed to read file '{}': {source}", path.display())
477            }
478            ErrorKind::UnsupportedOpaqueReference { path, reference } => write!(
479                f,
480                "Found unsupported opaque reference '{}' at {}. It is not supported by the Typescript exporter.",
481                reference.type_name(),
482                display_path(path)
483            ),
484            ErrorKind::DanglingNamedReference { path, reference } => write!(
485                f,
486                "Found dangling named reference {reference} at {}. The referenced type is missing from the resolved type collection.",
487                display_path(path)
488            ),
489            ErrorKind::InfiniteRecursiveInlineType {
490                path,
491                reference,
492                cycle,
493            } => {
494                write!(
495                    f,
496                    "Found infinitely recursive inline named reference {reference} at {}. Recursive inline types cannot be expanded because they would produce an infinite Typescript type.",
497                    display_path(path)
498                )?;
499                write!(f, "\nInline cycle:\n  {cycle:?}")?;
500                Ok(())
501            }
502            ErrorKind::InlineRecursionLimitExceeded { path } if path.is_empty() => write!(
503                f,
504                "Type recursion limit exceeded while expanding the provided inline type. Recursive inline types cannot be expanded because they would produce an infinite Typescript type."
505            ),
506            ErrorKind::InlineRecursionLimitExceeded { path } => write!(
507                f,
508                "Type recursion limit exceeded while expanding an inline Typescript type at {}. Recursive inline types cannot be expanded because they would produce an infinite Typescript type.",
509                display_path(path)
510            ),
511            ErrorKind::Framework { message, source } => {
512                let source = source.to_string();
513                if message.is_empty() && source.is_empty() {
514                    write!(f, "Framework error")
515                } else if source.is_empty() {
516                    write!(f, "Framework error: {message}")
517                } else {
518                    write!(f, "Framework error: {message}: {source}")
519                }
520            }
521            ErrorKind::Format {
522                message,
523                path,
524                source,
525            } => {
526                let source = source.to_string();
527                let location = path
528                    .as_deref()
529                    .filter(|path| !path.is_empty())
530                    .map(|path| format!(" at {}", display_path(path)))
531                    .unwrap_or_default();
532                if message.is_empty() && source.is_empty() {
533                    write!(f, "Format error{location}")
534                } else if source.is_empty() {
535                    write!(f, "Format error{location}: {message}")
536                } else {
537                    write!(f, "Format error{location}: {message}: {source}")
538                }
539            }
540            ErrorKind::ExportRequiresExportTo(layout) => write!(
541                f,
542                "Unable to export layout {layout} as a single string. Use `Exporter::export_to` with a directory path for file-based exports."
543            ),
544            ErrorKind::JsdocNamespacesUnsupported => write!(
545                f,
546                "Unable to export JSDoc with the Namespaces layout. Disable JSDoc or use FlatFile, ModulePrefixedName, or Files layout."
547            ),
548            ErrorKind::UnrepresentableAliasCycle { path, reason } => write!(
549                f,
550                "Attempted to export {} but it is part of a recursive type-alias cycle that cannot be collapsed into valid TypeScript: {reason}. TypeScript rejects self-referential type aliases (TS2456); restructure the type so the recursion passes through an object, array, or tuple instead of a bare (untagged/transparent) reference.",
551                display_path(path)
552            ),
553            ErrorKind::UnsupportedSemanticTransform { reason } => write!(
554                f,
555                "Unable to generate a runtime semantic transform: {reason}. The exported type would otherwise disagree with the value crossing the wire."
556            ),
557        }?;
558
559        if let Some(ndt) = self.named_datatype() {
560            write!(
561                f,
562                "\nRust type: {}::{} at {}",
563                ndt.module_path,
564                ndt.name,
565                format_location(ndt.location)
566            )?;
567        }
568
569        if !self.trace.is_empty() {
570            write!(f, "\nWhile inlining:")?;
571            for frame in self.trace.iter().rev() {
572                match frame {
573                    ErrorTraceFrame::Inlined {
574                        named_datatype,
575                        path,
576                    } => {
577                        write!(f, "\n  {path} -> ")?;
578                        if let Some(ndt) = named_datatype.as_deref() {
579                            write!(f, "{}::{}", ndt.module_path, ndt.name)?;
580                        } else {
581                            write!(f, "<unresolved named type>")?;
582                        }
583                    }
584                }
585            }
586        }
587
588        Ok(())
589    }
590}
591
592impl fmt::Debug for Error {
593    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
594        fmt::Display::fmt(self, f)
595    }
596}
597
598impl error::Error for Error {
599    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
600        match &self.kind {
601            ErrorKind::Io(error) => Some(error),
602            ErrorKind::ReadDir { source, .. }
603            | ErrorKind::Metadata { source, .. }
604            | ErrorKind::RemoveFile { source, .. }
605            | ErrorKind::RemoveDir { source, .. }
606            | ErrorKind::CreateDir { source, .. }
607            | ErrorKind::WriteFile { source, .. }
608            | ErrorKind::ReadFile { source, .. } => Some(source),
609            ErrorKind::Framework { source, .. } | ErrorKind::Format { source, .. } => {
610                Some(source.as_ref())
611            }
612            _ => None,
613        }
614    }
615}
616
617fn format_location(location: Location<'static>) -> String {
618    format!(
619        "{}:{}:{}",
620        location.file(),
621        location.line(),
622        location.column()
623    )
624}
625
626fn display_path(path: &str) -> Cow<'_, str> {
627    if path.is_empty() {
628        Cow::Borrowed("<unknown path>")
629    } else {
630        Cow::Owned(format!("{path:?}"))
631    }
632}