Skip to main content

hyprstream_ts_codegen/ts_codegen/
mod.rs

1//! TypeScript code generation from parsed Cap'n Proto schemas.
2//!
3//! Generates:
4//! - `capnp.ts`         — Wire format runtime (CapnpMessageBuilder + CapnpReader)
5//! - `{service}.ts`     — Per-service interfaces, builders, parsers, clients
6//! - `index.ts`         — Re-exports
7
8mod builders;
9mod client;
10mod interfaces;
11mod message;
12mod parsers;
13
14use std::path::Path;
15
16use hyprstream_rpc_build::backend::CodegenBackend;
17use hyprstream_rpc_build::schema::types::{
18    ArmPayload, EnumDef, FieldDef, FieldSection, ParsedSchema, ScopedClient, StructDef,
19};
20use hyprstream_rpc_build::util::{to_camel_case, to_pascal_case};
21
22/// Generate all output files from parsed schemas using the given backend.
23#[allow(clippy::print_stdout)]
24pub fn generate_all<B: CodegenBackend>(
25    backend: &B,
26    schemas: &[(String, ParsedSchema)],
27    output_dir: &Path,
28) {
29    // 1. Runtime file (e.g. capnp.ts)
30    let (runtime_name, runtime_content) = backend.runtime_file();
31    let runtime_path = output_dir.join(&runtime_name);
32    std::fs::write(&runtime_path, runtime_content).expect("Failed to write runtime file");
33    println!("  Generated {runtime_name}");
34
35    // 2. Per-schema service files
36    let mut all_names = Vec::new();
37    let mut client_names = Vec::new();
38    let mut module_contents = Vec::new();
39    for (name, schema) in schemas {
40        let content = backend.generate_service_file(name, schema);
41        let filename = format!("{name}.{}", backend.file_extension());
42        let path = output_dir.join(&filename);
43        std::fs::write(&path, &content).expect("Failed to write service file");
44        println!("  Generated {filename}");
45        all_names.push(name.clone());
46        if schema.request_struct.is_some() {
47            client_names.push(name.clone());
48        }
49        module_contents.push((name.clone(), content));
50    }
51
52    // 3. Optional index/manifest file
53    if let Some((index_name, index_content)) =
54        backend.index_file(&all_names, &client_names, &module_contents)
55    {
56        let index_path = output_dir.join(&index_name);
57        std::fs::write(&index_path, index_content).expect("Failed to write index file");
58        println!("  Generated {index_name}");
59    }
60}
61
62/// Generate a single TypeScript file for a schema.
63///
64/// For service schemas (with request/response structs): generates interfaces,
65/// service builders/parsers, client class, plus standalone struct builders/parsers.
66/// For data-only schemas: generates interfaces and standalone struct builders/parsers only.
67fn generate_service_file(service_name: &str, schema: &ParsedSchema) -> String {
68    let mut out = String::with_capacity(8192);
69
70    let is_service = schema.request_struct.is_some();
71
72    // Header
73    out.push_str(&format!(
74        "// Generated by hyprstream-ts-codegen — DO NOT EDIT\n\
75         // {label}: {service_name}\n\n\
76         import {{ CapnpArena, CapnpReader }} from './capnp';\n",
77        label = if is_service { "Service" } else { "Schema" }
78    ));
79
80    // Inline StreamHandle interface (only for service schemas with streaming methods)
81    if is_service && client::has_streaming_methods(schema) {
82        out.push_str(
83            "/** Verified stream handle (duck-type compatible with WASM StreamHandle). */\n\
84             export interface StreamHandle {\n\
85             \x20 nextPayload(): Promise<Uint8Array | null>;\n\
86             \x20 cancel(): Promise<void>;\n\
87             \x20 streamId(): string;\n\
88             \x20 isCompleted(): boolean;\n\
89             \x20 free(): void;\n\
90             \x20 [Symbol.dispose](): void;\n\
91             }\n\n",
92        );
93    }
94    out.push('\n');
95
96    // Interfaces
97    interfaces::generate_interfaces(&mut out, schema);
98
99    // Service builders/parsers (request/response union serialization)
100    builders::generate_builders(&mut out, service_name, schema);
101    parsers::generate_parsers(&mut out, service_name, schema);
102
103    // Standalone struct builders/parsers (for all union-bearing structs in schema.structs)
104    builders::generate_struct_builders(&mut out, schema);
105    parsers::generate_struct_parsers(&mut out, schema);
106
107    // Client class (only for service schemas)
108    if is_service {
109        client::generate_client(&mut out, service_name, schema);
110    }
111
112    out
113}
114
115// ---------------------------------------------------------------------------
116// Shared helpers used by submodules
117// ---------------------------------------------------------------------------
118
119/// Map a Cap'n Proto type name to a TypeScript type.
120fn capnp_to_ts_type(type_name: &str) -> String {
121    match type_name {
122        "Void" => "undefined".into(),
123        "Bool" => "boolean".into(),
124        "UInt8" | "UInt16" | "UInt32" | "Int8" | "Int16" | "Int32" | "Float32" | "Float64" => {
125            "number".into()
126        }
127        "UInt64" | "Int64" => "bigint".into(),
128        "Text" => "string".into(),
129        "Data" => "Uint8Array".into(),
130        _ if type_name.starts_with("List(") => {
131            let inner = &type_name[5..type_name.len() - 1];
132            format!("{}[]", capnp_to_ts_type(inner))
133        }
134        _ if type_name.starts_with("Option") => {
135            // Option<T> wrapper struct — map to `T | undefined`.
136            // Struct names use "Option" + capnp-case suffix (e.g. "OptionUint32", "OptionFloat32").
137            // Normalize to the canonical capnp type name before mapping.
138            let suffix = &type_name["Option".len()..];
139            let normalized = match suffix {
140                "Uint8" => "UInt8",
141                "Uint16" => "UInt16",
142                "Uint32" => "UInt32",
143                "Uint64" => "UInt64",
144                "Int8" => "Int8",
145                "Int16" => "Int16",
146                "Int32" => "Int32",
147                "Int64" => "Int64",
148                other => other,
149            };
150            format!("{} | undefined", capnp_to_ts_type(normalized))
151        }
152        _ => type_name.to_owned(),
153    }
154}
155
156/// Compute the byte offset for a data-section field based on its type and slot_offset.
157///
158/// Cap'n Proto slot_offset is in units of the type size:
159/// - Bool: 1-bit units (byteOff = offset/8, bitIdx = offset%8)
160/// - UInt8/Int8: byte units
161/// - UInt16/Int16: 2-byte units
162/// - UInt32/Int32/Float32: 4-byte units
163/// - UInt64/Int64/Float64: 8-byte units
164fn data_byte_offset(field: &FieldDef) -> u32 {
165    match field.type_name.as_str() {
166        "Bool" => field.slot_offset / 8,
167        "UInt8" | "Int8" => field.slot_offset,
168        "UInt16" | "Int16" => field.slot_offset * 2,
169        "UInt32" | "Int32" | "Float32" => field.slot_offset * 4,
170        "UInt64" | "Int64" | "Float64" => field.slot_offset * 8,
171        _ => {
172            // Enum types in data section are stored as UInt16
173            if field.section == FieldSection::Data {
174                field.slot_offset * 2
175            } else {
176                field.slot_offset
177            }
178        }
179    }
180}
181
182/// Return the bit index for a Bool field.
183fn bool_bit_index(field: &FieldDef) -> u32 {
184    field.slot_offset % 8
185}
186
187/// Return the TypeScript setter method name on `CapnpMessageBuilder` / `StructBuilder`.
188///
189/// Returns `None` for types that the runtime doesn't support yet (e.g., struct lists).
190fn setter_method(type_name: &str) -> Option<&str> {
191    Some(match type_name {
192        "Bool" => "setBool",
193        "UInt8" => "setUint8",
194        "UInt16" => "setUint16",
195        "UInt32" => "setUint32",
196        "UInt64" => "setUint64",
197        "Int8" => "setInt8",
198        "Int16" => "setInt16",
199        "Int32" => "setInt32",
200        "Int64" => "setInt64",
201        "Float32" => "setFloat32",
202        "Float64" => "setFloat64",
203        "Text" => "setText",
204        "Data" => "setData",
205        _ => return None, // List(_), struct pointers, etc. — handled by list_setter_method / struct codegen
206    })
207}
208
209/// Return the TypeScript setter method name for a `List(<inner>)` field, given
210/// the inner element type name (e.g. `"Int64"`, `"Bool"`, `"Text"`, `"Data"`).
211///
212/// This is the single source of truth for which list element shapes the
213/// `capnp.ts` runtime supports as a flat (non-composite-of-structs) list.
214/// `None` means the caller must fall through to struct-list codegen (if
215/// `inner` names a known struct) — anything else is an unresolved reference
216/// and must be treated as a hard generator error, never a silent comment.
217pub(crate) fn list_setter_method(inner: &str) -> Option<&str> {
218    Some(match inner {
219        "Text" => "setTextList",
220        "Data" => "setDataList",
221        "Bool" => "setBoolList",
222        "UInt8" => "setUint8List",
223        "Int8" => "setInt8List",
224        "UInt16" => "setUint16List",
225        "Int16" => "setInt16List",
226        "UInt32" => "setUint32List",
227        "Int32" => "setInt32List",
228        "UInt64" => "setUint64List",
229        "Int64" => "setInt64List",
230        "Float32" => "setFloat32List",
231        "Float64" => "setFloat64List",
232        _ => return None,
233    })
234}
235
236/// Return the TypeScript getter method name for a `List(<inner>)` field.
237/// Mirrors [`list_setter_method`] — see its docs.
238pub(crate) fn list_getter_method(inner: &str) -> Option<&str> {
239    Some(match inner {
240        "Text" => "getTextList",
241        "Data" => "getDataList",
242        "Bool" => "getBoolList",
243        "UInt8" => "getUint8List",
244        "Int8" => "getInt8List",
245        "UInt16" => "getUint16List",
246        "Int16" => "getInt16List",
247        "UInt32" => "getUint32List",
248        "Int32" => "getInt32List",
249        "UInt64" => "getUint64List",
250        "Int64" => "getInt64List",
251        "Float32" => "getFloat32List",
252        "Float64" => "getFloat64List",
253        _ => return None,
254    })
255}
256
257/// Return the TypeScript setter method name for a `List(List(<inner>))` field,
258/// given the doubly-nested (innermost) element type name — e.g. `"Float32"`
259/// for the `embeddings: List(List(Float32))` shape used by
260/// `inference.capnp`/`model.capnp`.
261///
262/// Mirrors [`list_setter_method`] one level deeper: the runtime encodes the
263/// outer list as a plain pointer list (each element itself a `List(<inner>)`
264/// pointer), so only inner element types the flat list runtime already
265/// supports as a *primitive* list are covered here — `None` for `Text`/`Data`
266/// (nested `List(List(Text))`/`List(List(Data))`) and struct/list inner types,
267/// which are not yet implemented and must remain a hard generator error
268/// rather than silently degrading (#758).
269pub(crate) fn nested_list_setter_method(inner: &str) -> Option<&str> {
270    Some(match inner {
271        "Bool" => "setBoolListList",
272        "UInt8" => "setUint8ListList",
273        "Int8" => "setInt8ListList",
274        "UInt16" => "setUint16ListList",
275        "Int16" => "setInt16ListList",
276        "UInt32" => "setUint32ListList",
277        "Int32" => "setInt32ListList",
278        "UInt64" => "setUint64ListList",
279        "Int64" => "setInt64ListList",
280        "Float32" => "setFloat32ListList",
281        "Float64" => "setFloat64ListList",
282        _ => return None,
283    })
284}
285
286/// Return the TypeScript getter method name for a `List(List(<inner>))`
287/// field. Mirrors [`nested_list_setter_method`] — see its docs.
288pub(crate) fn nested_list_getter_method(inner: &str) -> Option<&str> {
289    Some(match inner {
290        "Bool" => "getBoolListList",
291        "UInt8" => "getUint8ListList",
292        "Int8" => "getInt8ListList",
293        "UInt16" => "getUint16ListList",
294        "Int16" => "getInt16ListList",
295        "UInt32" => "getUint32ListList",
296        "Int32" => "getInt32ListList",
297        "UInt64" => "getUint64ListList",
298        "Int64" => "getInt64ListList",
299        "Float32" => "getFloat32ListList",
300        "Float64" => "getFloat64ListList",
301        _ => return None,
302    })
303}
304
305/// Return the default TS expression for a Cap'n Proto type (used for optional field coalescing).
306fn default_value_expr(type_name: &str) -> &str {
307    match type_name {
308        "Bool" => "false",
309        "UInt8" | "UInt16" | "UInt32" | "Int8" | "Int16" | "Int32" | "Float32" | "Float64" => "0",
310        "UInt64" | "Int64" => "0n",
311        "Text" => "''",
312        "Data" => "new Uint8Array(0)",
313        _ if type_name.starts_with("List(") => "[]",
314        _ => "undefined",
315    }
316}
317
318/// Return the TypeScript getter method name on `CapnpReader` / `StructReader`.
319fn getter_method(type_name: &str) -> &str {
320    match type_name {
321        "Bool" => "getBool",
322        "UInt8" => "getUint8",
323        "UInt16" => "getUint16",
324        "UInt32" => "getUint32",
325        "UInt64" => "getUint64",
326        "Int8" => "getInt8",
327        "Int16" => "getInt16",
328        "Int32" => "getInt32",
329        "Int64" => "getInt64",
330        "Float32" => "getFloat32",
331        "Float64" => "getFloat64",
332        "Text" => "getText",
333        "Data" => "getData",
334        // Callers only ever reach this function for `is_data_scalar`-narrowed
335        // types or a literal Text/Data check — List(_) always resolves through
336        // `list_getter_method` at the call site instead. Anything else getting
337        // here is a generator bug: fail loudly rather than silently guessing
338        // `getText` (the old behavior masked exactly this class of bug — #725).
339        other => panic!(
340            "ts_codegen: getter_method called with unsupported type `{other}` — this \
341             indicates a generator bug in the call site (missing a scalar/Text/Data \
342             guard), never silently degrade to a guessed getter (#725)."
343        ),
344    }
345}
346
347/// Check if a capnp type is a simple scalar (data section, not pointer).
348pub(crate) fn is_data_scalar(type_name: &str) -> bool {
349    matches!(
350        type_name,
351        "Bool"
352            | "UInt8"
353            | "UInt16"
354            | "UInt32"
355            | "UInt64"
356            | "Int8"
357            | "Int16"
358            | "Int32"
359            | "Int64"
360            | "Float32"
361            | "Float64"
362    )
363}
364
365/// Extract the inner type name from a `List(Foo)` type string. Returns `None` for non-list types.
366fn extract_list_inner_type(type_name: &str) -> Option<&str> {
367    if type_name.starts_with("List(") && type_name.ends_with(')') {
368        Some(&type_name[5..type_name.len() - 1])
369    } else {
370        None
371    }
372}
373
374/// Check if a capnp type name is a primitive (not a struct reference).
375///
376/// Delegates to `is_primitive_capnp_type` in `schema::types` — the canonical
377/// implementation shared with the CGR reader.
378pub(crate) fn is_primitive(type_name: &str) -> bool {
379    hyprstream_rpc_build::schema::types::is_primitive_capnp_type(type_name)
380}
381
382/// Map a union-member field to the TypeScript type carried in the `data` slot.
383///
384/// Mirrors the per-variant `data` expression produced by the parser emitters:
385/// - `Void`              → `undefined`
386/// - scalars / `Bool`    → the TS scalar (`number` / `bigint` / `boolean`)
387/// - `Text`              → `string`
388/// - `Data`              → `Uint8Array`
389/// - `List(Text)`        → `string[]`
390/// - `List(Struct)`      → `Inner[]` (elements are parsed into objects)
391/// - `Option*` wrapper   → `T | undefined` (absence is `undefined`, never `null`)
392/// - struct              → `TypeName | null` (the parser returns `null` on a null pointer)
393///
394/// Keeping this aligned with the parser guarantees the typed discriminated union
395/// is sound against the runtime values callers actually receive. Shared by both
396/// the interface emitter (`interfaces.rs`) and the parser-result type aliases
397/// (`parsers.rs`).
398pub(crate) fn union_variant_data_type(f: &FieldDef) -> String {
399    let tn = f.type_name.as_str();
400    if tn == "Void" {
401        return "undefined".to_owned();
402    }
403    if tn.starts_with("List(") {
404        // capnp_to_ts_type already maps List(T) → T[].
405        return capnp_to_ts_type(tn);
406    }
407    // `is_primitive` already covers Text/Data (and Void/List); no extra checks.
408    if is_primitive(tn) {
409        return capnp_to_ts_type(tn);
410    }
411    // Option* wrapper structs encode absence as `undefined`
412    // (capnp_to_ts_type maps `OptionUint32` → `number | undefined`); they live in
413    // the pointer section but must NOT get the struct-pointer `| null` suffix.
414    if tn.starts_with("Option") {
415        return capnp_to_ts_type(tn);
416    }
417    // Struct (or enum) reference. Struct pointers can be null at runtime; enums
418    // are data-section and never null, but the only data-section non-scalar union
419    // payloads are enums, which `capnp_to_ts_type` maps to their type name.
420    if matches!(f.section, FieldSection::Pointer) {
421        format!("{} | null", capnp_to_ts_type(tn))
422    } else {
423        capnp_to_ts_type(tn)
424    }
425}
426
427/// If union field `uf` of struct `sd` is an inline `group` arm, return its leaf
428/// fields (from the structured `union_arms` view). `None` for Void/single-type
429/// arms.
430///
431/// A capnp `group` arm carries an inlined anonymous struct whose leaf fields are
432/// allocated their own slots in the ENCLOSING struct's data/pointer sections;
433/// each leaf `FieldDef` therefore already carries a correct `slot_offset` +
434/// `section` (extracted by the same `field_def_from_slot` path as a normal
435/// field), so build/parse can read/write them directly on the enclosing
436/// reader/builder.
437pub(crate) fn group_arm_leaves<'a>(sd: &'a StructDef, uf: &FieldDef) -> Option<&'a [FieldDef]> {
438    if uf.section != FieldSection::Group {
439        return None;
440    }
441    sd.union_arms
442        .iter()
443        .find(|a| a.name == uf.name)
444        .and_then(|a| match &a.payload {
445            ArmPayload::Group(leaves) => Some(leaves.as_slice()),
446            _ => None,
447        })
448}
449
450/// Name of the synthesized TypeScript interface for a group arm, e.g. the
451/// `dropOldest` arm of `OverflowPolicy` → `OverflowPolicyDropOldest`.
452pub(crate) fn group_arm_type_name(struct_name: &str, arm_name: &str) -> String {
453    format!("{struct_name}{}", to_pascal_case(arm_name))
454}
455
456/// The `data:` TypeScript type for one arm of struct `sd`'s discriminated union.
457///
458/// Same as [`union_variant_data_type`] for Void/scalar/struct arms, but a group
459/// arm resolves to its synthesized interface (`{Struct}{Arm}` | null) instead of
460/// the bare, undefined `Group`. Shared by the interface emitter and the parser
461/// result-type aliases so type/build/parse agree.
462pub(crate) fn union_arm_data_type(sd: &StructDef, f: &FieldDef) -> String {
463    if group_arm_leaves(sd, f).is_some() {
464        format!("{} | null", group_arm_type_name(&sd.name, &f.name))
465    } else {
466        union_variant_data_type(f)
467    }
468}
469
470/// Shared named-field fragments for a union-having struct's discriminated
471/// aliases. One `name: type` entry per non-union field, with the same
472/// nullability rule the parser result aliases use, so the input alias and the
473/// `*Result` alias stay structurally identical.
474pub(crate) fn shared_union_fields(s: &StructDef) -> Vec<String> {
475    s.non_union_fields()
476        .map(|f| {
477            let ts_type = capnp_to_ts_type(&f.type_name);
478            // Struct pointer fields may be null when the capnp pointer is null.
479            let ts_type = if f.section == FieldSection::Pointer
480                && !f.type_name.starts_with("List(")
481                && f.type_name != "Text"
482                && f.type_name != "Data"
483                && !is_primitive(&f.type_name)
484            {
485                format!("{ts_type} | null")
486            } else {
487                ts_type
488            };
489            format!("{}: {}", to_camel_case(&f.name), ts_type)
490        })
491        .collect()
492}
493
494/// Emit a typed discriminated-union alias: one arm per union variant (data
495/// type mirroring the parser output) plus the parser's `unknown` default arm,
496/// with any non-union fields shared into every arm. Shared by the interface
497/// emitter (input aliases) and the parser result aliases.
498pub(crate) fn emit_union_alias(
499    out: &mut String,
500    name: &str,
501    shared_fields: &[String],
502    arms: &[(String, String)],
503) {
504    let shared = shared_fields.join("; ");
505    let shared_prefix = if shared.is_empty() {
506        String::new()
507    } else {
508        format!("{shared}; ")
509    };
510    out.push_str(&format!("export type {name} =\n"));
511    for (variant, data_ty) in arms {
512        out.push_str(&format!(
513            "  | {{ {shared_prefix}variant: '{variant}'; data: {data_ty} }}\n"
514        ));
515    }
516    out.push_str(&format!(
517        "  | {{ {shared_prefix}variant: 'unknown'; data: null }};\n\n"
518    ));
519}
520
521/// `true` when `sd` is a service or scoped request/response envelope — a
522/// struct with dedicated builder/parse paths (`builders.rs`, scoped response
523/// parsing) that never constructs or narrows the object type. Envelopes keep
524/// their legacy named-fields-only interface; every other union-having struct
525/// referenced as a data type must carry its union in the emitted type or the
526/// generated serializer/parser shapes disagree (#1616).
527pub(crate) fn is_service_envelope(schema: &ParsedSchema, sd: &StructDef) -> bool {
528    if schema
529        .request_struct
530        .as_ref()
531        .is_some_and(|rs| rs.name == sd.name)
532        || schema
533            .response_struct
534            .as_ref()
535            .is_some_and(|rs| rs.name == sd.name)
536    {
537        return true;
538    }
539    fn factory_names<'a>(scs: &'a [ScopedClient], out: &mut Vec<&'a str>) {
540        for sc in scs {
541            out.push(sc.factory_name.as_str());
542            factory_names(&sc.nested_clients, out);
543        }
544    }
545    let mut names = Vec::new();
546    factory_names(&schema.scoped_clients, &mut names);
547    schema.structs.iter().any(|s| {
548        s.fields
549            .iter()
550            .any(|f| names.contains(&f.name.as_str()) && f.type_name == sd.name)
551    })
552}
553
554/// `true` when struct `name` is referenced as a field, union-arm, group-leaf,
555/// or list element type anywhere in the schema.
556pub(crate) fn is_referenced_data_type(schema: &ParsedSchema, name: &str) -> bool {
557    schema.structs.iter().any(|s| {
558        s.fields.iter().any(|f| {
559            f.type_name == name
560                || extract_list_inner_type(&f.type_name).is_some_and(|i| i == name)
561                || extract_list_inner_type(&f.type_name)
562                    .and_then(extract_list_inner_type)
563                    .is_some_and(|i| i == name)
564        }) || s.union_arms.iter().any(|a| match &a.payload {
565            ArmPayload::Group(leaves) => leaves.iter().any(|f| f.type_name == name),
566            _ => false,
567        })
568    })
569}
570
571/// `true` when the emitted TypeScript for `sd` must be a discriminated-union
572/// alias rather than a named-fields-only interface.
573///
574/// Pure union envelopes are always aliases (existing behavior). A *mixed*
575/// struct (named fields + union) becomes an alias only when it is a referenced
576/// data type — service/scoped envelopes keep their legacy interface because
577/// their dedicated builder/parse paths never construct or narrow the object
578/// type. Without the alias, the generated request serializer switches on
579/// `variant`/`data` properties the interface does not declare, and the
580/// generated payload parser drops the union on the floor (#1616).
581pub(crate) fn emits_union_alias(schema: &ParsedSchema, sd: &StructDef) -> bool {
582    if !sd.has_union || sd.union_fields().next().is_none() {
583        return false;
584    }
585    if sd.non_union_fields().next().is_none() {
586        return true;
587    }
588    !is_service_envelope(schema, sd) && is_referenced_data_type(schema, &sd.name)
589}
590
591/// Build a TypeScript array literal from an enum's variants (camelCase names as strings).
592///
593/// Example output: `['active', 'inactive', 'pending']`
594fn enum_ordinal_array(ed: &EnumDef) -> String {
595    let variants: Vec<String> = ed
596        .variants
597        .iter()
598        .map(|(name, _)| format!("'{}'", to_camel_case(name)))
599        .collect();
600    format!("[{}]", variants.join(", "))
601}
602
603/// Emit a `setUint16` call that converts a TypeScript string enum to its wire ordinal.
604///
605/// Generates: `{indent}{builder_var}.setUint16({byte_off}, [...].indexOf({value_expr}));`
606pub(crate) fn emit_enum_setter(
607    out: &mut String,
608    indent: &str,
609    builder_var: &str,
610    byte_off: u32,
611    value_expr: &str,
612    ed: &EnumDef,
613) {
614    out.push_str(&format!(
615        "{indent}{builder_var}.setUint16({byte_off}, {}.indexOf({value_expr}));\n",
616        enum_ordinal_array(ed)
617    ));
618}
619
620/// Return a TypeScript expression that reads a UInt16 ordinal and maps it to a string enum.
621///
622/// Example output: `(['active', 'inactive'][reader.getUint16(4)] ?? 'unknown') as Status`
623pub(crate) fn emit_enum_getter_expr(
624    reader_var: &str,
625    byte_off: u32,
626    type_name: &str,
627    ed: &EnumDef,
628) -> String {
629    format!(
630        "({}[{reader_var}.getUint16({byte_off})] ?? 'unknown') as {type_name}",
631        enum_ordinal_array(ed)
632    )
633}
634
635// ---------------------------------------------------------------------------
636// TypeScript backend
637// ---------------------------------------------------------------------------
638
639/// TypeScript code generation backend.
640///
641/// Wraps the existing TypeScript emitters and implements the language-agnostic
642/// `CodegenBackend` trait, enabling `generate_all` to be called generically.
643pub struct TypeScriptBackend;
644
645impl CodegenBackend for TypeScriptBackend {
646    fn map_type(&self, capnp_type: &str) -> String {
647        capnp_to_ts_type(capnp_type)
648    }
649
650    fn setter_method(&self, type_name: &str) -> Option<String> {
651        setter_method(type_name).map(str::to_owned)
652    }
653
654    fn getter_expr(&self, reader_var: &str, field: &FieldDef) -> String {
655        // Simplified expression for the trait surface.
656        // Full dispatch (enums, structs, lists) is handled by the emitter functions.
657        let method = getter_method(&field.type_name);
658        format!("{reader_var}.{method}({})", field.slot_offset)
659    }
660
661    fn default_value(&self, type_name: &str) -> String {
662        default_value_expr(type_name).to_owned()
663    }
664
665    fn generate_service_file(&self, service_name: &str, schema: &ParsedSchema) -> String {
666        generate_service_file(service_name, schema)
667    }
668
669    fn runtime_file(&self) -> (String, String) {
670        ("capnp.ts".to_owned(), message::generate_capnp_runtime())
671    }
672
673    fn file_extension(&self) -> &str {
674        "ts"
675    }
676
677    fn index_file(
678        &self,
679        all_names: &[String],
680        client_names: &[String],
681        module_contents: &[(String, String)],
682    ) -> Option<(String, String)> {
683        Some((
684            "index.ts".to_owned(),
685            generate_index(all_names, client_names, module_contents),
686        ))
687    }
688}
689
690/// Scan the literal top-level exported symbol names out of generated TS source.
691///
692/// This is the single source of truth for "what does this module export": it
693/// reads the text that was actually emitted (`export interface X`, `export type
694/// X`, `export function X`) rather than independently re-deriving struct/enum/
695/// function naming rules, so it can never drift from what `interfaces.rs` /
696/// `builders.rs` / `parsers.rs` actually produce.
697fn scan_exported_names(content: &str) -> Vec<String> {
698    const PREFIXES: &[&str] = &["export interface ", "export type ", "export function "];
699    let mut names = Vec::new();
700    for line in content.lines() {
701        let line = line.trim_start();
702        for prefix in PREFIXES {
703            if let Some(rest) = line.strip_prefix(prefix) {
704                let name: String = rest
705                    .chars()
706                    .take_while(|c| c.is_alphanumeric() || *c == '_')
707                    .collect();
708                if !name.is_empty() {
709                    names.push(name);
710                }
711                break;
712            }
713        }
714    }
715    names
716}
717
718/// Generate index.ts with re-exports.
719///
720/// For service schemas: re-exports `{Pascal}Client` class.
721/// For data-only schemas: re-exports all exported symbols (standalone builders/parsers).
722/// Does not use `export type *` for service schemas since different services
723/// may share type names (e.g., ErrorInfo, StreamInfo) which causes TS2308 conflicts.
724///
725/// Data-only modules are barrel-exported with a plain `export * from './name'`
726/// UNLESS one of their exported names also appears in another data-only
727/// module — in that case every data-only module sharing the name switches to
728/// an explicit `export { ... }` list with the colliding names aliased as
729/// `{PascalModuleName}{Name}`, so two modules can never silently shadow one
730/// another's export (#725) and a full regen never leaves an ambiguous name
731/// for tsc to reject.
732fn generate_index(
733    all_names: &[String],
734    client_names: &[String],
735    module_contents: &[(String, String)],
736) -> String {
737    // Exported names per data-only module (services only ever barrel-export
738    // their Client class, so they can't collide with each other here).
739    let data_only_exports: Vec<(&String, Vec<String>)> = all_names
740        .iter()
741        .filter(|name| !client_names.contains(name))
742        .map(|name| {
743            let content = module_contents
744                .iter()
745                .find(|(n, _)| n == name)
746                .map(|(_, c)| c.as_str())
747                .unwrap_or_default();
748            (name, scan_exported_names(content))
749        })
750        .collect();
751
752    // name -> number of data-only modules that export it
753    let mut occurrence_count: std::collections::HashMap<&str, usize> =
754        std::collections::HashMap::new();
755    for (_, names) in &data_only_exports {
756        for n in names {
757            *occurrence_count.entry(n.as_str()).or_insert(0) += 1;
758        }
759    }
760
761    let mut out = String::from("// Generated by hyprstream-ts-codegen — DO NOT EDIT\n\n");
762    out.push_str("export { CapnpArena, CapnpReader } from './capnp';\n");
763    for name in all_names {
764        if client_names.contains(name) {
765            let pascal = to_pascal_case(name);
766            out.push_str(&format!("export {{ {pascal}Client }} from './{name}';\n"));
767            continue;
768        }
769
770        let exported = data_only_exports
771            .iter()
772            .find(|(n, _)| *n == name)
773            .map(|(_, names)| names.as_slice())
774            .unwrap_or_default();
775        let has_collision = exported
776            .iter()
777            .any(|n| occurrence_count.get(n.as_str()).copied().unwrap_or(0) > 1);
778
779        if !has_collision {
780            // No cross-module name collision — a plain wildcard re-export is safe.
781            out.push_str(&format!("export * from './{name}';\n"));
782            continue;
783        }
784
785        // At least one export from this module collides with another
786        // data-only module's export — enumerate every export explicitly,
787        // aliasing only the colliding ones, so tsc never sees an ambiguous
788        // wildcard re-export.
789        let module_prefix = to_pascal_case(name);
790        let items: Vec<String> = exported
791            .iter()
792            .map(|n| {
793                if occurrence_count.get(n.as_str()).copied().unwrap_or(0) > 1 {
794                    format!("{n} as {module_prefix}{n}")
795                } else {
796                    n.clone()
797                }
798            })
799            .collect();
800        if items.is_empty() {
801            // Nothing exported from this module (e.g. an empty schema) — no-op.
802            continue;
803        }
804        out.push_str(&format!(
805            "export {{ {} }} from './{name}';\n",
806            items.join(", ")
807        ));
808    }
809    out
810}
811
812#[cfg(test)]
813mod barrel_tests {
814    #![allow(clippy::expect_used, clippy::unwrap_used)]
815
816    use super::generate_index;
817
818    /// Two data-only modules that don't share any exported name keep the
819    /// cheap, plain `export *` re-export.
820    #[test]
821    fn no_collision_uses_plain_wildcard_export() {
822        let all_names = vec!["events".to_owned(), "streaming".to_owned()];
823        let client_names: Vec<String> = vec![];
824        let module_contents = vec![
825            (
826                "events".to_owned(),
827                "export interface EventEnvelope {\n  id: string;\n}\n".to_owned(),
828            ),
829            (
830                "streaming".to_owned(),
831                "export interface StreamInfo {\n  id: string;\n}\n".to_owned(),
832            ),
833        ];
834
835        let out = generate_index(&all_names, &client_names, &module_contents);
836
837        assert!(out.contains("export * from './events';"), "{out}");
838        assert!(out.contains("export * from './streaming';"), "{out}");
839    }
840
841    /// Two data-only modules that both export a struct with the same name (the
842    /// #725 "QoS" scenario) must never both emit a blind `export *` — every
843    /// module owning the colliding name switches to an explicit, aliased
844    /// export so tsc can never see an ambiguous re-export.
845    #[test]
846    fn colliding_export_name_is_aliased_per_module_not_silently_dropped() {
847        let all_names = vec!["events".to_owned(), "streaming".to_owned()];
848        let client_names: Vec<String> = vec![];
849        let module_contents = vec![
850            (
851                "events".to_owned(),
852                "export interface QoS {\n  retries: number;\n}\n\
853                 export interface EventEnvelope {\n  id: string;\n}\n"
854                    .to_owned(),
855            ),
856            (
857                "streaming".to_owned(),
858                "export interface QoS {\n  ackTimeoutMs: number;\n}\n\
859                 export interface StreamInfo {\n  id: string;\n}\n"
860                    .to_owned(),
861            ),
862        ];
863
864        let out = generate_index(&all_names, &client_names, &module_contents);
865
866        // Neither module may fall back to a blind wildcard export — that's
867        // exactly the silent-collision failure mode #725 reported.
868        assert!(!out.contains("export * from './events';"), "{out}");
869        assert!(!out.contains("export * from './streaming';"), "{out}");
870
871        // The colliding name is aliased per-module...
872        assert!(out.contains("QoS as EventsQoS"), "{out}");
873        assert!(out.contains("QoS as StreamingQoS"), "{out}");
874        // ...while the non-colliding names from each module are still
875        // re-exported (nothing gets dropped just because its sibling collided).
876        assert!(out.contains("EventEnvelope"), "{out}");
877        assert!(out.contains("StreamInfo"), "{out}");
878    }
879
880    /// `scan_exported_names` is the single source of truth the barrel
881    /// generator relies on — verify it picks up every emission shape used by
882    /// interfaces.rs / builders.rs / parsers.rs.
883    #[test]
884    fn scan_exported_names_finds_interfaces_types_and_functions() {
885        let content = "export interface Foo {\n  a: number;\n}\n\
886                        export type Bar =\n  | { variant: 'x'; data: undefined };\n\
887                        export function buildFoo(p: Foo): Uint8Array {\n  return new Uint8Array(0);\n}\n";
888        let names = super::scan_exported_names(content);
889        assert_eq!(names, vec!["Foo", "Bar", "buildFoo"]);
890    }
891}