Skip to main content

hyprstream_ts_codegen/ts_codegen/
interfaces.rs

1//! Generate TypeScript interfaces from Cap'n Proto struct and enum definitions.
2
3use hyprstream_rpc_build::schema::types::{
4    EnumDef, FieldDef, FieldSection, ParsedSchema, StructDef,
5};
6use hyprstream_rpc_build::util::to_camel_case;
7
8use super::capnp_to_ts_type;
9
10/// Generate all interface and type declarations for a service.
11pub fn generate_interfaces(out: &mut String, schema: &ParsedSchema) {
12    // 1. Enum types
13    for e in &schema.enums {
14        emit_enum(out, e);
15    }
16
17    // 2. Struct interfaces (data types referenced by request/response variants)
18    for s in &schema.structs {
19        emit_struct_interface(out, s, schema);
20    }
21}
22
23/// Emit a TypeScript string union type from an enum definition.
24fn emit_enum(out: &mut String, e: &EnumDef) {
25    out.push_str(&format!("export type {} =", e.name));
26    for (i, (name, _ord)) in e.variants.iter().enumerate() {
27        if i == 0 {
28            out.push('\n');
29        }
30        let sep = if i + 1 < e.variants.len() { "" } else { ";" };
31        out.push_str(&format!("  | '{}'{}\n", to_camel_case(name), sep));
32    }
33    out.push('\n');
34}
35
36/// Emit a TypeScript interface for an inline union `group` arm's leaf fields.
37///
38/// Mirrors the non-union-field emission in [`emit_struct_interface`]: struct
39/// pointers are nullable, Option*/Text/Data/List are not.
40fn emit_group_interface(out: &mut String, name: &str, leaves: &[FieldDef]) {
41    out.push_str(&format!("export interface {name} {{\n"));
42    for leaf in leaves {
43        let ts = capnp_to_ts_type(&leaf.type_name);
44        let nullable = if matches!(leaf.section, FieldSection::Pointer)
45            && !matches!(leaf.type_name.as_str(), "Text" | "Data")
46            && !leaf.type_name.starts_with("List(")
47            && !leaf.type_name.starts_with("Option")
48        {
49            " | null"
50        } else {
51            ""
52        };
53        out.push_str(&format!(
54            "  {}: {}{};\n",
55            to_camel_case(&leaf.name),
56            ts,
57            nullable
58        ));
59    }
60    out.push_str("}\n\n");
61}
62
63/// Emit a TypeScript interface from a struct definition.
64///
65/// Union-having structs emit as typed discriminated-union aliases (see
66/// [`super::emits_union_alias`]): each arm mirrors exactly what the generated
67/// parser returns for that discriminant (`{ variant: '<name>', data: <typed> }`,
68/// with any non-union fields shared into every arm), plus the parser's
69/// default-case `{ variant: 'unknown'; data: null }`. Mixed structs (named
70/// fields + union) that are referenced data types must take this path — a
71/// named-fields-only interface would not declare the `variant`/`data`
72/// properties the generated request serializer switches on (#1616).
73/// Service/scoped envelopes and plain structs get a named-fields interface.
74fn emit_struct_interface(out: &mut String, s: &StructDef, schema: &ParsedSchema) {
75    if super::emits_union_alias(schema, s) {
76        let union_fields: Vec<_> = s.union_fields().collect();
77        // Synthesize a named interface for each inline `group` arm. Its leaf
78        // fields live in this struct's own sections, so the arm's `data` is
79        // that leaf shape (see `group_arm_leaves`). Emit before the union
80        // type so the alias can reference it.
81        for f in &union_fields {
82            if let Some(leaves) = super::group_arm_leaves(s, f) {
83                emit_group_interface(out, &super::group_arm_type_name(&s.name, &f.name), leaves);
84            }
85        }
86        let shared_fields = super::shared_union_fields(s);
87        let arms: Vec<(String, String)> = union_fields
88            .iter()
89            // Use the raw field name to match the generated parser/builder,
90            // which key the discriminated `variant` on the capnp field name.
91            .map(|f| (f.name.clone(), super::union_arm_data_type(s, f)))
92            .collect();
93        super::emit_union_alias(out, &s.name, &shared_fields, &arms);
94        return;
95    }
96
97    let non_union_fields: Vec<_> = s.non_union_fields().collect();
98
99    out.push_str(&format!("export interface {} {{\n", s.name));
100    for f in &non_union_fields {
101        let ts = capnp_to_ts_type(&f.type_name);
102        let opt = if f.optional { "?" } else { "" };
103        // Struct pointer fields are nullable (getStruct can return null).
104        // Option* types already encode absence as `undefined` — don't add `| null`.
105        let nullable = if matches!(f.section, FieldSection::Pointer)
106            && !matches!(f.type_name.as_str(), "Text" | "Data")
107            && !f.type_name.starts_with("List(")
108            && !f.type_name.starts_with("Option")
109        {
110            " | null"
111        } else {
112            ""
113        };
114        out.push_str(&format!(
115            "  {}{}: {}{};\n",
116            to_camel_case(&f.name),
117            opt,
118            ts,
119            nullable
120        ));
121    }
122    out.push_str("}\n\n");
123}