1use std::{borrow::Cow, error, fmt, io, panic::Location, path::PathBuf};
2
3use specta::datatype::{NamedDataType, OpaqueReference, RecursiveInlineType};
4
5use crate::Layout;
6
7#[non_exhaustive]
43pub struct Error {
44 kind: ErrorKind,
45 named_datatype: Option<Box<NamedDataType>>,
46 trace: Vec<ErrorTraceFrame>,
47}
48
49#[derive(Debug, Clone)]
51#[non_exhaustive]
52pub enum ErrorTraceFrame {
53 Inlined {
55 named_datatype: Option<Box<NamedDataType>>,
57 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 InvalidMapKey {
73 path: String,
74 reason: Cow<'static, str>,
75 },
76 BigIntForbidden {
78 path: String,
79 },
80 ForbiddenName {
82 path: String,
83 name: &'static str,
84 },
85 InvalidName {
87 path: String,
88 name: Cow<'static, str>,
89 },
90 EmptyName {
92 path: String,
93 },
94 UnsupportedAnonymousEnumVariant {
96 path: String,
97 variant_kind: &'static str,
98 },
99 DuplicateTypeName {
104 name: Cow<'static, str>,
105 first: String,
106 second: String,
107 },
108 Io(io::Error),
111 ReadDir {
113 path: PathBuf,
114 source: io::Error,
115 },
116 Metadata {
118 path: PathBuf,
119 source: io::Error,
120 },
121 RemoveFile {
123 path: PathBuf,
124 source: io::Error,
125 },
126 RemoveDir {
128 path: PathBuf,
129 source: io::Error,
130 },
131 CreateDir {
133 path: PathBuf,
134 source: io::Error,
135 },
136 WriteFile {
138 path: PathBuf,
139 source: io::Error,
140 },
141 ReadFile {
143 path: PathBuf,
144 source: io::Error,
145 },
146 UnsupportedOpaqueReference {
149 path: String,
150 reference: OpaqueReference,
151 },
152 DanglingNamedReference {
155 path: String,
156 reference: String,
157 },
158 InfiniteRecursiveInlineType {
160 path: String,
161 reference: String,
162 cycle: RecursiveInlineType,
163 },
164 InlineRecursionLimitExceeded {
166 path: String,
167 },
168 Framework {
170 message: Cow<'static, str>,
171 source: FrameworkSource,
172 },
173 Format {
175 message: Cow<'static, str>,
176 path: Option<String>,
177 source: FrameworkSource,
178 },
179 ExportRequiresExportTo(Layout),
184 JsdocNamespacesUnsupported,
185 UnrepresentableAliasCycle {
190 path: String,
191 reason: Cow<'static, str>,
192 },
193 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 pub fn named_datatype(&self) -> Option<&NamedDataType> {
214 self.named_datatype.as_deref()
215 }
216
217 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 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 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}