Skip to main content

specta_typescript/
primitives.rs

1//! Primitives provide building blocks for Specta-based libraries.
2//!
3//! These are for advanced usecases, you should generally use [crate::Typescript] or
4//! [crate::JSDoc] in end-user applications.
5
6use std::{
7    borrow::Cow,
8    collections::{BTreeSet, HashMap, HashSet, hash_map::Entry},
9};
10
11use specta::{
12    Format, Types,
13    datatype::{
14        DataType, Deprecated, Enum, Field, Fields, GenericDefinition, GenericReference, List, Map,
15        NamedDataType, NamedReference, NamedReferenceType, OpaqueReference, Primitive, Reference,
16        Struct, Tuple, Variant,
17    },
18    markers::{ALIAS_EXCLUSION_MARKER, DEFERRED_ALIAS_UNION_MARKER, FINITE_NUMBER_MARKER},
19};
20
21use crate::{
22    Branded, BrandedTypeExporter, Error, Exporter, Layout, map_keys, opaque,
23    reserved_names::RESERVED_TYPE_NAMES,
24};
25
26const STRING: &str = "string";
27const NULL: &str = "null";
28const NEVER: &str = "never";
29
30fn path_string(location: &[Cow<'static, str>]) -> String {
31    location.join(".")
32}
33
34fn rust_type_path(ndt: &NamedDataType) -> Cow<'static, str> {
35    if ndt.module_path.is_empty() {
36        ndt.name.clone()
37    } else {
38        Cow::Owned(format!("{}::{}", ndt.module_path, ndt.name))
39    }
40}
41
42fn module_prefixed_type_name(ndt: &NamedDataType) -> String {
43    let mut name = ndt.module_path.split("::").collect::<Vec<_>>().join("_");
44    if !name.is_empty() {
45        name.push('_');
46    }
47    name.push_str(&ndt.name);
48    name
49}
50
51fn exported_type_name<'a>(exporter: &Exporter, ndt: &'a NamedDataType) -> Cow<'a, str> {
52    match exporter.layout {
53        Layout::ModulePrefixedName => Cow::Owned(module_prefixed_type_name(ndt)),
54        _ => ndt.name.clone(),
55    }
56}
57
58fn referenced_type_name<'a>(exporter: &Exporter, ndt: &'a NamedDataType) -> Cow<'a, str> {
59    match exporter.layout {
60        Layout::ModulePrefixedName => Cow::Owned(module_prefixed_type_name(ndt)),
61        Layout::Namespaces => {
62            if ndt.module_path.is_empty() {
63                ndt.name.clone()
64            } else {
65                let mut path =
66                    ndt.module_path
67                        .split("::")
68                        .fold("$s$.".to_string(), |mut s, segment| {
69                            s.push_str(segment);
70                            s.push('.');
71                            s
72                        });
73                path.push_str(&ndt.name);
74                Cow::Owned(path)
75            }
76        }
77        Layout::Files => {
78            let current_module_path = crate::references::current_module_path().unwrap_or_default();
79
80            if ndt.module_path == current_module_path {
81                ndt.name.clone()
82            } else {
83                let mut path = crate::exporter::module_alias(&ndt.module_path);
84                path.push('.');
85                path.push_str(&ndt.name);
86                Cow::Owned(path)
87            }
88        }
89        _ => ndt.name.clone(),
90    }
91}
92
93fn inner_comments(
94    deprecated: Option<&Deprecated>,
95    docs: &str,
96    other: String,
97    start_with_newline: bool,
98    prefix: &str,
99) -> String {
100    let mut comments = String::new();
101    js_doc(&mut comments, docs, deprecated);
102    if comments.is_empty() {
103        return other;
104    }
105
106    let mut out = String::new();
107    if start_with_newline {
108        out.push('\n');
109    }
110
111    for line in comments.lines() {
112        out.push_str(prefix);
113        out.push_str(line);
114        out.push('\n');
115    }
116
117    out.push_str(&other);
118    out
119}
120
121pub(crate) fn is_identifier(name: &str) -> bool {
122    let mut chars = name.chars();
123    let Some(first) = chars.next() else {
124        return false;
125    };
126
127    (first.is_ascii_alphabetic() || first == '_' || first == '$')
128        && chars.all(|ch| ch.is_ascii_alphanumeric() || ch == '_' || ch == '$')
129}
130
131pub(crate) fn escape_typescript_string_literal(value: &str) -> Cow<'_, str> {
132    if !value.chars().any(|ch| {
133        ch == '"' || ch == '\\' || ch == '\u{2028}' || ch == '\u{2029}' || ch.is_control()
134    }) {
135        return Cow::Borrowed(value);
136    }
137
138    let mut escaped = String::with_capacity(value.len());
139    for ch in value.chars() {
140        match ch {
141            '"' => escaped.push_str(r#"\""#),
142            '\\' => escaped.push_str(r#"\\"#),
143            '\n' => escaped.push_str(r#"\n"#),
144            '\r' => escaped.push_str(r#"\r"#),
145            '\t' => escaped.push_str(r#"\t"#),
146            '\u{2028}' => escaped.push_str(r#"\u2028"#),
147            '\u{2029}' => escaped.push_str(r#"\u2029"#),
148            ch if ch.is_control() => push_unicode_escape(&mut escaped, ch),
149            _ => escaped.push(ch),
150        }
151    }
152
153    Cow::Owned(escaped)
154}
155
156fn push_unicode_escape(s: &mut String, ch: char) {
157    const HEX: &[u8; 16] = b"0123456789ABCDEF";
158    let value = ch as u32;
159
160    s.push_str(r#"\u"#);
161    s.push(HEX[((value >> 12) & 0xF) as usize] as char);
162    s.push(HEX[((value >> 8) & 0xF) as usize] as char);
163    s.push(HEX[((value >> 4) & 0xF) as usize] as char);
164    s.push(HEX[(value & 0xF) as usize] as char);
165}
166
167fn sanitise_key<'a>(field_name: Cow<'static, str>, force_string: bool) -> Cow<'a, str> {
168    if force_string || !is_identifier(&field_name) {
169        format!(r#""{}""#, escape_typescript_string_literal(&field_name)).into()
170    } else {
171        field_name
172    }
173}
174
175fn sanitise_type_name(location: &[Cow<'static, str>], ident: &str) -> Result<String, Error> {
176    let path = path_string(location);
177
178    if ident.is_empty() {
179        return Err(Error::empty_name(path));
180    }
181
182    if let Some(name) = RESERVED_TYPE_NAMES.iter().find(|v| **v == ident) {
183        return Err(Error::forbidden_name(path, name));
184    }
185
186    if let Some(first_char) = ident.chars().next()
187        && !first_char.is_alphabetic()
188        && first_char != '_'
189    {
190        return Err(Error::invalid_name(path, ident.to_string()));
191    }
192
193    if ident
194        .find(|c: char| !c.is_alphanumeric() && c != '_')
195        .is_some()
196    {
197        return Err(Error::invalid_name(path, ident.to_string()));
198    }
199
200    Ok(ident.to_string())
201}
202
203pub(crate) fn js_doc(s: &mut String, docs: &str, deprecated: Option<&Deprecated>) {
204    if docs.is_empty() && deprecated.is_none() {
205        return;
206    }
207
208    if deprecated.is_none() {
209        let mut lines = docs.lines();
210        if let (Some(line), None) = (lines.next(), lines.next()) {
211            s.push_str("/** ");
212            s.push_str(&escape_jsdoc_text(line));
213            s.push_str(" */\n");
214            return;
215        }
216    }
217
218    s.push_str("/**\n");
219    if !docs.is_empty() {
220        for line in docs.lines() {
221            s.push_str(" * ");
222            s.push_str(&escape_jsdoc_text(line));
223            s.push('\n');
224        }
225    }
226
227    if let Some(typ) = deprecated {
228        s.push_str(" * @deprecated");
229        if let Some(details) = deprecated_details(typ) {
230            s.push(' ');
231            s.push_str(&details);
232        }
233        s.push('\n');
234    }
235
236    s.push_str(" */\n");
237}
238
239pub(crate) fn escape_jsdoc_text(text: &str) -> Cow<'_, str> {
240    if text.contains("*/") {
241        Cow::Owned(text.replace("*/", "*\\/"))
242    } else {
243        Cow::Borrowed(text)
244    }
245}
246
247pub(crate) fn deprecated_details(typ: &Deprecated) -> Option<String> {
248    typ.note
249        .as_deref()
250        .map(str::trim)
251        .filter(|note| !note.is_empty())
252        .map(str::to_string)
253}
254
255/// Generate a group of `export Type = ...` Typescript string for a specific [`NamedDataType`].
256///
257/// This method leaves the following up to the implementer:
258///  - Ensuring all referenced types are exported
259///  - Handling multiple type with overlapping names
260///  - Transforming the type for your serialization format (Eg. Serde)
261///
262/// We recommend passing in your types in bulk instead of doing individual calls as it leaves formatting to us and also allows us to merge the JSDoc types into a single large comment.
263///
264/// If you are using a custom format such as `serde::format` with the high-level exporter,
265/// these primitive helpers do not apply that mapping automatically. Standalone primitive usage
266/// should map both the full [`Types`] graph and any top-level [`DataType`] values with matching
267/// helpers first.
268///
269pub fn export<'a>(
270    exporter: &dyn AsRef<Exporter>,
271    types: &Types,
272    ndts: impl Iterator<Item = &'a NamedDataType>,
273    indent: &str,
274) -> Result<String, Error> {
275    let mut s = String::new();
276    export_internal(&mut s, exporter.as_ref(), None, types, ndts, indent)?;
277    Ok(s)
278}
279
280pub(crate) fn export_internal<'a>(
281    s: &mut String,
282    exporter: &Exporter,
283    format: Option<&dyn Format>,
284    types: &Types,
285    ndts: impl Iterator<Item = &'a NamedDataType>,
286    indent: &str,
287) -> Result<(), Error> {
288    let ndts = ndts.filter(|ndt| ndt.ty.is_some());
289
290    if exporter.jsdoc {
291        let mut ndts = ndts.peekable();
292        if ndts.peek().is_none() {
293            return Ok(());
294        }
295
296        s.push_str(indent);
297        s.push_str("/**\n");
298
299        for (index, ndt) in ndts.enumerate() {
300            if index != 0 {
301                s.push_str(indent);
302                s.push_str("\t*\n");
303            }
304
305            append_typedef_body(s, exporter, format, types, ndt, indent)?;
306        }
307
308        s.push_str(indent);
309        s.push_str("\t*/\n");
310        return Ok(());
311    }
312
313    for (index, ndt) in ndts.enumerate() {
314        if index != 0 {
315            s.push('\n');
316        }
317
318        export_single_internal(s, exporter, format, types, ndt, indent)?;
319    }
320
321    Ok(())
322}
323
324fn export_single_internal(
325    s: &mut String,
326    exporter: &Exporter,
327    format: Option<&dyn Format>,
328    types: &Types,
329    ndt: &NamedDataType,
330    indent: &str,
331) -> Result<(), Error> {
332    if exporter.jsdoc {
333        let mut typedef = String::new();
334        typedef_internal(&mut typedef, exporter, format, types, ndt)?;
335        for line in typedef.lines() {
336            s.push_str(indent);
337            s.push_str(line);
338            s.push('\n');
339        }
340        return Ok(());
341    }
342
343    let raw_name = exported_type_name(exporter, ndt);
344    let name = sanitise_type_name(&[rust_type_path(ndt)], &raw_name)
345        .map_err(|err| err.with_named_datatype(ndt))?;
346
347    let mut comments = String::new();
348    js_doc(&mut comments, &ndt.docs, ndt.deprecated.as_ref());
349    if !comments.is_empty() {
350        for line in comments.lines() {
351            s.push_str(indent);
352            s.push_str(line);
353            s.push('\n');
354        }
355    }
356
357    s.push_str(indent);
358    s.push_str("export type ");
359    s.push_str(&name);
360    write_generic_parameters(s, exporter, types, &[rust_type_path(ndt)], &ndt.generics)?;
361    s.push_str(" = ");
362
363    let body = resolve_named_export_body(types, ndt)?;
364    datatype(
365        s,
366        exporter,
367        format,
368        types,
369        &body,
370        vec![rust_type_path(ndt)],
371        Some(ndt.name.as_ref()),
372        indent,
373        Default::default(),
374    )
375    .map_err(|err| err.with_named_datatype(ndt))?;
376    s.push_str(";\n");
377
378    Ok(())
379}
380
381/// Generate an anonymous Typescript string for a specific [`DataType`].
382///
383/// This method leaves all the same things as the [`export`] method up to the user.
384///
385/// Note that calling this method with a tagged struct or enum may cause the tag to not be exported.
386/// The type should be wrapped in a [`NamedDataType`] to provide a proper name.
387///
388/// You are responsible for apply Serde or other format mapping to the top-level datatype in the
389/// same way as the [`Types`] graph before calling this helper.
390///
391pub fn inline(
392    exporter: &dyn AsRef<Exporter>,
393    types: &Types,
394    dt: &DataType,
395) -> Result<String, Error> {
396    let mut s = String::new();
397    inline_datatype(
398        &mut s,
399        exporter.as_ref(),
400        None,
401        types,
402        dt,
403        vec![],
404        None,
405        "",
406        0,
407        &[],
408    )?;
409    Ok(s)
410}
411
412// This can be used internally to prevent cloning `Typescript` instances.
413// Externally this shouldn't be a concern so we don't expose it.
414pub(crate) fn typedef_internal(
415    s: &mut String,
416    exporter: &Exporter,
417    format: Option<&dyn Format>,
418    types: &Types,
419    dt: &NamedDataType,
420) -> Result<(), Error> {
421    s.push_str("/**\n");
422    append_typedef_body(s, exporter, format, types, dt, "")?;
423
424    s.push_str("\t*/");
425
426    Ok(())
427}
428
429fn append_jsdoc_properties(
430    s: &mut String,
431    exporter: &Exporter,
432    format: Option<&dyn Format>,
433    types: &Types,
434    dt_name: &str,
435    dt: &DataType,
436    indent: &str,
437) -> Result<(), Error> {
438    match dt {
439        DataType::Struct(strct) => match &strct.fields {
440            Fields::Unit => {}
441            Fields::Unnamed(unnamed) => {
442                for (idx, field) in unnamed.fields.iter().enumerate() {
443                    let Some(ty) = field.ty.as_ref() else {
444                        continue;
445                    };
446
447                    let mut ty_str = String::new();
448                    let datatype_prefix = format!("{indent}\t*\t");
449                    datatype(
450                        &mut ty_str,
451                        exporter,
452                        format,
453                        types,
454                        ty,
455                        vec![Cow::Owned(dt_name.to_owned()), idx.to_string().into()],
456                        Some(dt_name),
457                        &datatype_prefix,
458                        Default::default(),
459                    )?;
460
461                    push_jsdoc_property(
462                        s,
463                        &ty_str,
464                        &idx.to_string(),
465                        field.optional,
466                        &field.docs,
467                        field.deprecated.as_ref(),
468                        indent,
469                    );
470                }
471            }
472            Fields::Named(named) => {
473                for (name, field) in &named.fields {
474                    let Some(ty) = field.ty.as_ref() else {
475                        continue;
476                    };
477
478                    let mut ty_str = String::new();
479                    let datatype_prefix = format!("{indent}\t*\t");
480                    datatype(
481                        &mut ty_str,
482                        exporter,
483                        format,
484                        types,
485                        ty,
486                        vec![Cow::Owned(dt_name.to_owned()), name.clone()],
487                        Some(dt_name),
488                        &datatype_prefix,
489                        Default::default(),
490                    )?;
491
492                    push_jsdoc_property(
493                        s,
494                        &ty_str,
495                        name,
496                        field.optional,
497                        &field.docs,
498                        field.deprecated.as_ref(),
499                        indent,
500                    );
501                }
502            }
503        },
504        DataType::Enum(enm) => {
505            for (variant_name, variant) in enm.variants.iter().filter(|(_, v)| !v.skip) {
506                let mut one_variant_enum = enm.clone();
507                one_variant_enum
508                    .variants
509                    .retain(|(name, _)| name == variant_name);
510
511                let mut variant_ty = String::new();
512                enum_dt(
513                    &mut variant_ty,
514                    exporter,
515                    types,
516                    &one_variant_enum,
517                    vec![Cow::Owned(dt_name.to_owned())],
518                    "",
519                    &[],
520                )?;
521
522                push_jsdoc_property(
523                    s,
524                    &variant_ty,
525                    variant_name,
526                    false,
527                    &variant.docs,
528                    variant.deprecated.as_ref(),
529                    indent,
530                );
531            }
532        }
533        DataType::Intersection(types_) => {
534            for ty in types_ {
535                append_jsdoc_properties(s, exporter, format, types, dt_name, ty, indent)?;
536            }
537        }
538        _ => {}
539    }
540
541    Ok(())
542}
543
544fn push_jsdoc_property(
545    s: &mut String,
546    ty: &str,
547    name: &str,
548    optional: bool,
549    docs: &str,
550    deprecated: Option<&Deprecated>,
551    indent: &str,
552) {
553    s.push_str(indent);
554    s.push_str("\t* @property {");
555    push_jsdoc_type(s, ty, indent);
556    s.push_str("} ");
557    s.push_str(&jsdoc_property_name(name, optional));
558
559    if let Some(description) = jsdoc_description(docs, deprecated) {
560        s.push_str(" - ");
561        s.push_str(&description);
562    }
563
564    s.push('\n');
565}
566
567fn push_jsdoc_type(s: &mut String, ty: &str, indent: &str) {
568    let mut lines = ty.lines();
569    if let Some(first_line) = lines.next() {
570        s.push_str(first_line);
571    }
572
573    for line in lines {
574        s.push('\n');
575
576        if line
577            .strip_prefix(indent)
578            .is_some_and(|rest| rest.starts_with("\t*"))
579        {
580            s.push_str(line);
581        } else {
582            s.push_str(indent);
583            s.push_str("\t* ");
584            s.push_str(line);
585        }
586    }
587}
588
589fn jsdoc_property_name(name: &str, optional: bool) -> String {
590    let name = if is_identifier(name) {
591        name.to_string()
592    } else {
593        format!("\"{}\"", escape_typescript_string_literal(name))
594    };
595
596    if optional { format!("[{name}]") } else { name }
597}
598
599fn append_typedef_body(
600    s: &mut String,
601    exporter: &Exporter,
602    format: Option<&dyn Format>,
603    types: &Types,
604    dt: &NamedDataType,
605    indent: &str,
606) -> Result<(), Error> {
607    let name = &dt.name;
608    let mut type_name = String::from(name.as_ref());
609    write_generic_parameters(
610        &mut type_name,
611        exporter,
612        types,
613        &[rust_type_path(dt)],
614        &dt.generics,
615    )?;
616
617    let mut typedef_ty = String::new();
618    let datatype_prefix = format!("{indent}\t*\t");
619    let body = resolve_named_export_body(types, dt)?;
620    datatype(
621        &mut typedef_ty,
622        exporter,
623        format,
624        types,
625        &body,
626        vec![rust_type_path(dt)],
627        Some(dt.name.as_ref()),
628        &datatype_prefix,
629        Default::default(),
630    )
631    .map_err(|err| err.with_named_datatype(dt))?;
632
633    if !dt.docs.is_empty() {
634        for line in dt.docs.lines() {
635            s.push_str(indent);
636            s.push_str("\t* ");
637            s.push_str(&escape_jsdoc_text(line));
638            s.push('\n');
639        }
640        s.push_str(indent);
641        s.push_str("\t*\n");
642    }
643
644    if let Some(deprecated) = dt.deprecated.as_ref() {
645        s.push_str(indent);
646        s.push_str("\t* @deprecated");
647        if let Some(details) = deprecated_details(deprecated) {
648            s.push(' ');
649            s.push_str(&details);
650        }
651        s.push('\n');
652    }
653
654    s.push_str(indent);
655    s.push_str("\t* @typedef {");
656    push_jsdoc_type(s, &typedef_ty, indent);
657    s.push_str("} ");
658    s.push_str(&type_name);
659    s.push('\n');
660
661    if let Some(ty) = &dt.ty {
662        let dt_path = rust_type_path(dt);
663        append_jsdoc_properties(s, exporter, format, types, dt_path.as_ref(), ty, indent)?;
664    }
665
666    Ok(())
667}
668
669fn write_generic_parameters(
670    s: &mut String,
671    exporter: &Exporter,
672    types: &Types,
673    parent_location: &[Cow<'static, str>],
674    generics: &[GenericDefinition],
675) -> Result<(), Error> {
676    if generics.is_empty() {
677        return Ok(());
678    }
679
680    s.push('<');
681    for (index, generic) in generics.iter().enumerate() {
682        if index != 0 {
683            s.push_str(", ");
684        }
685
686        s.push_str(generic.name.as_ref());
687
688        if let Some(default) = &generic.default {
689            let mut rendered_default = String::new();
690            let mut default_location = parent_location.to_vec();
691            default_location.push(format!("<generic {} default>", generic.name).into());
692            shallow_inline_datatype(
693                &mut rendered_default,
694                exporter,
695                None,
696                types,
697                default,
698                default_location,
699                None,
700                "",
701                Default::default(),
702            )?;
703            s.push_str(" = ");
704            s.push_str(&rendered_default);
705        }
706    }
707    s.push('>');
708
709    Ok(())
710}
711
712fn jsdoc_description(docs: &str, deprecated: Option<&Deprecated>) -> Option<String> {
713    let docs = docs
714        .lines()
715        .map(str::trim)
716        .filter(|line| !line.is_empty())
717        .map(|line| escape_jsdoc_text(line).into_owned())
718        .collect::<Vec<_>>()
719        .join(" ");
720
721    let deprecated = deprecated.map(|deprecated| {
722        let mut value = String::from("@deprecated");
723        if let Some(details) = deprecated_details(deprecated) {
724            value.push(' ');
725            value.push_str(&escape_jsdoc_text(&details));
726        }
727        value
728    });
729
730    match (docs.is_empty(), deprecated) {
731        (true, None) => None,
732        (true, Some(deprecated)) => Some(deprecated),
733        (false, None) => Some(docs),
734        (false, Some(deprecated)) => Some(format!("{docs} {deprecated}")),
735    }
736}
737
738/// Generate a Typescript string for a specific [`DataType`] while preserving ordinary named
739/// references recursively.
740///
741/// Unlike [`inline`], named types are rendered as references even when nested within an anonymous
742/// composite type. References explicitly marked as inline are still expanded.
743///
744/// See [`export`] for the list of things to consider when using this.
745pub fn reference(
746    exporter: &dyn AsRef<Exporter>,
747    types: &Types,
748    dt: &DataType,
749) -> Result<String, Error> {
750    let mut s = String::new();
751    datatype(
752        &mut s,
753        exporter.as_ref(),
754        None,
755        types,
756        dt,
757        vec![],
758        None,
759        "",
760        &[],
761    )?;
762    Ok(s)
763}
764
765pub(crate) fn datatype_with_inline_attr(
766    s: &mut String,
767    exporter: &Exporter,
768    format: Option<&dyn Format>,
769    types: &Types,
770    dt: &DataType,
771    location: Vec<Cow<'static, str>>,
772    parent_name: Option<&str>,
773    prefix: &str,
774    generics: &[(GenericReference, DataType)],
775    shallow_inline: bool,
776) -> Result<(), Error> {
777    if shallow_inline {
778        let inline_path = path_string(&location);
779        return shallow_inline_datatype(
780            s,
781            exporter,
782            format,
783            types,
784            dt,
785            location,
786            parent_name,
787            prefix,
788            generics,
789        )
790        .map_err(|err| err.with_inline_trace(inline_named_datatype(types, dt), inline_path));
791    }
792
793    datatype(
794        s,
795        exporter,
796        format,
797        types,
798        dt,
799        location,
800        parent_name,
801        prefix,
802        generics,
803    )
804}
805
806fn write_generic_reference(s: &mut String, generic: &GenericReference) {
807    s.push_str(generic.name());
808}
809
810fn scoped_reference_generics(
811    parent_generics: &[(GenericReference, DataType)],
812    reference_generics: &[(GenericReference, DataType)],
813) -> Vec<(GenericReference, DataType)> {
814    parent_generics
815        .iter()
816        .filter(|(parent_generic, _)| {
817            !reference_generics
818                .iter()
819                .any(|(child_generic, _)| child_generic == parent_generic)
820        })
821        .cloned()
822        .collect()
823}
824
825fn named_reference_generics(r: &NamedReference) -> Result<&[(GenericReference, DataType)], Error> {
826    match &r.inner {
827        NamedReferenceType::Reference { generics, .. } => Ok(generics),
828        NamedReferenceType::Inline { .. } => Ok(&[]),
829        NamedReferenceType::Recursive(_) => Ok(&[]),
830    }
831}
832
833fn named_reference_ty<'a>(
834    types: &'a Types,
835    r: &'a NamedReference,
836    location: &[Cow<'static, str>],
837) -> Result<&'a DataType, Error> {
838    let path = path_string(location);
839    match &r.inner {
840        NamedReferenceType::Reference { .. } => types
841            .get(r)
842            .and_then(|ndt| ndt.ty.as_ref())
843            .ok_or_else(|| Error::dangling_named_reference(path, format!("{r:?}"))),
844        NamedReferenceType::Inline { dt, .. } => Ok(dt),
845        NamedReferenceType::Recursive(cycle) => Err(Error::infinite_recursive_inline_type(
846            path,
847            format!("{r:?}"),
848            cycle.clone(),
849        )),
850    }
851}
852
853fn inline_named_datatype<'a>(types: &'a Types, dt: &DataType) -> Option<&'a NamedDataType> {
854    match dt {
855        DataType::Reference(Reference::Named(r)) => types.get(r),
856        _ => None,
857    }
858}
859
860fn resolve_scoped_generic_default(
861    default: &DataType,
862    scoped_generics: &[(GenericReference, DataType)],
863) -> DataType {
864    match default {
865        DataType::Generic(default) => scoped_generics
866            .iter()
867            .find_map(|(reference, dt)| (reference == default).then_some(dt.clone()))
868            .unwrap_or_else(|| DataType::Generic(default.clone())),
869        default => default.clone(),
870    }
871}
872
873fn resolved_reference_generics(
874    ndt: &specta::datatype::NamedDataType,
875    r: &NamedReference,
876    parent_generics: &[(GenericReference, DataType)],
877) -> Option<(Vec<DataType>, bool, Vec<(GenericReference, DataType)>)> {
878    let reference_generics = named_reference_generics(r).ok()?;
879    let mut scoped_generics = scoped_reference_generics(parent_generics, reference_generics);
880    let mut all_default = true;
881    let mut rendered_generics = Vec::with_capacity(ndt.generics.len());
882
883    for generic in ndt.generics.iter() {
884        let explicit = reference_generics
885            .iter()
886            .find(|(reference, _)| *reference == generic.reference())
887            .map(|(_, dt)| dt.clone());
888
889        let resolved_default = generic
890            .default
891            .as_ref()
892            .map(|default| resolve_scoped_generic_default(default, &scoped_generics));
893
894        let resolved = explicit.or_else(|| resolved_default.clone()).or_else(|| {
895            Some(DataType::Reference(Reference::opaque(
896                crate::opaque::Unknown,
897            )))
898        });
899
900        let resolved = resolved?;
901        all_default &= resolved_default
902            .as_ref()
903            .is_some_and(|default| default == &resolved);
904        scoped_generics.push((generic.reference(), resolved.clone()));
905        rendered_generics.push(resolved);
906    }
907
908    Some((rendered_generics, all_default, scoped_generics))
909}
910
911#[derive(Clone, Copy)]
912struct RenderCtx<'a> {
913    exporter: &'a Exporter,
914    format: Option<&'a dyn Format>,
915    types: &'a Types,
916    parent_name: Option<&'a str>,
917    prefix: &'a str,
918    generics: &'a [(GenericReference, DataType)],
919}
920
921#[derive(Clone, Copy)]
922enum RenderMode {
923    Normal,
924    ShallowInline,
925}
926
927impl RenderMode {
928    fn render(
929        self,
930        s: &mut String,
931        ctx: RenderCtx<'_>,
932        dt: &DataType,
933        location: Vec<Cow<'static, str>>,
934    ) -> Result<(), Error> {
935        match self {
936            Self::Normal => datatype(
937                s,
938                ctx.exporter,
939                ctx.format,
940                ctx.types,
941                dt,
942                location,
943                ctx.parent_name,
944                ctx.prefix,
945                ctx.generics,
946            ),
947            Self::ShallowInline => shallow_inline_datatype(
948                s,
949                ctx.exporter,
950                ctx.format,
951                ctx.types,
952                dt,
953                location,
954                ctx.parent_name,
955                ctx.prefix,
956                ctx.generics,
957            ),
958        }
959    }
960
961    fn render_intersection_part(
962        self,
963        s: &mut String,
964        ctx: RenderCtx<'_>,
965        dt: &DataType,
966        location: Vec<Cow<'static, str>>,
967    ) -> Result<(), Error> {
968        match (self, dt) {
969            (Self::ShallowInline, DataType::Reference(r)) => reference_dt(
970                s,
971                ctx.exporter,
972                ctx.format,
973                ctx.types,
974                r,
975                location,
976                ctx.prefix,
977                ctx.generics,
978            ),
979            _ => self.render(s, ctx, dt, location),
980        }
981    }
982}
983
984fn render_datatype(
985    s: &mut String,
986    ctx: RenderCtx<'_>,
987    dt: &DataType,
988    location: Vec<Cow<'static, str>>,
989    mode: RenderMode,
990) -> Result<(), Error> {
991    match (mode, dt) {
992        (_, DataType::Primitive(p)) => s.push_str(primitive_dt(p, location)?),
993        (_, DataType::Generic(g)) => write_generic_reference(s, g),
994        (RenderMode::Normal, DataType::List(list)) => {
995            list_dt(s, ctx.exporter, ctx.types, list, location, ctx.generics)?;
996        }
997        (RenderMode::ShallowInline, DataType::List(list)) => {
998            let mut inner = String::new();
999            render_datatype(&mut inner, ctx, &list.ty, location, mode)?;
1000            push_list(s, &inner, list.length);
1001        }
1002        (RenderMode::Normal, DataType::Map(map)) => {
1003            map_dt(
1004                s,
1005                ctx.exporter,
1006                ctx.format,
1007                ctx.types,
1008                map,
1009                location,
1010                ctx.generics,
1011            )?;
1012        }
1013        (RenderMode::ShallowInline, DataType::Map(map)) => render_map(
1014            s,
1015            ctx.exporter,
1016            ctx.format,
1017            ctx.types,
1018            map,
1019            location,
1020            ctx.parent_name,
1021            ctx.prefix,
1022            ctx.generics,
1023            mode,
1024        )?,
1025        (_, DataType::Nullable(inner)) => {
1026            let mut rendered = String::new();
1027            let child_ctx = RenderCtx { prefix: "", ..ctx };
1028            render_datatype(&mut rendered, child_ctx, inner, location, mode)?;
1029            push_nullable(s, &rendered);
1030        }
1031        (_, DataType::Struct(st)) => struct_dt(
1032            s,
1033            ctx.exporter,
1034            ctx.format,
1035            ctx.types,
1036            st,
1037            location,
1038            ctx.parent_name,
1039            ctx.prefix,
1040            ctx.generics,
1041        )?,
1042        (_, DataType::Enum(enm)) => enum_dt(
1043            s,
1044            ctx.exporter,
1045            ctx.types,
1046            enm,
1047            location,
1048            ctx.prefix,
1049            ctx.generics,
1050        )?,
1051        (RenderMode::Normal, DataType::Tuple(tuple)) => {
1052            tuple_dt(s, ctx.exporter, ctx.types, tuple, location, ctx.generics)?;
1053        }
1054        (RenderMode::ShallowInline, DataType::Tuple(tuple)) => match tuple.elements.as_slice() {
1055            [] => s.push_str(NULL),
1056            elements => {
1057                s.push('[');
1058                for (idx, dt) in elements.iter().enumerate() {
1059                    if idx != 0 {
1060                        s.push_str(", ");
1061                    }
1062                    render_datatype(s, ctx, dt, location.clone(), mode)?;
1063                }
1064                s.push(']');
1065            }
1066        },
1067        (_, DataType::Intersection(parts)) => {
1068            write_intersection(s, ctx, parts, location, mode)?;
1069        }
1070        (RenderMode::Normal, DataType::Reference(r)) => reference_dt(
1071            s,
1072            ctx.exporter,
1073            ctx.format,
1074            ctx.types,
1075            r,
1076            location,
1077            ctx.prefix,
1078            ctx.generics,
1079        )?,
1080        (RenderMode::ShallowInline, DataType::Reference(r)) => match r {
1081            Reference::Named(r) => {
1082                let ty = named_reference_ty(ctx.types, r, &location)?;
1083                let reference_generics = named_reference_generics(r)?;
1084                let child_ctx = RenderCtx {
1085                    generics: reference_generics,
1086                    ..ctx
1087                };
1088                let inline_path = path_string(&location);
1089                render_datatype(s, child_ctx, ty, location, mode)
1090                    .map_err(|err| err.with_inline_trace(ctx.types.get(r), inline_path))?;
1091            }
1092            Reference::Opaque(_) => reference_dt(
1093                s,
1094                ctx.exporter,
1095                ctx.format,
1096                ctx.types,
1097                r,
1098                location,
1099                ctx.prefix,
1100                ctx.generics,
1101            )?,
1102        },
1103    }
1104
1105    Ok(())
1106}
1107
1108fn needs_array_parens(ty: &str) -> bool {
1109    ty.contains(' ') && (!ty.ends_with('}') || ty.contains('&') || ty.contains('|'))
1110}
1111
1112fn push_list(s: &mut String, ty: &str, length: Option<usize>) {
1113    let ty = if needs_array_parens(ty) {
1114        Cow::Owned(format!("({ty})"))
1115    } else {
1116        Cow::Borrowed(ty)
1117    };
1118
1119    if let Some(length) = length {
1120        s.push('[');
1121        for i in 0..length {
1122            if i != 0 {
1123                s.push_str(", ");
1124            }
1125            s.push_str(&ty);
1126        }
1127        s.push(']');
1128    } else {
1129        s.push_str(&ty);
1130        s.push_str("[]");
1131    }
1132}
1133
1134/// Whether a primitive renders as a union.
1135///
1136/// Floats render as `number | null` because NaN and Infinity are not
1137/// representable as JSON numbers.
1138fn primitive_is_union(p: &Primitive) -> bool {
1139    matches!(p, Primitive::f16 | Primitive::f32 | Primitive::f64)
1140}
1141
1142/// Whether `ty` can be written as an operand of a TypeScript intersection
1143/// without parentheses.
1144///
1145/// `&` binds tighter than `|`, so an operand that renders a top-level union
1146/// escapes the intersection: `{ x: boolean } & A | B` parses as
1147/// `({ x: boolean } & A) | B`, dropping the required `x` from the second arm.
1148/// Every operand that is not a primary expression must therefore be wrapped.
1149///
1150/// Precedence would ideally be carried alongside the rendered text. Until the
1151/// renderer does that, we classify the datatype instead, treating anything we
1152/// cannot prove atomic as non-atomic. Inline references, branded payloads and
1153/// newtypes are the cases where the rendered shape is not visible from the
1154/// datatype at the boundary.
1155fn intersection_operand_is_atomic(ty: &DataType) -> bool {
1156    match ty {
1157        DataType::Primitive(p) => !primitive_is_union(p),
1158        DataType::Nullable(_) => false,
1159        // An enum renders a union of its variants (or `never` when empty), and
1160        // even a single-variant enum can render a union when its payload is
1161        // itself a union. Treat every enum as non-atomic.
1162        DataType::Enum(_) => false,
1163        DataType::Intersection(parts) if parts.len() == 1 => {
1164            intersection_operand_is_atomic(&parts[0])
1165        }
1166        // A genuine newtype (one declared unnamed field) renders as its bare
1167        // inner type, so it inherits that type's precedence. Every other struct
1168        // shape renders an object literal or tuple, both primary expressions.
1169        // `inline_struct_with_generics` delegates unnamed fields to `struct_dt`,
1170        // so this covers the inline path too.
1171        DataType::Struct(strct) => match &strct.fields {
1172            Fields::Unnamed(unnamed) if unnamed.fields.len() == 1 => unnamed
1173                .fields
1174                .first()
1175                .and_then(|field| field.ty.as_ref())
1176                .is_none_or(intersection_operand_is_atomic),
1177            _ => true,
1178        },
1179        // An inline reference is expanded where it is used. Its datatype is
1180        // attached to the reference (not resolved through `Types`), so we can
1181        // classify the shape that will actually be rendered.
1182        DataType::Reference(Reference::Named(r)) => match &r.inner {
1183            NamedReferenceType::Inline { dt, .. } => intersection_operand_is_atomic(dt),
1184            _ => true,
1185        },
1186        // `Branded` renders `<payload> & { readonly __brand: ... }` and `Define`
1187        // renders arbitrary caller-supplied text; neither is a primary
1188        // expression we can prove atomic.
1189        DataType::Reference(Reference::Opaque(r)) => {
1190            !(r.downcast_ref::<Branded>().is_some() || r.downcast_ref::<opaque::Define>().is_some())
1191        }
1192        _ => true,
1193    }
1194}
1195
1196/// Append an already-rendered intersection operand, wrapping it in parentheses
1197/// unless [`intersection_operand_is_atomic`] proves it is a primary expression.
1198fn push_intersection_operand(s: &mut String, ty: &DataType, rendered: &str) {
1199    if intersection_operand_is_atomic(ty) {
1200        s.push_str(rendered);
1201    } else {
1202        s.push('(');
1203        s.push_str(rendered);
1204        s.push(')');
1205    }
1206}
1207
1208fn push_nullable(s: &mut String, inner: &str) {
1209    s.push_str(inner);
1210    if inner != NULL && !inner.ends_with(" | null") {
1211        s.push_str(" | null");
1212    }
1213}
1214
1215fn is_exhaustive_map_key(
1216    dt: &DataType,
1217    types: &Types,
1218    generics: &[(GenericReference, DataType)],
1219) -> bool {
1220    match dt {
1221        DataType::Enum(e) => e.variants.iter().filter(|(_, v)| !v.skip).count() == 0,
1222        DataType::Reference(Reference::Named(r)) => named_reference_ty(types, r, &[])
1223            .and_then(|ty| {
1224                named_reference_generics(r).map(|reference_generics| {
1225                    let substitution = generics
1226                        .iter()
1227                        .map(|(generic, dt)| (generic.name().clone(), dt.clone()))
1228                        .collect::<GenericSubst>();
1229                    let reference_generics = reference_generics
1230                        .iter()
1231                        .map(|(generic, dt)| {
1232                            let mut dt = dt.clone();
1233                            let _ = substitute_generics(&mut dt, &substitution);
1234                            (generic.clone(), dt)
1235                        })
1236                        .collect::<Vec<_>>();
1237                    is_exhaustive_map_key(ty, types, &reference_generics)
1238                })
1239            })
1240            .unwrap_or(false),
1241        DataType::Struct(strct) => match &strct.fields {
1242            Fields::Unnamed(fields) => {
1243                let mut fields = fields.fields.iter().filter_map(|field| field.ty.as_ref());
1244                fields
1245                    .next()
1246                    .is_none_or(|dt| is_exhaustive_map_key(dt, types, generics))
1247                    && fields.next().is_none()
1248            }
1249            _ => true,
1250        },
1251        DataType::Reference(Reference::Opaque(_)) => false,
1252        DataType::Generic(generic) => generics
1253            .iter()
1254            .find(|(candidate, _)| candidate == generic)
1255            .is_none_or(|(_, dt)| {
1256                matches!(dt, DataType::Generic(candidate) if candidate == generic)
1257                    || is_exhaustive_map_key(dt, types, generics)
1258            }),
1259        _ => true,
1260    }
1261}
1262
1263fn render_map(
1264    s: &mut String,
1265    exporter: &Exporter,
1266    format: Option<&dyn Format>,
1267    types: &Types,
1268    map: &Map,
1269    location: Vec<Cow<'static, str>>,
1270    parent_name: Option<&str>,
1271    prefix: &str,
1272    generics: &[(GenericReference, DataType)],
1273    value_mode: RenderMode,
1274) -> Result<(), Error> {
1275    let path = map_key_path(&location);
1276    map_keys::validate_map_key(map.key_ty(), types, format!("{path}.<map_key>"))?;
1277
1278    let rendered_key = map_key_render_type(map.key_ty().clone());
1279    let key_shape = map_keys::map_key_shape(&rendered_key, types, generics);
1280    // A key normalised to a lexical string/number (or a locally constrained
1281    // type parameter) is exhaustive in the same sense a `String` key is, so it
1282    // must not be wrapped in `Partial<>`. Everything else keeps the existing
1283    // enum/`Partial<>` behaviour.
1284    let exhaustive = !matches!(key_shape, map_keys::MapKeyShape::Property)
1285        || is_exhaustive_map_key(&rendered_key, types, generics);
1286
1287    // Use `{ [key in K]: V }` instead of `Record<K, V>` to avoid circular reference issues.
1288    if !exhaustive {
1289        s.push_str("Partial<");
1290    }
1291
1292    s.push_str("{ [key in ");
1293    map_key_datatype(
1294        s,
1295        exporter,
1296        format,
1297        types,
1298        &rendered_key,
1299        key_shape,
1300        location.clone(),
1301        parent_name,
1302        prefix,
1303        generics,
1304    )?;
1305    s.push_str("]: ");
1306    value_mode.render(
1307        s,
1308        RenderCtx {
1309            exporter,
1310            format,
1311            types,
1312            parent_name,
1313            prefix,
1314            generics,
1315        },
1316        map.value_ty(),
1317        location,
1318    )?;
1319    s.push_str(" }");
1320
1321    if !exhaustive {
1322        s.push('>');
1323    }
1324
1325    Ok(())
1326}
1327
1328fn shallow_inline_datatype(
1329    s: &mut String,
1330    exporter: &Exporter,
1331    format: Option<&dyn Format>,
1332    types: &Types,
1333    dt: &DataType,
1334    location: Vec<Cow<'static, str>>,
1335    parent_name: Option<&str>,
1336    prefix: &str,
1337    generics: &[(GenericReference, DataType)],
1338) -> Result<(), Error> {
1339    render_datatype(
1340        s,
1341        RenderCtx {
1342            exporter,
1343            format,
1344            types,
1345            parent_name,
1346            prefix,
1347            generics,
1348        },
1349        dt,
1350        location,
1351        RenderMode::ShallowInline,
1352    )
1353}
1354
1355/// Join `parts` with ` & `, parenthesising every operand that is not a primary
1356/// expression (see [`intersection_operand_is_atomic`]).
1357fn write_intersection(
1358    s: &mut String,
1359    ctx: RenderCtx<'_>,
1360    parts: &[DataType],
1361    location: Vec<Cow<'static, str>>,
1362    mode: RenderMode,
1363) -> Result<(), Error> {
1364    for (idx, part) in parts.iter().enumerate() {
1365        if idx != 0 {
1366            s.push_str(" & ");
1367        }
1368
1369        let mut rendered = String::new();
1370        mode.render_intersection_part(&mut rendered, ctx, part, location.clone())?;
1371        // A lone operand is the whole expression, so it needs no parentheses
1372        // here; an enclosing intersection wraps it if it needs wrapping.
1373        if parts.len() > 1 {
1374            push_intersection_operand(s, part, &rendered);
1375        } else {
1376            s.push_str(&rendered);
1377        }
1378    }
1379
1380    Ok(())
1381}
1382
1383// Render an anonymous type while expanding core-provided inline references.
1384fn inline_datatype(
1385    s: &mut String,
1386    exporter: &Exporter,
1387    format: Option<&dyn Format>,
1388    types: &Types,
1389    dt: &DataType,
1390    location: Vec<Cow<'static, str>>,
1391    parent_name: Option<&str>,
1392    prefix: &str,
1393    depth: usize,
1394    generics: &[(GenericReference, DataType)],
1395) -> Result<(), Error> {
1396    // Prevent infinite recursion
1397    if depth == 25 {
1398        return Err(Error::inline_recursion_limit_exceeded(path_string(
1399            &location,
1400        )));
1401    }
1402
1403    match dt {
1404        DataType::Primitive(p) => s.push_str(primitive_dt(p, location)?),
1405        DataType::Generic(g) => write_generic_reference(s, g),
1406        DataType::List(l) => {
1407            let mut dt_str = String::new();
1408            datatype(
1409                &mut dt_str,
1410                exporter,
1411                format,
1412                types,
1413                &l.ty,
1414                location.clone(),
1415                parent_name,
1416                prefix,
1417                generics,
1418            )?;
1419            push_list(s, &dt_str, l.length);
1420        }
1421        DataType::Map(m) => map_dt(s, exporter, format, types, m, location, generics)?,
1422        DataType::Nullable(def) => {
1423            let mut inner = String::new();
1424            inline_datatype(
1425                &mut inner,
1426                exporter,
1427                format,
1428                types,
1429                def,
1430                location,
1431                parent_name,
1432                "",
1433                depth + 1,
1434                generics,
1435            )?;
1436
1437            push_nullable(s, &inner);
1438        }
1439        DataType::Struct(st) => {
1440            if !generics.is_empty() {
1441                inline_struct_with_generics(
1442                    s,
1443                    exporter,
1444                    format,
1445                    types,
1446                    st,
1447                    location,
1448                    parent_name,
1449                    prefix,
1450                    depth,
1451                    generics,
1452                )?;
1453            } else {
1454                struct_dt(
1455                    s,
1456                    exporter,
1457                    format,
1458                    types,
1459                    st,
1460                    location,
1461                    parent_name,
1462                    prefix,
1463                    generics,
1464                )?;
1465            }
1466        }
1467        DataType::Enum(e) => enum_dt(s, exporter, types, e, location, prefix, generics)?,
1468        DataType::Tuple(t) => tuple_dt(s, exporter, types, t, location, generics)?,
1469        DataType::Intersection(types_) => write_intersection(
1470            s,
1471            RenderCtx {
1472                exporter,
1473                format,
1474                types,
1475                parent_name,
1476                prefix,
1477                generics,
1478            },
1479            types_,
1480            location,
1481            RenderMode::Normal,
1482        )?,
1483        DataType::Reference(r) => {
1484            if let Reference::Named(r) = r
1485                && let Ok(ty) = named_reference_ty(types, r, &location)
1486            {
1487                let reference_generics = named_reference_generics(r)?;
1488                let inline_path = path_string(&location);
1489                inline_datatype(
1490                    s,
1491                    exporter,
1492                    format,
1493                    types,
1494                    ty,
1495                    location,
1496                    parent_name,
1497                    prefix,
1498                    depth + 1,
1499                    reference_generics,
1500                )
1501                .map_err(|err| err.with_inline_trace(types.get(r), inline_path))?;
1502            } else {
1503                reference_dt(s, exporter, format, types, r, location, prefix, generics)?;
1504            }
1505        }
1506    }
1507
1508    Ok(())
1509}
1510
1511fn inline_struct_with_generics(
1512    s: &mut String,
1513    exporter: &Exporter,
1514    format: Option<&dyn Format>,
1515    types: &Types,
1516    st: &Struct,
1517    location: Vec<Cow<'static, str>>,
1518    parent_name: Option<&str>,
1519    prefix: &str,
1520    depth: usize,
1521    generics: &[(GenericReference, DataType)],
1522) -> Result<(), Error> {
1523    match &st.fields {
1524        Fields::Unit => s.push_str(NULL),
1525        Fields::Unnamed(_) => struct_dt(
1526            s,
1527            exporter,
1528            format,
1529            types,
1530            st,
1531            location,
1532            parent_name,
1533            prefix,
1534            generics,
1535        )?,
1536        Fields::Named(named) => {
1537            s.push('{');
1538            let mut has_field = false;
1539
1540            for (key, field) in &named.fields {
1541                let Some(field_ty) = field.ty.as_ref() else {
1542                    continue;
1543                };
1544
1545                has_field = true;
1546                s.push('\n');
1547                s.push_str(prefix);
1548                s.push('\t');
1549                s.push_str(&sanitise_key(key.clone(), false));
1550                if field.optional {
1551                    s.push('?');
1552                }
1553                s.push_str(": ");
1554                inline_datatype(
1555                    s,
1556                    exporter,
1557                    format,
1558                    types,
1559                    field_ty,
1560                    location.clone(),
1561                    parent_name,
1562                    prefix,
1563                    depth + 1,
1564                    generics,
1565                )?;
1566                s.push(',');
1567            }
1568
1569            if has_field {
1570                s.push('\n');
1571                s.push_str(prefix);
1572            }
1573
1574            s.push('}');
1575        }
1576    }
1577
1578    Ok(())
1579}
1580
1581pub(crate) fn datatype(
1582    s: &mut String,
1583    exporter: &Exporter,
1584    format: Option<&dyn Format>,
1585    types: &Types,
1586    dt: &DataType,
1587    location: Vec<Cow<'static, str>>,
1588    parent_name: Option<&str>,
1589    prefix: &str,
1590    generics: &[(GenericReference, DataType)],
1591) -> Result<(), Error> {
1592    render_datatype(
1593        s,
1594        RenderCtx {
1595            exporter,
1596            format,
1597            types,
1598            parent_name,
1599            prefix,
1600            generics,
1601        },
1602        dt,
1603        location,
1604        RenderMode::Normal,
1605    )
1606}
1607
1608fn primitive_dt(p: &Primitive, location: Vec<Cow<'static, str>>) -> Result<&'static str, Error> {
1609    use Primitive::*;
1610
1611    Ok(match p {
1612        i8 | i16 | i32 | u8 | u16 | u32 => "number",
1613        // `null` comes from `NaN`, `Infinity` and `-Infinity`. Is done by JS APIs and Serde JSON.
1614        f16 | f32 | f64 /* this looks wrong but `f64` is the direct equivalent of `number` */ => "number | null",
1615        usize | isize | i64 | u64 | i128 | u128 | f128 => {
1616            return Err(Error::bigint_forbidden(location.join(".")));
1617        }
1618        Primitive::bool => "boolean",
1619        str | char => "string",
1620    })
1621}
1622
1623fn list_dt(
1624    s: &mut String,
1625    exporter: &Exporter,
1626    types: &Types,
1627    l: &List,
1628    location: Vec<Cow<'static, str>>,
1629    generics: &[(GenericReference, DataType)],
1630) -> Result<(), Error> {
1631    let mut dt = String::new();
1632    datatype(
1633        &mut dt, exporter, None, types, &l.ty, location, None, "", generics,
1634    )?;
1635    push_list(s, &dt, l.length);
1636
1637    Ok(())
1638}
1639
1640/// Renders a map key as a TypeScript mapped-type key.
1641///
1642/// Object property names have stricter rules than values, so a key never
1643/// reuses the value rendering directly. [`map_keys::map_key_shape`] classifies
1644/// the key into a key-safe shape (see [`map_keys::MapKeyShape`]) and this
1645/// function emits the matching expression.
1646fn map_key_datatype(
1647    s: &mut String,
1648    exporter: &Exporter,
1649    format: Option<&dyn Format>,
1650    types: &Types,
1651    key_ty: &DataType,
1652    shape: map_keys::MapKeyShape,
1653    location: Vec<Cow<'static, str>>,
1654    parent_name: Option<&str>,
1655    prefix: &str,
1656    generics: &[(GenericReference, DataType)],
1657) -> Result<(), Error> {
1658    match shape {
1659        // serde_json writes integer map keys as JSON strings, and a lossless
1660        // `BigInt` key would otherwise render as the value-shaped `bigint`.
1661        map_keys::MapKeyShape::String => s.push_str(STRING),
1662        // `number | null` is not assignable to `PropertyKey`; a key is always
1663        // a finite number (`NaN`/`Infinity` are not representable in JSON).
1664        map_keys::MapKeyShape::Number => s.push_str("number"),
1665        // A type parameter is not constrained to `PropertyKey` at its
1666        // declaration, so constrain it locally to keep the mapped type valid.
1667        map_keys::MapKeyShape::TypeParameter => {
1668            map_key_expression(
1669                s,
1670                exporter,
1671                format,
1672                types,
1673                key_ty,
1674                location,
1675                parent_name,
1676                prefix,
1677                generics,
1678            )?;
1679            s.push_str(" & PropertyKey");
1680        }
1681        map_keys::MapKeyShape::Property => map_key_expression(
1682            s,
1683            exporter,
1684            format,
1685            types,
1686            key_ty,
1687            location,
1688            parent_name,
1689            prefix,
1690            generics,
1691        )?,
1692    }
1693
1694    Ok(())
1695}
1696
1697/// Renders a map key whose shape is already a valid `PropertyKey` (or a type
1698/// parameter to be constrained by the caller).
1699fn map_key_expression(
1700    s: &mut String,
1701    exporter: &Exporter,
1702    format: Option<&dyn Format>,
1703    types: &Types,
1704    key_ty: &DataType,
1705    location: Vec<Cow<'static, str>>,
1706    parent_name: Option<&str>,
1707    prefix: &str,
1708    generics: &[(GenericReference, DataType)],
1709) -> Result<(), Error> {
1710    match key_ty {
1711        DataType::Reference(r) => {
1712            reference_dt(s, exporter, format, types, r, location, prefix, generics)
1713        }
1714        key_ty => shallow_inline_datatype(
1715            s,
1716            exporter,
1717            format,
1718            types,
1719            key_ty,
1720            location,
1721            parent_name,
1722            prefix,
1723            generics,
1724        ),
1725    }
1726}
1727
1728fn map_dt(
1729    s: &mut String,
1730    exporter: &Exporter,
1731    format: Option<&dyn Format>,
1732    types: &Types,
1733    m: &Map,
1734    location: Vec<Cow<'static, str>>,
1735    generics: &[(GenericReference, DataType)],
1736) -> Result<(), Error> {
1737    render_map(
1738        s,
1739        exporter,
1740        format,
1741        types,
1742        m,
1743        location,
1744        None,
1745        "",
1746        generics,
1747        RenderMode::Normal,
1748    )
1749}
1750
1751fn map_key_path(location: &[Cow<'static, str>]) -> String {
1752    if location.is_empty() {
1753        return "HashMap".to_string();
1754    }
1755
1756    location.join(".")
1757}
1758
1759fn map_key_render_type(dt: DataType) -> DataType {
1760    if matches!(dt, DataType::Primitive(Primitive::bool)) {
1761        return bool_key_literal_datatype();
1762    }
1763
1764    dt
1765}
1766
1767fn bool_key_literal_datatype() -> DataType {
1768    let mut bool_enum = Enum::default();
1769    bool_enum
1770        .variants
1771        .push((Cow::Borrowed("true"), Variant::unit()));
1772    bool_enum
1773        .variants
1774        .push((Cow::Borrowed("false"), Variant::unit()));
1775    DataType::Enum(bool_enum)
1776}
1777
1778fn unnamed_fields_datatype(
1779    s: &mut String,
1780    exporter: &Exporter,
1781    format: Option<&dyn Format>,
1782    types: &Types,
1783    fields: &[(&Field, &DataType)],
1784    declared_len: usize,
1785    location: Vec<Cow<'static, str>>,
1786    parent_name: Option<&str>,
1787    prefix: &str,
1788    generics: &[(GenericReference, DataType)],
1789    force_inline: bool,
1790) -> Result<(), Error> {
1791    match fields {
1792        // Only a genuine newtype (declared arity 1) renders as its bare
1793        // inner type. A declared-multi-field tuple reduced to one live
1794        // element by skips stays a sequence on the wire, so it keeps the
1795        // array form below.
1796        [(field, ty)] if declared_len == 1 => {
1797            let mut v = String::new();
1798            datatype_with_inline_attr(
1799                &mut v,
1800                exporter,
1801                format,
1802                types,
1803                ty,
1804                location,
1805                parent_name,
1806                "",
1807                generics,
1808                force_inline,
1809            )?;
1810            s.push_str(&inner_comments(
1811                field.deprecated.as_ref(),
1812                &field.docs,
1813                v,
1814                true,
1815                prefix,
1816            ));
1817        }
1818        fields => {
1819            let optional_from = trailing_optional_run(fields.iter().map(|(field, _)| *field));
1820
1821            s.push('[');
1822            for (i, (field, ty)) in fields.iter().enumerate() {
1823                if i != 0 {
1824                    s.push_str(", ");
1825                }
1826
1827                let mut v = String::new();
1828                let mut field_location = location.clone();
1829                field_location.push(i.to_string().into());
1830                datatype_with_inline_attr(
1831                    &mut v,
1832                    exporter,
1833                    format,
1834                    types,
1835                    ty,
1836                    field_location,
1837                    parent_name,
1838                    "",
1839                    generics,
1840                    force_inline,
1841                )?;
1842                if i >= optional_from {
1843                    if optional_element_needs_parens(ty) {
1844                        v = format!("({v})");
1845                    }
1846                    v.push('?');
1847                }
1848                s.push_str(&inner_comments(
1849                    field.deprecated.as_ref(),
1850                    &field.docs,
1851                    v,
1852                    true,
1853                    prefix,
1854                ));
1855            }
1856            s.push(']');
1857        }
1858    }
1859
1860    Ok(())
1861}
1862
1863/// The start index of the maximal all-optional TRAILING run of tuple
1864/// elements, or `fields.len()` when the last element isn't optional.
1865///
1866/// TypeScript only allows optional tuple elements at the end, so a
1867/// non-trailing `optional` flag is ignored (rendered required, the safe
1868/// wider-input direction). serde can't produce one anyway: `#[serde(default)]`
1869/// on an unnamed field requires every later field to be defaulted too, so
1870/// optional elements always form a suffix.
1871fn trailing_optional_run<'a>(fields: impl Iterator<Item = &'a Field>) -> usize {
1872    let mut run_start = 0;
1873    for (idx, field) in fields.enumerate() {
1874        if !field.optional {
1875            run_start = idx + 1;
1876        }
1877    }
1878    run_start
1879}
1880
1881/// Whether an optional tuple element's type must be parenthesized before the
1882/// trailing `?` marker: `[number, (number | null)?]` is valid TypeScript
1883/// while `[number, number | null?]` is not, and likewise for intersections.
1884fn optional_element_needs_parens(ty: &DataType) -> bool {
1885    match ty {
1886        // Floats render as `number | null`, which cannot take a trailing `?`.
1887        DataType::Primitive(p) => primitive_is_union(p),
1888        DataType::Nullable(_) | DataType::Enum(_) | DataType::Intersection(_) => true,
1889        DataType::Reference(Reference::Named(reference)) => match &reference.inner {
1890            NamedReferenceType::Inline { dt, .. } => optional_element_needs_parens(dt),
1891            _ => false,
1892        },
1893        // `Branded` renders `<payload> & { readonly __brand: ... }` and `Define`
1894        // renders arbitrary caller-supplied text; both need parentheses before
1895        // the trailing `?`, matching [`intersection_operand_is_atomic`].
1896        DataType::Reference(Reference::Opaque(r)) => {
1897            r.downcast_ref::<Branded>().is_some() || r.downcast_ref::<opaque::Define>().is_some()
1898        }
1899        // A lone live unnamed field renders as its bare inner type.
1900        DataType::Struct(strct) => match &strct.fields {
1901            Fields::Unnamed(unnamed) if unnamed.fields.len() == 1 => unnamed
1902                .fields
1903                .first()
1904                .and_then(|field| field.ty.as_ref())
1905                .is_some_and(optional_element_needs_parens),
1906            _ => false,
1907        },
1908        _ => false,
1909    }
1910}
1911
1912fn struct_dt(
1913    s: &mut String,
1914    exporter: &Exporter,
1915    format: Option<&dyn Format>,
1916    types: &Types,
1917    st: &Struct,
1918    location: Vec<Cow<'static, str>>,
1919    parent_name: Option<&str>,
1920    prefix: &str,
1921    generics: &[(GenericReference, DataType)],
1922) -> Result<(), Error> {
1923    match &st.fields {
1924        Fields::Unit => s.push_str(NULL),
1925        Fields::Unnamed(unnamed) => unnamed_fields_datatype(
1926            s,
1927            exporter,
1928            format,
1929            types,
1930            &unnamed
1931                .fields
1932                .iter()
1933                .filter_map(|field| field.ty.as_ref().map(|ty| (field, ty)))
1934                .collect::<Vec<_>>(),
1935            unnamed.fields.len(),
1936            location,
1937            parent_name,
1938            prefix,
1939            generics,
1940            false,
1941        )?,
1942        Fields::Named(named) => {
1943            let fields = named
1944                .fields
1945                .iter()
1946                .filter_map(|(name, field)| field.ty.as_ref().map(|ty| (name, (field, ty))))
1947                .collect::<Vec<_>>();
1948
1949            if fields.is_empty() {
1950                s.push_str("Record<string, never>");
1951                return Ok(());
1952            }
1953
1954            let mut unflattened_fields = Vec::with_capacity(fields.len());
1955            for (key, (field, ty)) in fields {
1956                let field_prefix = format!("{prefix}\t");
1957                let mut other = String::new();
1958                let mut field_location = location.clone();
1959                field_location.push(key.clone());
1960                object_field_to_ts(
1961                    &mut other,
1962                    exporter,
1963                    format,
1964                    types,
1965                    key.clone(),
1966                    (field, ty),
1967                    field_location,
1968                    parent_name,
1969                    generics,
1970                    &field_prefix,
1971                    false,
1972                    None,
1973                )?;
1974
1975                unflattened_fields.push(inner_comments(
1976                    field.deprecated.as_ref(),
1977                    &field.docs,
1978                    other,
1979                    false,
1980                    &field_prefix,
1981                ));
1982            }
1983
1984            s.push('{');
1985            for field in unflattened_fields {
1986                s.push('\n');
1987                s.push_str(&field);
1988                s.push(',');
1989            }
1990            s.push('\n');
1991            s.push_str(prefix);
1992            s.push('}');
1993        }
1994    }
1995
1996    Ok(())
1997}
1998
1999fn object_field_to_ts(
2000    s: &mut String,
2001    exporter: &Exporter,
2002    format: Option<&dyn Format>,
2003    types: &Types,
2004    key: Cow<'static, str>,
2005    (field, ty): (&Field, &DataType),
2006    location: Vec<Cow<'static, str>>,
2007    parent_name: Option<&str>,
2008    generics: &[(GenericReference, DataType)],
2009    prefix: &str,
2010    force_inline: bool,
2011    ty_override: Option<&str>,
2012) -> Result<(), Error> {
2013    let field_name_safe = sanitise_key(key, false);
2014    let key = if field.optional {
2015        format!("{field_name_safe}?").into()
2016    } else {
2017        field_name_safe
2018    };
2019
2020    let value = match ty_override {
2021        Some(ty_override) => ty_override.to_string(),
2022        None => {
2023            let mut value = String::new();
2024            datatype_with_inline_attr(
2025                &mut value,
2026                exporter,
2027                format,
2028                types,
2029                ty,
2030                location,
2031                parent_name,
2032                prefix,
2033                generics,
2034                force_inline,
2035            )?;
2036            value
2037        }
2038    };
2039
2040    s.push_str(prefix);
2041    s.push_str(&key);
2042    s.push_str(": ");
2043    s.push_str(&value);
2044
2045    Ok(())
2046}
2047
2048struct EnumVariantOutput {
2049    value: String,
2050    strict_keys: Option<BTreeSet<String>>,
2051}
2052
2053#[derive(Debug, Clone)]
2054struct DiscriminatorAnalysis {
2055    key: String,
2056    known_literals: Vec<String>,
2057    fallback_variant_idx: Option<usize>,
2058}
2059
2060#[derive(Debug, Clone, Copy)]
2061struct VariantTypeOverride<'a> {
2062    key: &'a str,
2063    ty: &'a str,
2064}
2065
2066#[derive(Debug, Clone)]
2067enum DiscriminatorValue {
2068    StringLiteral(String),
2069    String,
2070}
2071
2072fn analyze_discriminator(
2073    variants: &[&(Cow<'static, str>, Variant)],
2074) -> Option<DiscriminatorAnalysis> {
2075    if variants.iter().any(|(name, _)| name.is_empty()) {
2076        return None;
2077    }
2078
2079    let mut key = None::<String>;
2080    let mut known_literals = BTreeSet::new();
2081    let mut fallback_variant_idx = None;
2082
2083    for (idx, (_, variant)) in variants.iter().enumerate() {
2084        let (variant_key, value) = variant_discriminator(variant)?;
2085
2086        if let Some(expected) = &key {
2087            if expected != &variant_key {
2088                return None;
2089            }
2090        } else {
2091            key = Some(variant_key.clone());
2092        }
2093
2094        match value {
2095            DiscriminatorValue::StringLiteral(value) => {
2096                known_literals.insert(value);
2097            }
2098            DiscriminatorValue::String => {
2099                if fallback_variant_idx.replace(idx).is_some() {
2100                    return None;
2101                }
2102            }
2103        }
2104    }
2105
2106    if known_literals.is_empty() {
2107        return None;
2108    }
2109
2110    Some(DiscriminatorAnalysis {
2111        key: key?,
2112        known_literals: known_literals.into_iter().collect(),
2113        fallback_variant_idx,
2114    })
2115}
2116
2117fn variant_discriminator(variant: &Variant) -> Option<(String, DiscriminatorValue)> {
2118    let Fields::Named(named) = &variant.fields else {
2119        return None;
2120    };
2121
2122    let (name, field) = named.fields.iter().find(|(_, field)| !field.optional)?;
2123    let ty = field.ty.as_ref()?;
2124
2125    if matches!(ty, DataType::Primitive(Primitive::str)) {
2126        return Some((name.to_string(), DiscriminatorValue::String));
2127    }
2128
2129    string_literal_datatype_value(ty)
2130        .map(|value| (name.to_string(), DiscriminatorValue::StringLiteral(value)))
2131}
2132
2133fn string_literal_datatype_value(ty: &DataType) -> Option<String> {
2134    let DataType::Enum(enm) = ty else {
2135        return None;
2136    };
2137
2138    let mut variants = enm.variants.iter();
2139    let (name, variant) = variants.next()?;
2140    if variants.next().is_some() || !matches!(&variant.fields, Fields::Unit) {
2141        return None;
2142    }
2143
2144    Some(name.to_string())
2145}
2146
2147fn exclude_known_literals_type(literals: &[String]) -> Option<String> {
2148    if literals.is_empty() {
2149        return None;
2150    }
2151
2152    let known = literals
2153        .iter()
2154        .map(|value| format!("\"{}\"", escape_typescript_string_literal(value.as_str())))
2155        .collect::<Vec<_>>()
2156        .join(" | ");
2157
2158    Some(format!("Exclude<string, {known}>"))
2159}
2160
2161fn fallback_discriminator_override(
2162    discriminator: Option<&DiscriminatorAnalysis>,
2163) -> Option<(usize, &str, String)> {
2164    let discriminator = discriminator?;
2165    discriminator.fallback_variant_idx.and_then(|idx| {
2166        exclude_known_literals_type(&discriminator.known_literals)
2167            .map(|ty| (idx, discriminator.key.as_str(), ty))
2168    })
2169}
2170
2171fn untagged_strict_keys(variant: &Variant) -> Option<BTreeSet<String>> {
2172    match &variant.fields {
2173        Fields::Named(obj) => Some(
2174            obj.fields
2175                .iter()
2176                .filter_map(|(name, field)| {
2177                    field
2178                        .ty
2179                        .as_ref()
2180                        .map(|_| sanitise_key(name.clone(), false).to_string())
2181                })
2182                .collect(),
2183        ),
2184        _ => None,
2185    }
2186}
2187
2188fn has_anonymous_variant(variants: &[&(Cow<'static, str>, Variant)]) -> bool {
2189    variants.iter().any(|(name, _)| name.is_empty())
2190}
2191
2192fn active_variants(e: &Enum) -> Vec<&(Cow<'static, str>, Variant)> {
2193    e.variants
2194        .iter()
2195        .filter(|(_, variant)| !variant.skip)
2196        .collect()
2197}
2198
2199fn strictify_enum_variants(variants: &mut [EnumVariantOutput]) {
2200    let strict_key_universe = variants
2201        .iter()
2202        .filter_map(|variant| variant.strict_keys.as_ref())
2203        .flat_map(|keys| keys.iter().cloned())
2204        .collect::<BTreeSet<_>>();
2205
2206    if strict_key_universe.len() < 2 {
2207        return;
2208    }
2209
2210    for variant in variants {
2211        let Some(keys) = variant.strict_keys.as_ref() else {
2212            continue;
2213        };
2214
2215        let missing_keys = strict_key_universe
2216            .iter()
2217            .filter(|key| !keys.contains(*key))
2218            .map(|key| format!("{key}?: {NEVER}"))
2219            .collect::<Vec<_>>();
2220
2221        if !missing_keys.is_empty() {
2222            variant.value = format!("({}) & {{ {} }}", variant.value, missing_keys.join("; "));
2223        }
2224    }
2225}
2226
2227fn push_union(s: &mut String, variants: Vec<String>) {
2228    let mut seen = BTreeSet::new();
2229    let variants = variants
2230        .into_iter()
2231        .filter(|variant| seen.insert(variant.clone()))
2232        .collect::<Vec<_>>();
2233
2234    if variants.is_empty() {
2235        s.push_str(NEVER);
2236    } else {
2237        s.push_str(&variants.join(" | "));
2238    }
2239}
2240
2241fn enum_variant_datatype(
2242    exporter: &Exporter,
2243    format: Option<&dyn Format>,
2244    types: &Types,
2245    name: Cow<'static, str>,
2246    variant: &Variant,
2247    location: Vec<Cow<'static, str>>,
2248    prefix: &str,
2249    generics: &[(GenericReference, DataType)],
2250    ty_override: Option<VariantTypeOverride<'_>>,
2251) -> Result<Option<String>, Error> {
2252    match &variant.fields {
2253        // An empty name is a legitimate wire value: `#[serde(rename = "")]`
2254        // serializes a unit variant as the empty string, which renders as the
2255        // `""` literal. The diagnostic is kept for the anonymous named-field
2256        // shape, which has no tag to render.
2257        Fields::Unit => Ok(Some(sanitise_key(name, true).to_string())),
2258        Fields::Named(_) if name.is_empty() => Err(Error::unsupported_anonymous_enum_variant(
2259            path_string(&location),
2260            "named-field",
2261        )),
2262        Fields::Named(obj) => {
2263            let mut regular_fields = Vec::new();
2264            for (field_name, field) in &obj.fields {
2265                let Some(ty) = field.ty.as_ref() else {
2266                    continue;
2267                };
2268
2269                let mut other = String::new();
2270                let mut field_location = location.clone();
2271                if field_location
2272                    .last()
2273                    .is_some_and(|location| location == field_name)
2274                {
2275                    if !matches!(ty, DataType::Struct(_)) {
2276                        field_location.push("0".into());
2277                    }
2278                } else {
2279                    field_location.push(field_name.clone());
2280                }
2281                object_field_to_ts(
2282                    &mut other,
2283                    exporter,
2284                    format,
2285                    types,
2286                    field_name.clone(),
2287                    (field, ty),
2288                    field_location,
2289                    None,
2290                    generics,
2291                    "",
2292                    false,
2293                    ty_override
2294                        .as_ref()
2295                        .filter(|override_ty| override_ty.key == field_name.as_ref())
2296                        .map(|override_ty| override_ty.ty),
2297                )?;
2298
2299                regular_fields.push(inner_comments(
2300                    field.deprecated.as_ref(),
2301                    &field.docs,
2302                    other,
2303                    true,
2304                    prefix,
2305                ));
2306            }
2307
2308            Ok(Some(if regular_fields.is_empty() {
2309                format!("Record<{STRING}, {NEVER}>")
2310            } else {
2311                format!("{{ {} }}", regular_fields.join("; "))
2312            }))
2313        }
2314        Fields::Unnamed(obj) => {
2315            let live_fields = obj
2316                .fields
2317                .iter()
2318                .filter_map(|field| field.ty.as_ref().map(|ty| (field, ty)))
2319                .collect::<Vec<_>>();
2320            // A newtype payload renders bare, with no tuple position for an
2321            // optional marker to attach to.
2322            let is_newtype = obj.fields.len() == 1;
2323            let optional_from = if is_newtype {
2324                live_fields.len()
2325            } else {
2326                trailing_optional_run(live_fields.iter().map(|(field, _)| *field))
2327            };
2328
2329            let fields = live_fields
2330                .iter()
2331                .enumerate()
2332                .map(|(idx, (_, ty))| {
2333                    let mut out = String::new();
2334                    let mut field_location = location.clone();
2335                    field_location.push(idx.to_string().into());
2336                    datatype_with_inline_attr(
2337                        &mut out,
2338                        exporter,
2339                        format,
2340                        types,
2341                        ty,
2342                        field_location,
2343                        None,
2344                        "",
2345                        generics,
2346                        false,
2347                    )?;
2348                    if idx >= optional_from {
2349                        if optional_element_needs_parens(ty) {
2350                            out = format!("({out})");
2351                        }
2352                        out.push('?');
2353                    }
2354                    Ok(out)
2355                })
2356                .collect::<Result<Vec<_>, Error>>()?;
2357
2358            Ok(match &fields[..] {
2359                [] if obj.fields.is_empty() => Some("[]".to_string()),
2360                [] => None,
2361                [field] if is_newtype => Some(field.to_string()),
2362                fields => Some(format!("[{}]", fields.join(", "))),
2363            })
2364        }
2365    }
2366}
2367
2368/// Identity used to detect Serde `#[serde(untagged)]` alias cycles among
2369/// named exports (see [`collapse_untagged_alias_cycle`]). Two named types
2370/// are treated as "the same" if they share a Rust path, mirroring the
2371/// identity `rust_type_path` already uses for name-collision detection
2372/// elsewhere in this module.
2373///
2374/// Generic arguments are deliberately ignored: TypeScript's alias-cycle
2375/// check (TS2456) is declaration-level, so `GenP<T>` referencing `GenQ<T>`
2376/// referencing `GenP<U>` back is a cycle no matter how the parameters are
2377/// instantiated along the way.
2378type AliasId = (Cow<'static, str>, Cow<'static, str>);
2379
2380fn alias_id(ndt: &NamedDataType) -> AliasId {
2381    (ndt.module_path.clone(), ndt.name.clone())
2382}
2383
2384/// Substitution from a cycle member's generic parameter names to the
2385/// datatypes they are instantiated with along some path from the exported
2386/// root type: either the root's own parameters (`GenQ<U>` in a cycle with
2387/// `GenP<T>` says `U` where `GenP`'s body must say `T`) or concrete types
2388/// (`Root -> Gen<String> -> Root` instantiates `Gen`'s `T` at `string`).
2389/// Applying it to a member's variants lets them merge into the root's body
2390/// without dangling parameters.
2391type GenericSubst = HashMap<Cow<'static, str>, DataType>;
2392
2393/// An alias-transparent hop from one named export to another: a position
2394/// whose TypeScript rendering is the *bare* referenced name (possibly
2395/// `| null`), with no `{}`/`[]`/tuple wrapper deferring alias resolution
2396/// around it.
2397///
2398/// This is exactly the shape that makes TypeScript's alias resolution
2399/// eager: `type X = Y` requires resolving `Y` immediately, so a cycle
2400/// through only this shape of hop is what produces the illegal
2401/// `type X = X | ...` (TS2456), whereas a cycle through `{ field: X }`,
2402/// `X[]`, or `[X]` does not, because object/array/tuple types defer
2403/// resolution.
2404struct TransparentHop<'t, 'r> {
2405    target: &'t NamedDataType,
2406    /// The reference itself, kept so the collapse can resolve the hop's
2407    /// generic arguments (including omitted ones) with the same
2408    /// [`resolved_reference_generics`] logic ordinary rendering uses.
2409    reference: &'r NamedReference,
2410    /// Whether the hop passes through [`DataType::Nullable`], rendering as
2411    /// `Target | null`. A union member is still resolved eagerly, so this is
2412    /// just as much a cycle - but dropping such a back edge must keep the
2413    /// `null` branch, because an `Option` chain bottoms out at `None`.
2414    nullable: bool,
2415}
2416
2417/// Returns the alias-transparent hop `dt` renders as, if any: a bare
2418/// [`Reference::Named`], optionally wrapped in [`DataType::Nullable`]
2419/// (which renders as `| null` - still an eagerly-resolved position).
2420///
2421/// The hop's target borrows from `types` while the reference borrows from
2422/// `dt`, so a hop derived from a temporary (substituted) datatype still
2423/// yields a long-lived target.
2424fn transparent_reference<'t, 'r>(
2425    types: &'t Types,
2426    dt: &'r DataType,
2427) -> Option<TransparentHop<'t, 'r>> {
2428    match dt {
2429        DataType::Reference(Reference::Named(r)) => match &r.inner {
2430            NamedReferenceType::Reference { .. } => Some(TransparentHop {
2431                target: types.get(r)?,
2432                reference: r,
2433                nullable: false,
2434            }),
2435            _ => None,
2436        },
2437        DataType::Nullable(inner) => Some(TransparentHop {
2438            nullable: true,
2439            ..transparent_reference(types, inner)?
2440        }),
2441        _ => None,
2442    }
2443}
2444
2445/// If `variant`'s rendering is exactly a transparent hop - the shape a
2446/// `#[serde(untagged)]` newtype variant takes, since serde adds no wire
2447/// structure around it - returns that hop.
2448///
2449/// The variant must have exactly one field *total*, mirroring the
2450/// `obj.fields.len() == 1` bare-rendering rule in [`enum_variant_datatype`]:
2451/// a skipped extra field makes the renderer emit a `[T]` one-tuple
2452/// (matching serde's one-element seq), which is a deferred position and
2453/// therefore not transparent.
2454fn transparent_variant_hop<'t, 'r>(
2455    types: &'t Types,
2456    variant: &'r Variant,
2457) -> Option<TransparentHop<'t, 'r>> {
2458    let Fields::Unnamed(unnamed) = &variant.fields else {
2459        return None;
2460    };
2461    let [field] = unnamed.fields.as_slice() else {
2462        return None;
2463    };
2464    transparent_reference(types, field.ty.as_ref()?)
2465}
2466
2467/// Returns the alias-transparent *position* of a named export whose own
2468/// body renders as a single bare datatype - a plain alias body (e.g. what
2469/// `#[serde(transparent)]` rewrites to) or a newtype tuple struct, both
2470/// exported as `export type W = <position>;`. Such exports continue an
2471/// alias cycle without contributing union members of their own.
2472///
2473/// Unlike enum variants, [`struct_dt`] pre-filters skipped fields, so a
2474/// struct renders bare whenever exactly one *live* field remains.
2475fn transparent_export_position(ndt: &NamedDataType) -> Option<&DataType> {
2476    match ndt.ty.as_ref()? {
2477        DataType::Struct(s) => {
2478            let Fields::Unnamed(unnamed) = &s.fields else {
2479                return None;
2480            };
2481            let mut live = unnamed.fields.iter().filter_map(|field| field.ty.as_ref());
2482            let ty = live.next()?;
2483            if live.next().is_some() {
2484                return None;
2485            }
2486            Some(ty)
2487        }
2488        // An enum body contributes hops through its variants instead.
2489        DataType::Enum(_) => None,
2490        dt => Some(dt),
2491    }
2492}
2493
2494/// The transparent hop of a passthrough export's body, if any (see
2495/// [`transparent_export_position`]).
2496fn transparent_export_hop<'t, 'r>(
2497    types: &'t Types,
2498    ndt: &'r NamedDataType,
2499) -> Option<TransparentHop<'t, 'r>> {
2500    transparent_reference(types, transparent_export_position(ndt)?)
2501}
2502
2503/// A named export participating in the alias-transparent reference graph.
2504struct AliasNode<'a> {
2505    ndt: &'a NamedDataType,
2506    /// Every distinct generic instantiation this node is reached with from
2507    /// the root, in deterministic discovery order. A node can have several -
2508    /// e.g. `Gen<T>` reached both as itself (the root, identity) and as
2509    /// `Gen<String>` through the cycle - and its variants merge into the
2510    /// root's body once per instantiation.
2511    substs: Vec<GenericSubst>,
2512    /// Targets of this node's outgoing alias-transparent hops, used to
2513    /// compute cycle membership. The hops themselves are re-derived (and
2514    /// re-classified post-substitution) during the merge walk.
2515    edges: Vec<AliasId>,
2516}
2517
2518/// Divergence guards for [`collapse_untagged_alias_cycle`]'s instantiation
2519/// walk (see [`enqueue_cycle_instantiation`]). The instantiation set is
2520/// infinite only when the cycle grows its own type arguments
2521/// (`Gen<T> -> Gen<Vec<T>>`) - a shape serde itself cannot serialize (it
2522/// would need infinite monomorphization) but dynamically built [`Types`]
2523/// can express - so two generous caps turn divergence into an error
2524/// instead of a hang: one on *distinct* instantiations per node (breadth -
2525/// many small instantiations), and a much smaller one on the structural
2526/// size of a single instantiation (growth - it stops both linearly-growing
2527/// arguments after a few hundred trips and exponentially-growing ones like
2528/// `Gen<T> -> Gen<(T, T)>` long before they exhaust memory; no realistic
2529/// single type argument is 256 nodes deep/wide).
2530const MAX_SUBSTS_PER_NODE: usize = 1024;
2531const MAX_SUBST_WEIGHT: usize = 256;
2532
2533/// Adds a (cycle member, instantiation) pair to the collapse's merge work
2534/// list unless that exact pair was already processed, enforcing the
2535/// divergence guards above. Only genuinely new pairs enter the list, which
2536/// is what makes the walk a terminating fixed-point iteration.
2537fn enqueue_cycle_instantiation(
2538    nodes: &mut HashMap<AliasId, AliasNode<'_>>,
2539    work: &mut Vec<(AliasId, GenericSubst)>,
2540    target_id: AliasId,
2541    subst: GenericSubst,
2542) -> Result<(), Cow<'static, str>> {
2543    let node = nodes
2544        .get_mut(&target_id)
2545        .expect("cycle members were discovered in phase 1");
2546    if node.substs.contains(&subst) {
2547        return Ok(());
2548    }
2549    if node.substs.len() >= MAX_SUBSTS_PER_NODE {
2550        return Err(Cow::Borrowed(
2551            "the cycle's generic parameter instantiations do not converge (a single type is instantiated with an unbounded number of distinct arguments)",
2552        ));
2553    }
2554    if subst.values().map(datatype_weight).sum::<usize>() > MAX_SUBST_WEIGHT {
2555        return Err(Cow::Borrowed(
2556            "the cycle's generic parameter instantiations do not converge (a type argument keeps growing with every trip around the cycle)",
2557        ));
2558    }
2559    node.substs.push(subst.clone());
2560    work.push((target_id, subst));
2561    Ok(())
2562}
2563
2564fn node_enum(ndt: &NamedDataType) -> Option<&Enum> {
2565    match ndt.ty.as_ref() {
2566        Some(DataType::Enum(e)) => Some(e),
2567        _ => None,
2568    }
2569}
2570
2571/// The *effective* transparent hop of a position under an instantiation:
2572/// where its rendering ends up once generic parameters are taken into
2573/// account, which is how TypeScript's eager alias resolution sees it.
2574struct EffectiveHop<'t> {
2575    target: &'t NamedDataType,
2576    /// The full substitution the hop applies to its target, resolved via
2577    /// [`edge_substitution`].
2578    target_subst: GenericSubst,
2579    nullable: bool,
2580}
2581
2582/// Computes the effective transparent hop of an enum variant under `subst`,
2583/// along with the substituted variant to merge if the hop is not taken:
2584///
2585/// - A *raw* hop's target is fixed regardless of substitution; its
2586///   arguments resolve under `subst`.
2587/// - Otherwise the *substituted* form can reveal a hop that only exists
2588///   under this instantiation - `B(T)` with `T = Root` (or
2589///   `T = Gen<String>`). A revealed reference's arguments are already in
2590///   the root's scope, so they resolve under `identity`.
2591fn effective_variant_hop<'t>(
2592    types: &'t Types,
2593    variant: &Variant,
2594    subst: &GenericSubst,
2595    identity: &GenericSubst,
2596) -> Result<(Variant, Option<EffectiveHop<'t>>), Cow<'static, str>> {
2597    let raw_hop = transparent_variant_hop(types, variant);
2598
2599    let mut variant = variant.clone();
2600    substitute_fields_generics(&mut variant.fields, subst)?;
2601
2602    if let Some(hop) = raw_hop {
2603        let target_subst = edge_substitution(subst, hop.target, hop.reference)?;
2604        let hop = EffectiveHop {
2605            target: hop.target,
2606            target_subst,
2607            nullable: hop.nullable,
2608        };
2609        return Ok((variant, Some(hop)));
2610    }
2611
2612    let hop = match transparent_variant_hop(types, &variant) {
2613        Some(hop) => Some(EffectiveHop {
2614            target: hop.target,
2615            target_subst: edge_substitution(identity, hop.target, hop.reference)?,
2616            nullable: hop.nullable,
2617        }),
2618        None => None,
2619    };
2620    Ok((variant, hop))
2621}
2622
2623/// The passthrough-export analogue of [`effective_variant_hop`]: the
2624/// effective hop of the export's body position under `subst`, along with
2625/// the substituted position itself (a passthrough member whose effective
2626/// body is *not* a cycle hop contributes it as a terminal).
2627fn effective_export_hop<'t>(
2628    types: &'t Types,
2629    ndt: &NamedDataType,
2630    subst: &GenericSubst,
2631    identity: &GenericSubst,
2632) -> Result<Option<(DataType, Option<EffectiveHop<'t>>)>, Cow<'static, str>> {
2633    let Some(position) = transparent_export_position(ndt) else {
2634        return Ok(None);
2635    };
2636    let raw_hop = transparent_reference(types, position);
2637
2638    let mut position = position.clone();
2639    substitute_generics(&mut position, subst)?;
2640
2641    if let Some(hop) = raw_hop {
2642        let target_subst = edge_substitution(subst, hop.target, hop.reference)?;
2643        let hop = EffectiveHop {
2644            target: hop.target,
2645            target_subst,
2646            nullable: hop.nullable,
2647        };
2648        return Ok(Some((position, Some(hop))));
2649    }
2650
2651    let hop = match transparent_reference(types, &position) {
2652        Some(hop) => Some(EffectiveHop {
2653            target: hop.target,
2654            target_subst: edge_substitution(identity, hop.target, hop.reference)?,
2655            nullable: hop.nullable,
2656        }),
2657        None => None,
2658    };
2659    Ok(Some((position, hop)))
2660}
2661
2662/// Resolves the full substitution an in-cycle hop applies to its target: one
2663/// entry per *declared* parameter of the target, filled exactly the way
2664/// ordinary reference rendering fills them via
2665/// [`resolved_reference_generics`] - the explicit argument if present,
2666/// otherwise the parameter's declared default, otherwise `unknown` - so the
2667/// collapse and the renderer can never disagree about omitted parameters.
2668/// Each resolved value is then rewritten from the source node's scope into
2669/// the root's via `source_subst` (extended with the target's earlier
2670/// parameters, which declared defaults may reference).
2671fn edge_substitution(
2672    source_subst: &GenericSubst,
2673    target: &NamedDataType,
2674    reference: &NamedReference,
2675) -> Result<GenericSubst, Cow<'static, str>> {
2676    let (resolved, _, _) = resolved_reference_generics(target, reference, &[]).ok_or(
2677        Cow::Borrowed("the cycle contains a reference whose generic arguments cannot be resolved"),
2678    )?;
2679
2680    let mut scope = source_subst.clone();
2681    let mut target_subst = GenericSubst::with_capacity(resolved.len());
2682    for (generic, mut value) in target.generics.iter().zip(resolved) {
2683        substitute_generics(&mut value, &scope)?;
2684        scope.insert(generic.name.clone(), value.clone());
2685        target_subst.insert(generic.name.clone(), value);
2686    }
2687    Ok(target_subst)
2688}
2689
2690/// Whether a substitution maps every parameter to itself, i.e. applying it
2691/// is a no-op. The root's own variants merge under the identity, and only
2692/// non-identity substitutions can invalidate payloads the walk can't see
2693/// into (unknown opaque references).
2694fn subst_is_identity(subst: &GenericSubst) -> bool {
2695    subst
2696        .iter()
2697        .all(|(name, dt)| matches!(dt, DataType::Generic(g) if g.name() == name))
2698}
2699
2700/// Rewrites every generic parameter reference in `dt` (part of a cycle
2701/// member's variant being merged into the exported root type) to the
2702/// datatype the member is instantiated with, per `subst`. Errors abort the
2703/// collapse and fail the export - by this point the cycle is known to
2704/// render as illegal TypeScript (TS2456), so an honest error beats silently
2705/// emitting either that or a dangling parameter name.
2706fn substitute_generics(dt: &mut DataType, subst: &GenericSubst) -> Result<(), Cow<'static, str>> {
2707    match dt {
2708        DataType::Generic(g) => match subst.get(g.name()) {
2709            Some(replacement) => {
2710                *dt = replacement.clone();
2711                Ok(())
2712            }
2713            None => Err(Cow::Owned(format!(
2714                "the cycle references generic parameter `{}` with no instantiation for it",
2715                g.name()
2716            ))),
2717        },
2718        DataType::Primitive(_) => Ok(()),
2719        DataType::List(list) => substitute_generics(&mut list.ty, subst),
2720        DataType::Map(map) => {
2721            substitute_generics(map.key_ty_mut(), subst)?;
2722            substitute_generics(map.value_ty_mut(), subst)
2723        }
2724        DataType::Struct(s) => substitute_fields_generics(&mut s.fields, subst),
2725        DataType::Enum(e) => e
2726            .variants
2727            .iter_mut()
2728            .try_for_each(|(_, variant)| substitute_fields_generics(&mut variant.fields, subst)),
2729        DataType::Tuple(t) => t
2730            .elements
2731            .iter_mut()
2732            .try_for_each(|ty| substitute_generics(ty, subst)),
2733        DataType::Nullable(inner) => substitute_generics(inner, subst),
2734        DataType::Intersection(parts) => parts
2735            .iter_mut()
2736            .try_for_each(|ty| substitute_generics(ty, subst)),
2737        DataType::Reference(Reference::Named(r)) => match &mut r.inner {
2738            NamedReferenceType::Reference { generics, .. } => generics
2739                .iter_mut()
2740                .try_for_each(|(_, dt)| substitute_generics(dt, subst)),
2741            NamedReferenceType::Inline { dt, .. } => substitute_generics(dt, subst),
2742            NamedReferenceType::Recursive(_) => Ok(()),
2743        },
2744        DataType::Reference(Reference::Opaque(opaque_ref)) => {
2745            if let Some(branded) = opaque_ref.downcast_ref::<Branded>() {
2746                // A branded payload can embed generic parameters
2747                // (`branded!(struct Id<T>(T))` renders as `T & { ... }`),
2748                // so it has to be rewritten like any other datatype.
2749                let mut ty = branded.ty().clone();
2750                let brand = branded.brand().clone();
2751                substitute_generics(&mut ty, subst)?;
2752                *dt = DataType::Reference(Reference::opaque(Branded::new(brand, ty)));
2753                Ok(())
2754            } else if subst_is_identity(subst) {
2755                // Identity substitutions are no-ops: nothing is being
2756                // rewritten, so no payload can be invalidated.
2757                Ok(())
2758            } else if let Some(def) = opaque_ref.downcast_ref::<opaque::Define>() {
2759                // `define(...)` is raw TypeScript text: it can *name* the
2760                // member's generic parameters but cannot be structurally
2761                // rewritten (and textually rewriting raw TS would be
2762                // fragile). Allow it only when a conservative
2763                // word-boundary scan shows it mentions no parameter this
2764                // substitution actually rewrites.
2765                match subst.iter().find(|(name, replacement)| {
2766                    !matches!(replacement, DataType::Generic(g) if g.name() == *name)
2767                        && raw_ts_mentions_identifier(&def.0, name)
2768                }) {
2769                    Some((name, _)) => Err(Cow::Owned(format!(
2770                        "the cycle contains raw TypeScript (`define(...)`) that mentions generic parameter `{name}`, which cannot be rewritten"
2771                    ))),
2772                    None => Ok(()),
2773                }
2774            } else if opaque_ref.downcast_ref::<opaque::Any>().is_some()
2775                || opaque_ref.downcast_ref::<opaque::Unknown>().is_some()
2776                || opaque_ref.downcast_ref::<opaque::Never>().is_some()
2777                || opaque_ref.downcast_ref::<opaque::Number>().is_some()
2778                || opaque_ref.downcast_ref::<opaque::BigInt>().is_some()
2779            {
2780                // This crate's remaining opaque payloads can't embed a
2781                // datatype or mention a parameter at all.
2782                Ok(())
2783            } else {
2784                // An opaque reference from elsewhere might embed generic
2785                // parameters this walk can't see, let alone rewrite.
2786                Err(Cow::Owned(format!(
2787                    "the cycle contains an opaque reference (`{}`) whose payload cannot be checked for generic parameters",
2788                    opaque_ref.type_name()
2789                )))
2790            }
2791        }
2792    }
2793}
2794
2795/// Conservative check for whether raw TypeScript text (a `define(...)`
2796/// payload) mentions `name` as a standalone identifier - a word-boundary
2797/// match, so the parameter `U` is found in `ReadonlyArray<U>` but not in
2798/// `Unit`. Any hit means the raw text may depend on a generic parameter a
2799/// cycle merge would rewrite, which is impossible for raw text, so the
2800/// caller must reject the merge. Non-ASCII bytes are treated as identifier
2801/// characters, erring toward a match (and therefore rejection) around
2802/// exotic identifiers.
2803fn raw_ts_mentions_identifier(raw: &str, name: &str) -> bool {
2804    fn is_ident_byte(b: u8) -> bool {
2805        b.is_ascii_alphanumeric() || b == b'_' || b == b'$' || !b.is_ascii()
2806    }
2807
2808    if name.is_empty() {
2809        return false;
2810    }
2811    let bytes = raw.as_bytes();
2812    let mut search_start = 0;
2813    while let Some(pos) = raw[search_start..].find(name) {
2814        let start = search_start + pos;
2815        let end = start + name.len();
2816        if (start == 0 || !is_ident_byte(bytes[start - 1]))
2817            && (end == raw.len() || !is_ident_byte(bytes[end]))
2818        {
2819            return true;
2820        }
2821        // A later occurrence overlapping this one starts inside `name`, so
2822        // its preceding character is part of `name` - an identifier - and
2823        // would fail the boundary check anyway; skipping past `end` is safe
2824        // and keeps the cursor on a UTF-8 character boundary.
2825        search_start = end;
2826    }
2827    false
2828}
2829
2830/// Structural size of a datatype, used as a divergence guard for cycle
2831/// instantiations (see [`collapse_untagged_alias_cycle`] phase 3): a type
2832/// argument that grows on every trip around a cycle grows in weight, so
2833/// capping the weight bounds the walk even for exponential growth.
2834fn datatype_weight(dt: &DataType) -> usize {
2835    fn fields_weight(fields: &Fields) -> usize {
2836        match fields {
2837            Fields::Unit => 1,
2838            Fields::Unnamed(unnamed) => unnamed
2839                .fields
2840                .iter()
2841                .filter_map(|field| field.ty.as_ref())
2842                .map(datatype_weight)
2843                .sum(),
2844            Fields::Named(named) => named
2845                .fields
2846                .iter()
2847                .filter_map(|(_, field)| field.ty.as_ref())
2848                .map(datatype_weight)
2849                .sum(),
2850        }
2851    }
2852
2853    1_usize.saturating_add(match dt {
2854        DataType::Primitive(_) | DataType::Generic(_) => 0,
2855        DataType::List(list) => datatype_weight(&list.ty),
2856        DataType::Map(map) => {
2857            datatype_weight(map.key_ty()).saturating_add(datatype_weight(map.value_ty()))
2858        }
2859        DataType::Struct(s) => fields_weight(&s.fields),
2860        DataType::Enum(e) => e
2861            .variants
2862            .iter()
2863            .map(|(_, variant)| fields_weight(&variant.fields))
2864            .sum(),
2865        DataType::Tuple(t) => t.elements.iter().map(datatype_weight).sum(),
2866        DataType::Nullable(inner) => datatype_weight(inner),
2867        DataType::Intersection(parts) => parts.iter().map(datatype_weight).sum(),
2868        DataType::Reference(Reference::Named(r)) => match &r.inner {
2869            NamedReferenceType::Reference { generics, .. } => {
2870                generics.iter().map(|(_, dt)| datatype_weight(dt)).sum()
2871            }
2872            NamedReferenceType::Inline { dt, .. } => datatype_weight(dt),
2873            NamedReferenceType::Recursive(_) => 0,
2874        },
2875        DataType::Reference(Reference::Opaque(opaque_ref)) => opaque_ref
2876            .downcast_ref::<Branded>()
2877            .map(|branded| datatype_weight(branded.ty()))
2878            .unwrap_or(0),
2879    })
2880}
2881
2882fn substitute_fields_generics(
2883    fields: &mut Fields,
2884    subst: &GenericSubst,
2885) -> Result<(), Cow<'static, str>> {
2886    match fields {
2887        Fields::Unit => Ok(()),
2888        Fields::Unnamed(unnamed) => unnamed
2889            .fields
2890            .iter_mut()
2891            .filter_map(|field| field.ty.as_mut())
2892            .try_for_each(|ty| substitute_generics(ty, subst)),
2893        Fields::Named(named) => named
2894            .fields
2895            .iter_mut()
2896            .filter_map(|(_, field)| field.ty.as_mut())
2897            .try_for_each(|ty| substitute_generics(ty, subst)),
2898    }
2899}
2900
2901/// Detects whether `root` is part of an alias-transparent reference cycle -
2902/// i.e. whether naively rendering its variants would produce a TypeScript
2903/// alias that circularly references itself, directly or through other
2904/// untagged enums or passthrough exports (`type Rec = Rec | ...`, or
2905/// `type RecA = RecB | ...; type RecB = RecA | ...`).
2906///
2907/// Every transparent hop serializes as exactly its inner value, so the
2908/// wire-level value set of an enum in such a cycle is precisely the union
2909/// of the *non-cyclic* branches reachable from anywhere in the cycle (plus
2910/// `null` if any cyclic branch passes through an `Option`): any finite
2911/// value must eventually bottom out at one of them, since the recursive
2912/// branches never add wire structure of their own. Returns the merged,
2913/// cycle-free variant list to render in `root`'s place, or `Ok(None)` if
2914/// `root` isn't part of such a cycle - in which case its rendering must be
2915/// left completely untouched.
2916///
2917/// Returns an error (the human-readable reason) when a cycle exists but
2918/// cannot be collapsed. The naive rendering of such a cycle is illegal
2919/// TypeScript (TS2456), so failing the export loudly beats emitting it.
2920///
2921/// Regression test for https://github.com/specta-rs/specta/pull/517#discussion_r3584346217:
2922/// exporting `#[serde(untagged)] enum Rec { A(Box<Rec>), B(Map) }` used to
2923/// emit `export type Rec = Rec | Map;`, which `tsc` rejects.
2924fn collapse_untagged_alias_cycle(
2925    types: &Types,
2926    root: &NamedDataType,
2927) -> Result<Option<Enum>, Cow<'static, str>> {
2928    // Only enum exports assemble a union that can be collapsed. Passthrough
2929    // exports inside a cycle (see `transparent_export_hop`) keep their bare
2930    // alias body, which becomes legal once every enum in the cycle is
2931    // collapsed and the chain of aliases stops looping.
2932    if node_enum(root).is_none() {
2933        return Ok(None);
2934    }
2935    let root_id = alias_id(root);
2936
2937    let identity: GenericSubst = root
2938        .generics
2939        .iter()
2940        .map(|g| (g.name.clone(), DataType::Generic(g.reference())))
2941        .collect();
2942
2943    // Phase 1: discover the *effective* alias-transparent reference graph
2944    // reachable from `root`. Nodes are explored once per (node,
2945    // instantiation) pair (same dedup and divergence guards as the merge
2946    // walk), and hops are derived from each node's substituted form, so an
2947    // edge carried entirely by a generic argument - `Gen<Root>` where
2948    // `Gen<T>`'s only transparent branch is the bare parameter `T` - is
2949    // discovered exactly like a raw reference edge. TypeScript's alias
2950    // cycle check is declaration-level, so edges are recorded per node
2951    // (not per instantiation) for the cycle test in phase 2.
2952    //
2953    // A substitution failure here (e.g. an opaque payload the walk refuses
2954    // to touch) must not fail an export that may not be cyclic at all: the
2955    // raw hop's target is still recorded (its identity doesn't depend on
2956    // the substitution) and explored under its own identity, which keeps
2957    // raw reachability complete. If such a node does end up in a cycle,
2958    // the merge walk hits the same substitution error and fails honestly.
2959    let mut nodes: HashMap<AliasId, AliasNode<'_>> = HashMap::new();
2960    nodes.insert(
2961        root_id.clone(),
2962        AliasNode {
2963            ndt: root,
2964            substs: vec![identity.clone()],
2965            edges: Vec::new(),
2966        },
2967    );
2968
2969    let mut work: Vec<(AliasId, GenericSubst)> = vec![(root_id.clone(), identity.clone())];
2970    let mut cursor = 0;
2971    while cursor < work.len() {
2972        let (id, subst) = work[cursor].clone();
2973        cursor += 1;
2974
2975        let ndt = nodes[&id].ndt;
2976        let mut hops: Vec<(&NamedDataType, Option<GenericSubst>)> = Vec::new();
2977        match node_enum(ndt) {
2978            Some(enm) => {
2979                for (_, variant) in &enm.variants {
2980                    if variant.skip {
2981                        continue;
2982                    }
2983                    match effective_variant_hop(types, variant, &subst, &identity) {
2984                        Ok((_, Some(hop))) => hops.push((hop.target, Some(hop.target_subst))),
2985                        Ok((_, None)) => {}
2986                        Err(_) => {
2987                            if let Some(hop) = transparent_variant_hop(types, variant) {
2988                                hops.push((hop.target, None));
2989                            }
2990                        }
2991                    }
2992                }
2993            }
2994            None => match effective_export_hop(types, ndt, &subst, &identity) {
2995                Ok(Some((_, Some(hop)))) => hops.push((hop.target, Some(hop.target_subst))),
2996                Ok(_) => {}
2997                Err(_) => {
2998                    if let Some(hop) = transparent_export_hop(types, ndt) {
2999                        hops.push((hop.target, None));
3000                    }
3001                }
3002            },
3003        }
3004
3005        for (target, target_subst) in hops {
3006            let target_id = alias_id(target);
3007            if let Entry::Vacant(entry) = nodes.entry(target_id.clone()) {
3008                entry.insert(AliasNode {
3009                    ndt: target,
3010                    substs: Vec::new(),
3011                    edges: Vec::new(),
3012                });
3013            }
3014
3015            let source = nodes
3016                .get_mut(&id)
3017                .expect("node was inserted before being visited");
3018            if !source.edges.contains(&target_id) {
3019                source.edges.push(target_id.clone());
3020            }
3021
3022            // Fall back to the target's own identity when the hop's
3023            // instantiation couldn't be resolved, so its raw hops are
3024            // still explored.
3025            let target_subst = match target_subst {
3026                Some(target_subst) => target_subst,
3027                None => target
3028                    .generics
3029                    .iter()
3030                    .map(|g| (g.name.clone(), DataType::Generic(g.reference())))
3031                    .collect(),
3032            };
3033            enqueue_cycle_instantiation(&mut nodes, &mut work, target_id, target_subst)?;
3034        }
3035    }
3036
3037    // Phase 2: `root`'s strongly-connected component. Every discovered node
3038    // is reachable from `root`, so the members of `root`'s cycle are exactly
3039    // the nodes that can reach `root` back - found by walking the reversed
3040    // edges from `root`. `root` itself shows up iff some cycle through it
3041    // exists at all.
3042    let mut reverse: HashMap<&AliasId, Vec<&AliasId>> = HashMap::new();
3043    for (id, node) in &nodes {
3044        for target in &node.edges {
3045            reverse.entry(target).or_default().push(id);
3046        }
3047    }
3048    let mut in_cycle: HashSet<AliasId> = HashSet::new();
3049    let mut frontier = vec![&root_id];
3050    while let Some(id) = frontier.pop() {
3051        for &source in reverse.get(id).into_iter().flatten() {
3052            if in_cycle.insert(source.clone()) {
3053                frontier.push(source);
3054            }
3055        }
3056    }
3057    if !in_cycle.contains(&root_id) {
3058        return Ok(None);
3059    }
3060    drop(frontier);
3061    drop(reverse);
3062
3063    // Phase 3: propagate generic instantiations around the cycle to a fixed
3064    // point, starting from the root's identity, merging each (member,
3065    // instantiation) pair's non-back-edge branches as it is processed. A
3066    // member can be reached with several distinct instantiations (`Gen<T>`
3067    // as the root *and* as `Gen<String>` through the cycle); each one
3068    // contributes a copy of its branches.
3069    //
3070    // Back edges are classified on each branch's *effective* hop (see
3071    // `effective_variant_hop`): the raw hop when the branch is one, or the
3072    // hop its substituted form reveals (`B(T)` with `T = Root`, or
3073    // `T = Gen<String>` for a cycle member `Gen`). A back edge is dropped -
3074    // it adds no wire structure of its own, except a `Nullable` hop whose
3075    // `None` case is a real `null` wire value to keep - and its
3076    // instantiation is fed through this same work list, so its terminals
3077    // still merge. Discovery errors were tolerated in phase 1; here the
3078    // cycle is confirmed, so substitution failures fail the export
3079    // honestly.
3080    //
3081    // Termination: only genuinely new (node, substitution) pairs enter the
3082    // work list (see `enqueue_cycle_instantiation`), so the walk stops
3083    // exactly when the instantiation set stops growing - a finite set of
3084    // any size converges. Branches are merged in work-list order (`root`'s
3085    // own branches under the identity first), so the output is
3086    // deterministic; `push_union` dedupes identical renderings.
3087    for node in nodes.values_mut() {
3088        node.substs.clear();
3089    }
3090    let mut work: Vec<(AliasId, GenericSubst)> = vec![(root_id.clone(), identity.clone())];
3091    nodes
3092        .get_mut(&root_id)
3093        .expect("root node always exists")
3094        .substs
3095        .push(identity.clone());
3096
3097    let mut variants = Vec::new();
3098    let mut needs_null = false;
3099    let mut cursor = 0;
3100    while cursor < work.len() {
3101        let (id, subst) = work[cursor].clone();
3102        cursor += 1;
3103
3104        let ndt = nodes[&id].ndt;
3105        let Some(enm) = node_enum(ndt) else {
3106            // Passthrough member: its effective body is usually a back edge
3107            // into the cycle (contributing nothing but a possible `null`
3108            // remnant), but under some instantiations it can be a hop out
3109            // of the cycle or no hop at all (`W<T>` reached at
3110            // `T = string`), in which case the substituted body is a
3111            // terminal to keep.
3112            let Some((position, hop)) = effective_export_hop(types, ndt, &subst, &identity)? else {
3113                continue;
3114            };
3115            match hop {
3116                Some(hop) if in_cycle.contains(&alias_id(hop.target)) => {
3117                    needs_null |= hop.nullable;
3118                    enqueue_cycle_instantiation(
3119                        &mut nodes,
3120                        &mut work,
3121                        alias_id(hop.target),
3122                        hop.target_subst,
3123                    )?;
3124                }
3125                _ => variants.push((
3126                    Cow::Borrowed("passthrough"),
3127                    Variant::unnamed().field(Field::new(position)).build(),
3128                )),
3129            }
3130            continue;
3131        };
3132
3133        for (name, variant) in &enm.variants {
3134            if variant.skip {
3135                continue;
3136            }
3137
3138            let (variant, hop) = effective_variant_hop(types, variant, &subst, &identity)?;
3139            if let Some(hop) = hop
3140                && in_cycle.contains(&alias_id(hop.target))
3141            {
3142                needs_null |= hop.nullable;
3143                enqueue_cycle_instantiation(
3144                    &mut nodes,
3145                    &mut work,
3146                    alias_id(hop.target),
3147                    hop.target_subst,
3148                )?;
3149                continue;
3150            }
3151
3152            variants.push((name.clone(), variant));
3153        }
3154    }
3155
3156    if needs_null {
3157        // The same `null`-rendering empty-tuple shape `specta-serde` uses
3158        // for untagged unit variants.
3159        variants.push((
3160            Cow::Borrowed("null"),
3161            Variant::unnamed()
3162                .field(Field::new(DataType::Tuple(Tuple::new(vec![]))))
3163                .build(),
3164        ));
3165    }
3166
3167    let mut collapsed = Enum::default();
3168    collapsed.variants = variants;
3169    Ok(Some(collapsed))
3170}
3171
3172/// Returns the [`DataType`] to render as `ndt`'s own top-level export body,
3173/// collapsing an untagged-enum alias cycle into valid TypeScript if `ndt` is
3174/// part of one (see [`collapse_untagged_alias_cycle`]). Borrows `ndt.ty`
3175/// unchanged in the (overwhelmingly common) non-cyclic case.
3176fn resolve_named_export_body<'a>(
3177    types: &Types,
3178    ndt: &'a NamedDataType,
3179) -> Result<Cow<'a, DataType>, Error> {
3180    let ty = ndt.ty.as_ref().expect("named datatype must have a body");
3181    match collapse_untagged_alias_cycle(types, ndt) {
3182        Ok(Some(collapsed)) => Ok(Cow::Owned(DataType::Enum(collapsed))),
3183        Ok(None) => Ok(Cow::Borrowed(ty)),
3184        Err(reason) => Err(Error::unrepresentable_alias_cycle(
3185            rust_type_path(ndt).into_owned(),
3186            reason,
3187        )
3188        .with_named_datatype(ndt)),
3189    }
3190}
3191
3192fn enum_dt(
3193    s: &mut String,
3194    exporter: &Exporter,
3195    types: &Types,
3196    e: &Enum,
3197    location: Vec<Cow<'static, str>>,
3198    prefix: &str,
3199    generics: &[(GenericReference, DataType)],
3200) -> Result<(), Error> {
3201    let is_finite_number = e.attributes.get_named_as(FINITE_NUMBER_MARKER) == Some(&true);
3202
3203    if e.attributes.get_named_as(DEFERRED_ALIAS_UNION_MARKER) == Some(&true) {
3204        return alias_field_union_dt(s, exporter, types, e, location, prefix, generics);
3205    }
3206
3207    if e.variants.is_empty() {
3208        s.push_str(NEVER);
3209        return Ok(());
3210    }
3211
3212    let filtered_variants = active_variants(e);
3213
3214    let discriminator = analyze_discriminator(&filtered_variants);
3215    let fallback_override = fallback_discriminator_override(discriminator.as_ref());
3216
3217    let mut rendered_variants = Vec::with_capacity(filtered_variants.len());
3218    for (idx, (variant_name, variant)) in filtered_variants.iter().enumerate() {
3219        let variant_override = fallback_override
3220            .as_ref()
3221            .and_then(|(fallback_idx, key, ty)| {
3222                (*fallback_idx == idx).then_some(VariantTypeOverride {
3223                    key,
3224                    ty: ty.as_str(),
3225                })
3226            });
3227
3228        let mut variant_location = location.clone();
3229        variant_location.push(variant_name.clone());
3230        let ts_values = enum_variant_datatype(
3231            exporter,
3232            None,
3233            types,
3234            variant_name.clone(),
3235            variant,
3236            variant_location,
3237            prefix,
3238            generics,
3239            variant_override,
3240        )?;
3241
3242        rendered_variants.push(EnumVariantOutput {
3243            value: ts_values.unwrap_or_else(|| NEVER.to_string()),
3244            strict_keys: untagged_strict_keys(variant),
3245        });
3246    }
3247
3248    // Rendering first preserves errors for unremapped BigInt-style variants.
3249    if is_finite_number {
3250        s.push_str("number");
3251        return Ok(());
3252    }
3253
3254    if discriminator.is_none() && !has_anonymous_variant(&filtered_variants) {
3255        strictify_enum_variants(&mut rendered_variants);
3256    }
3257
3258    let variants = filtered_variants
3259        .into_iter()
3260        .zip(rendered_variants)
3261        .map(|((_, variant), rendered)| {
3262            inner_comments(
3263                variant.deprecated.as_ref(),
3264                &variant.docs,
3265                rendered.value,
3266                true,
3267                prefix,
3268            )
3269        })
3270        .collect::<Vec<_>>();
3271
3272    push_union(s, variants);
3273
3274    Ok(())
3275}
3276
3277/// Renders serde field aliases as a deferred mapped XOR instead of an
3278/// intersection of unions. The latter distributes into one union member for
3279/// every combination of aliased fields, which quickly reaches TS2590.
3280///
3281/// The mapped type retains the original semantics for required fields: each
3282/// must use exactly one accepted spelling. Fully optional alias groups render
3283/// as their plain object intersection instead. TypeScript cannot retain their
3284/// duplicate-key rejection without forcing consumers to expand an exponential
3285/// union, while serde's optional/omitted behavior remains represented.
3286fn alias_field_union_dt(
3287    s: &mut String,
3288    exporter: &Exporter,
3289    types: &Types,
3290    e: &Enum,
3291    location: Vec<Cow<'static, str>>,
3292    prefix: &str,
3293    generics: &[(GenericReference, DataType)],
3294) -> Result<(), Error> {
3295    let mut fields = Vec::with_capacity(e.variants.len());
3296    let mut all_optional = true;
3297
3298    for (name, variant) in active_variants(e) {
3299        let mut variant = (*variant).clone();
3300        if let Fields::Unnamed(unnamed) = &mut variant.fields
3301            && let Some(DataType::Struct(strct)) = unnamed
3302                .fields
3303                .first_mut()
3304                .and_then(|field| field.ty.as_mut())
3305            && let Fields::Named(named) = &mut strct.fields
3306        {
3307            named
3308                .fields
3309                .retain(|(_, field)| !field.attributes.contains_key(ALIAS_EXCLUSION_MARKER));
3310            all_optional &= named.fields.iter().all(|(_, field)| field.optional);
3311        } else {
3312            all_optional = false;
3313        }
3314
3315        let mut variant_location = location.clone();
3316        variant_location.push(name.clone());
3317        let field = enum_variant_datatype(
3318            exporter,
3319            None,
3320            types,
3321            name.clone(),
3322            &variant,
3323            variant_location,
3324            prefix,
3325            generics,
3326            None,
3327        )?
3328        .unwrap_or_else(|| NEVER.to_string());
3329        fields.push(field);
3330    }
3331
3332    let source = fields.join(" & ");
3333    if all_optional {
3334        s.push_str(&source);
3335        return Ok(());
3336    }
3337
3338    s.push_str("((");
3339    s.push_str(&source);
3340    s.push_str(") extends infer T extends object ? { [K in keyof T]: { [P in keyof T as P extends K ? P : never]: T[P] } & { [P in keyof T as P extends K ? never : P]?: never } }[keyof T] & object : never)");
3341
3342    Ok(())
3343}
3344
3345fn tuple_dt(
3346    s: &mut String,
3347    exporter: &Exporter,
3348    types: &Types,
3349    t: &Tuple,
3350    location: Vec<Cow<'static, str>>,
3351    generics: &[(GenericReference, DataType)],
3352) -> Result<(), Error> {
3353    match t.elements.as_slice() {
3354        [] => s.push_str(NULL),
3355        elements => {
3356            s.push('[');
3357            for (idx, dt) in elements.iter().enumerate() {
3358                if idx != 0 {
3359                    s.push_str(", ");
3360                }
3361                let mut element_location = location.clone();
3362                element_location.push(idx.to_string().into());
3363                datatype(
3364                    s,
3365                    exporter,
3366                    None,
3367                    types,
3368                    dt,
3369                    element_location,
3370                    None,
3371                    "",
3372                    generics,
3373                )?;
3374            }
3375            s.push(']');
3376        }
3377    }
3378
3379    Ok(())
3380}
3381
3382fn reference_dt(
3383    s: &mut String,
3384    exporter: &Exporter,
3385    format: Option<&dyn Format>,
3386    types: &Types,
3387    r: &Reference,
3388    location: Vec<Cow<'static, str>>,
3389    prefix: &str,
3390    generics: &[(GenericReference, DataType)],
3391) -> Result<(), Error> {
3392    match r {
3393        Reference::Named(r) => match &r.inner {
3394            NamedReferenceType::Reference { .. } => {
3395                reference_named_dt(s, exporter, types, r, location, generics)
3396            }
3397            NamedReferenceType::Inline { dt, .. } => {
3398                let inline_path = path_string(&location);
3399                inline_datatype(
3400                    s, exporter, format, types, dt, location, None, prefix, 0, generics,
3401                )
3402                .map_err(|err| err.with_inline_trace(types.get(r), inline_path))
3403            }
3404            NamedReferenceType::Recursive(cycle) => Err(Error::infinite_recursive_inline_type(
3405                path_string(&location),
3406                format!("{r:?}"),
3407                cycle.clone(),
3408            )),
3409        },
3410        Reference::Opaque(r) => reference_opaque_dt(s, exporter, format, types, r, location),
3411    }
3412}
3413
3414fn reference_opaque_dt(
3415    s: &mut String,
3416    exporter: &Exporter,
3417    format: Option<&dyn Format>,
3418    types: &Types,
3419    r: &OpaqueReference,
3420    location: Vec<Cow<'static, str>>,
3421) -> Result<(), Error> {
3422    if let Some(def) = r.downcast_ref::<opaque::Define>() {
3423        s.push_str(&def.0);
3424        return Ok(());
3425    }
3426
3427    if r.downcast_ref::<opaque::Any>().is_some() {
3428        s.push_str("any");
3429        return Ok(());
3430    }
3431
3432    if r.downcast_ref::<opaque::Unknown>().is_some() {
3433        s.push_str("unknown");
3434        return Ok(());
3435    }
3436
3437    if r.downcast_ref::<opaque::Never>().is_some() {
3438        s.push_str("never");
3439        return Ok(());
3440    }
3441
3442    if r.downcast_ref::<opaque::Number>().is_some() {
3443        s.push_str("number");
3444        return Ok(());
3445    }
3446
3447    if r.downcast_ref::<opaque::BigInt>().is_some() {
3448        s.push_str("bigint");
3449        return Ok(());
3450    }
3451
3452    if let Some(def) = r.downcast_ref::<Branded>() {
3453        if let Some(branded_type) = exporter
3454            .branded_type_impl
3455            .as_ref()
3456            .map(|builder| {
3457                (builder.0)(
3458                    BrandedTypeExporter {
3459                        exporter,
3460                        format,
3461                        types,
3462                    },
3463                    def,
3464                )
3465            })
3466            .transpose()?
3467        {
3468            s.push_str(branded_type.as_ref());
3469            return Ok(());
3470        }
3471
3472        let mut payload = String::new();
3473        match def.ty() {
3474            DataType::Reference(r) => reference_dt(
3475                &mut payload,
3476                exporter,
3477                format,
3478                types,
3479                r,
3480                location.clone(),
3481                "",
3482                &[],
3483            )?,
3484            ty => inline_datatype(
3485                &mut payload,
3486                exporter,
3487                format,
3488                types,
3489                ty,
3490                location.clone(),
3491                None,
3492                "",
3493                0,
3494                &[],
3495            )?,
3496        }
3497        // The brand is intersected with the payload, so a payload that renders a
3498        // top-level union must be parenthesised or the brand is swallowed:
3499        // `string | null & Brand` parses as `string | (null & Brand)`.
3500        push_intersection_operand(s, def.ty(), &payload);
3501        s.push_str(r#" & { readonly __brand: ""#);
3502        s.push_str(&escape_typescript_string_literal(def.brand()));
3503        s.push_str("\" }");
3504        return Ok(());
3505    }
3506
3507    Err(Error::unsupported_opaque_reference(
3508        path_string(&location),
3509        r.clone(),
3510    ))
3511}
3512
3513fn reference_named_dt(
3514    s: &mut String,
3515    exporter: &Exporter,
3516    types: &Types,
3517    r: &NamedReference,
3518    location: Vec<Cow<'static, str>>,
3519    generics: &[(GenericReference, DataType)],
3520) -> Result<(), Error> {
3521    let path = path_string(&location);
3522    let ndt = types
3523        .get(r)
3524        .ok_or_else(|| Error::dangling_named_reference(path.clone(), format!("{r:?}")))?;
3525    // We check it's valid before tracking
3526    crate::references::track_nr(r);
3527
3528    let name = referenced_type_name(exporter, ndt);
3529
3530    let (rendered_generics, omit_generics, scoped_generics) =
3531        resolved_reference_generics(ndt, r, generics)
3532            .ok_or_else(|| Error::dangling_named_reference(path, format!("{r:?}")))?;
3533
3534    s.push_str(&name);
3535    if !omit_generics && !rendered_generics.is_empty() {
3536        s.push('<');
3537
3538        for (i, dt) in rendered_generics.iter().enumerate() {
3539            if i != 0 {
3540                s.push_str(", ");
3541            }
3542
3543            datatype(
3544                s,
3545                exporter,
3546                None,
3547                types,
3548                dt,
3549                vec![],
3550                None,
3551                "",
3552                &scoped_generics,
3553            )?;
3554        }
3555
3556        s.push('>');
3557    }
3558
3559    Ok(())
3560}