Skip to main content

hyprstream_ts_codegen/ts_codegen/
parsers.rs

1//! Generate TypeScript response parser functions.
2//!
3//! For each service, generates a `parse{Service}Response` function that reads
4//! the response union discriminant and returns typed data.
5//!
6//! Scoped response variants (structs that themselves contain unions) are
7//! parsed recursively, returning nested `{ variant, data }` objects.
8
9use hyprstream_rpc_build::schema::types::{
10    FieldDef, FieldSection, ParsedSchema, ScopedClient, StructDef,
11};
12use hyprstream_rpc_build::util::{to_camel_case, to_pascal_case};
13
14use super::{bool_bit_index, capnp_to_ts_type, data_byte_offset, is_data_scalar};
15
16/// Generate response parser types and functions for a service.
17pub fn generate_parsers(out: &mut String, service_name: &str, schema: &ParsedSchema) {
18    let resp_struct = match &schema.response_struct {
19        Some(s) => s,
20        None => return,
21    };
22
23    let pascal = to_pascal_case(service_name);
24
25    let non_union_fields: Vec<&FieldDef> = resp_struct.non_union_fields().collect();
26
27    let disc_byte_off = resp_struct.discriminant_offset * 2;
28
29    // Build a map of factory_name → ScopedClient for scoped response detection
30    let scoped_map: Vec<(&str, &ScopedClient)> = schema
31        .scoped_clients
32        .iter()
33        .map(|sc| (sc.factory_name.as_str(), sc))
34        .collect();
35
36    // Response result type — a typed discriminated union when the response is a
37    // union envelope, so callers narrow on `result.variant`. Each arm mirrors the
38    // parser's per-variant `return` (shared non-union fields + `{ variant, data }`).
39    if resp_struct.has_union {
40        let shared_fields: Vec<String> = non_union_fields
41            .iter()
42            .map(|f| {
43                format!(
44                    "{}: {}",
45                    to_camel_case(&f.name),
46                    capnp_to_ts_type(&f.type_name)
47                )
48            })
49            .collect();
50        let arms: Vec<(String, String)> = schema
51            .response_variants
52            .iter()
53            .map(|v| {
54                let data_ty = resp_struct
55                    .fields
56                    .iter()
57                    .find(|f| f.name == v.name && f.discriminant_value != 0xFFFF)
58                    .map(super::union_variant_data_type)
59                    .unwrap_or_else(|| "unknown".to_owned());
60                (v.name.clone(), data_ty)
61            })
62            .collect();
63        super::emit_union_alias(
64            out,
65            &format!("{pascal}ResponseResult"),
66            &shared_fields,
67            &arms,
68        );
69    } else {
70        // Data-only response (no union) — plain interface, unchanged shape.
71        out.push_str(&format!("export interface {pascal}ResponseResult {{\n"));
72        for f in &non_union_fields {
73            out.push_str(&format!(
74                "  {}: {};\n",
75                to_camel_case(&f.name),
76                capnp_to_ts_type(&f.type_name)
77            ));
78        }
79        out.push_str("  variant: string;\n");
80        out.push_str("  data: unknown;\n");
81        out.push_str("}\n\n");
82    }
83
84    // Parser function
85    out.push_str(&format!(
86        "function parse{pascal}Response(bytes: Uint8Array): {pascal}ResponseResult {{\n"
87    ));
88    out.push_str(&format!(
89        "  const reader = new CapnpReader(bytes, {}, {});\n",
90        resp_struct.data_words, resp_struct.pointer_words
91    ));
92
93    for f in &non_union_fields {
94        emit_reader_field(out, "reader", f, &to_camel_case(&f.name), "  ", schema);
95    }
96
97    out.push_str(&format!(
98        "  const _disc = reader.getUint16({disc_byte_off});\n"
99    ));
100    out.push_str("  switch (_disc) {\n");
101
102    for variant in &schema.response_variants {
103        let variant_field = resp_struct
104            .fields
105            .iter()
106            .find(|f| f.name == variant.name && f.discriminant_value != 0xFFFF);
107
108        let disc_value = variant_field.map(|f| f.discriminant_value).unwrap_or(0);
109
110        out.push_str(&format!("    case {disc_value}: // {}\n", variant.name));
111
112        // Check if this variant is a scoped response (matches "{factory}Result")
113        let is_scoped = variant
114            .name
115            .strip_suffix("Result")
116            .and_then(|base| scoped_map.iter().find(|(name, _)| *name == base))
117            .map(|(_, sc)| *sc);
118
119        if let Some(sc) = is_scoped {
120            // Scoped response: read inner struct and parse its union
121            emit_scoped_response_parse(
122                out,
123                "reader",
124                variant_field,
125                sc,
126                schema,
127                &non_union_fields,
128                &variant.name,
129            );
130        } else if variant.type_name == "Void" {
131            emit_return(out, &non_union_fields, &variant.name, "undefined");
132        } else if variant.type_name == "Bool" {
133            if let Some(vf) = variant_field {
134                let byte_off = data_byte_offset(vf);
135                let bit = bool_bit_index(vf);
136                emit_return(
137                    out,
138                    &non_union_fields,
139                    &variant.name,
140                    &format!("reader.getBool({byte_off}, {bit})"),
141                );
142            }
143        } else if is_data_scalar(&variant.type_name) {
144            if let Some(vf) = variant_field {
145                let byte_off = data_byte_offset(vf);
146                let method = super::getter_method(&variant.type_name);
147                emit_return(
148                    out,
149                    &non_union_fields,
150                    &variant.name,
151                    &format!("reader.{method}({byte_off})"),
152                );
153            }
154        } else if variant.type_name == "Text" {
155            if let Some(vf) = variant_field {
156                emit_return(
157                    out,
158                    &non_union_fields,
159                    &variant.name,
160                    &format!("reader.getText({})", vf.slot_offset),
161                );
162            }
163        } else if variant.type_name == "Data" {
164            if let Some(vf) = variant_field {
165                emit_return(
166                    out,
167                    &non_union_fields,
168                    &variant.name,
169                    &format!("reader.getData({})", vf.slot_offset),
170                );
171            }
172        } else if let Some(inner) = super::extract_list_inner_type(&variant.type_name) {
173            if let Some(vf) = variant_field {
174                if let Some(method) = super::list_getter_method(inner) {
175                    emit_return(
176                        out,
177                        &non_union_fields,
178                        &variant.name,
179                        &format!("reader.{method}({})", vf.slot_offset),
180                    );
181                } else if let Some(nested_inner) = super::extract_list_inner_type(inner) {
182                    if let Some(method) = super::nested_list_getter_method(nested_inner) {
183                        emit_return(
184                            out,
185                            &non_union_fields,
186                            &variant.name,
187                            &format!("reader.{method}({})", vf.slot_offset),
188                        );
189                    } else {
190                        panic!(
191                            "ts_codegen: response variant `{}: {}` is a nested list of \
192                             `{nested_inner}` — not yet supported by the capnp.ts runtime \
193                             (only primitive-scalar List(List(_)) shapes are implemented) \
194                             (#758).",
195                            variant.name, variant.type_name
196                        );
197                    }
198                } else if let Some(sd) = schema.structs.iter().find(|s| s.name == inner) {
199                    emit_struct_list_read(
200                        out,
201                        "reader",
202                        vf,
203                        sd,
204                        &non_union_fields,
205                        &variant.name,
206                        schema,
207                    );
208                } else {
209                    panic!(
210                        "ts_codegen: response variant `{}: {}` references struct `{inner}`, \
211                         which was not found in the parsed schema — dangling reference, must \
212                         not silently degrade (#725).",
213                        variant.name, variant.type_name
214                    );
215                }
216            }
217        } else {
218            // Struct type
219            if let Some(vf) = variant_field {
220                let struct_def = schema.structs.iter().find(|s| s.name == variant.type_name);
221                if let Some(sd) = struct_def {
222                    emit_struct_read(
223                        out,
224                        "reader",
225                        vf,
226                        sd,
227                        &non_union_fields,
228                        &variant.name,
229                        schema,
230                    );
231                } else {
232                    emit_return(out, &non_union_fields, &variant.name, "null");
233                }
234            }
235        }
236    }
237
238    // Default case
239    let default_fields: Vec<String> = non_union_fields
240        .iter()
241        .map(|f| to_camel_case(&f.name))
242        .collect();
243    let fields_str = default_fields.join(", ");
244    let comma = if fields_str.is_empty() { "" } else { ", " };
245    out.push_str("    default:\n");
246    out.push_str(&format!(
247        "      return {{ {fields_str}{comma}variant: 'unknown' as const, data: null }};\n"
248    ));
249    out.push_str("  }\n");
250    out.push_str("}\n\n");
251}
252
253// ---------------------------------------------------------------------------
254// Standalone struct parsers
255// ---------------------------------------------------------------------------
256
257/// Generate standalone parser functions for all structs in a schema.
258///
259/// For union-bearing structs: `parse{StructName}(bytes): {StructName}Result`
260/// (discriminated union return with `{ variant, data }` fields).
261///
262/// For non-union structs: `parse{StructName}(bytes): StructName`
263/// (returns the struct interface directly).
264///
265/// Skips Option* wrapper structs and service request/response structs.
266pub fn generate_struct_parsers(out: &mut String, schema: &ParsedSchema) {
267    for sd in &schema.structs {
268        if sd.option_inner_type().is_some() {
269            continue;
270        }
271        // Skip service request/response structs (handled by generate_parsers)
272        if schema
273            .request_struct
274            .as_ref()
275            .is_some_and(|rs| rs.name == sd.name)
276            || schema
277                .response_struct
278                .as_ref()
279                .is_some_and(|rs| rs.name == sd.name)
280        {
281            continue;
282        }
283
284        if !sd.has_union {
285            generate_plain_struct_parser(out, sd, schema);
286            continue;
287        }
288
289        let non_union_fields: Vec<&FieldDef> = sd.non_union_fields().collect();
290        let union_fields: Vec<&FieldDef> = sd.union_fields().collect();
291
292        let disc_byte_off = sd.discriminant_offset * 2;
293
294        // Result type — typed discriminated union so callers narrow on `.variant`.
295        // One arm per union variant (data type mirroring the parser output) plus a
296        // shared block of non-union fields and the parser's `unknown` default arm.
297        let shared_fields = super::shared_union_fields(sd);
298        let arms: Vec<(String, String)> = union_fields
299            .iter()
300            .map(|f| (f.name.clone(), super::union_arm_data_type(sd, f)))
301            .collect();
302        super::emit_union_alias(out, &format!("{}Result", sd.name), &shared_fields, &arms);
303
304        // Parser function
305        out.push_str(&format!(
306            "export function parse{}(bytes: Uint8Array): {}Result {{\n",
307            sd.name, sd.name
308        ));
309        out.push_str(&format!(
310            "  const reader = new CapnpReader(bytes, {}, {});\n",
311            sd.data_words, sd.pointer_words
312        ));
313
314        // Read non-union fields
315        for f in &non_union_fields {
316            emit_reader_field(out, "reader", f, &to_camel_case(&f.name), "  ", schema);
317        }
318
319        // Read discriminant
320        out.push_str(&format!(
321            "  const _disc = reader.getUint16({disc_byte_off});\n"
322        ));
323        out.push_str("  switch (_disc) {\n");
324
325        for variant in &union_fields {
326            out.push_str(&format!(
327                "    case {}: // {}\n",
328                variant.discriminant_value, variant.name
329            ));
330
331            if let Some(leaves) = super::group_arm_leaves(sd, variant) {
332                let data = emit_group_arm_read("reader", leaves, schema);
333                emit_return(out, &non_union_fields, &variant.name, &data);
334            } else if variant.type_name == "Void" {
335                emit_return(out, &non_union_fields, &variant.name, "undefined");
336            } else if variant.type_name == "Bool" {
337                let byte_off = data_byte_offset(variant);
338                let bit = bool_bit_index(variant);
339                emit_return(
340                    out,
341                    &non_union_fields,
342                    &variant.name,
343                    &format!("reader.getBool({byte_off}, {bit})"),
344                );
345            } else if is_data_scalar(&variant.type_name) {
346                let byte_off = data_byte_offset(variant);
347                let method = super::getter_method(&variant.type_name);
348                emit_return(
349                    out,
350                    &non_union_fields,
351                    &variant.name,
352                    &format!("reader.{method}({byte_off})"),
353                );
354            } else if variant.type_name == "Text" {
355                emit_return(
356                    out,
357                    &non_union_fields,
358                    &variant.name,
359                    &format!("reader.getText({})", variant.slot_offset),
360                );
361            } else if variant.type_name == "Data" {
362                emit_return(
363                    out,
364                    &non_union_fields,
365                    &variant.name,
366                    &format!("reader.getData({})", variant.slot_offset),
367                );
368            } else if let Some(inner) = super::extract_list_inner_type(&variant.type_name) {
369                if let Some(method) = super::list_getter_method(inner) {
370                    emit_return(
371                        out,
372                        &non_union_fields,
373                        &variant.name,
374                        &format!("reader.{method}({})", variant.slot_offset),
375                    );
376                } else if let Some(nested_inner) = super::extract_list_inner_type(inner) {
377                    if let Some(method) = super::nested_list_getter_method(nested_inner) {
378                        emit_return(
379                            out,
380                            &non_union_fields,
381                            &variant.name,
382                            &format!("reader.{method}({})", variant.slot_offset),
383                        );
384                    } else {
385                        panic!(
386                            "ts_codegen: union arm `{}: {}` is a nested list of `{nested_inner}` \
387                             — not yet supported by the capnp.ts runtime (only \
388                             primitive-scalar List(List(_)) shapes are implemented) (#758).",
389                            variant.name, variant.type_name
390                        );
391                    }
392                } else if let Some(isd) = schema.structs.iter().find(|s| s.name == inner) {
393                    emit_struct_list_read(
394                        out,
395                        "reader",
396                        variant,
397                        isd,
398                        &non_union_fields,
399                        &variant.name,
400                        schema,
401                    );
402                } else {
403                    panic!(
404                        "ts_codegen: union arm `{}: {}` references struct `{inner}`, which \
405                         was not found in the parsed schema — dangling reference, must not \
406                         silently degrade (#725).",
407                        variant.name, variant.type_name
408                    );
409                }
410            } else {
411                // Struct type
412                if let Some(struct_def) =
413                    schema.structs.iter().find(|s| s.name == variant.type_name)
414                {
415                    emit_struct_read(
416                        out,
417                        "reader",
418                        variant,
419                        struct_def,
420                        &non_union_fields,
421                        &variant.name,
422                        schema,
423                    );
424                } else {
425                    emit_return(out, &non_union_fields, &variant.name, "null");
426                }
427            }
428        }
429
430        // Default case
431        let default_fields: Vec<String> = non_union_fields
432            .iter()
433            .map(|f| to_camel_case(&f.name))
434            .collect();
435        let fields_str = default_fields.join(", ");
436        let comma = if fields_str.is_empty() { "" } else { ", " };
437        out.push_str("    default:\n");
438        out.push_str(&format!(
439            "      return {{ {fields_str}{comma}variant: 'unknown' as const, data: null }};\n"
440        ));
441        out.push_str("  }\n");
442        out.push_str("}\n\n");
443    }
444}
445
446/// Generate a parser function for a non-union struct.
447///
448/// `export function parse{StructName}(bytes: Uint8Array): StructName`
449fn generate_plain_struct_parser(out: &mut String, sd: &StructDef, schema: &ParsedSchema) {
450    out.push_str(&format!(
451        "export function parse{}(bytes: Uint8Array): {} {{\n",
452        sd.name, sd.name
453    ));
454    out.push_str(&format!(
455        "  const reader = new CapnpReader(bytes, {}, {});\n",
456        sd.data_words, sd.pointer_words
457    ));
458
459    // Gensym counter: _f{n} locals are always valid identifiers regardless of field name.
460    // This avoids reserved-word collisions (function, arguments, ...) and name-capture
461    // bugs (a field named "reader" would shadow the CapnpReader local above).
462    let mut field_pairs: Vec<(String, String)> = Vec::new();
463    for (n, f) in sd.fields.iter().enumerate() {
464        let camel = to_camel_case(&f.name);
465        let local = format!("_f{n}");
466        emit_reader_field(out, "reader", f, &local, "  ", schema);
467        field_pairs.push((camel, local));
468    }
469
470    let props: Vec<String> = field_pairs
471        .iter()
472        .map(|(key, local)| format!("{key}: {local}"))
473        .collect();
474    out.push_str(&format!("  return {{ {} }};\n", props.join(", ")));
475    out.push_str("}\n\n");
476}
477
478/// Emit code to parse a scoped response variant (inner union within a struct).
479fn emit_scoped_response_parse(
480    out: &mut String,
481    reader_var: &str,
482    variant_field: Option<&FieldDef>,
483    sc: &ScopedClient,
484    schema: &ParsedSchema,
485    non_union_fields: &[&FieldDef],
486    variant_name: &str,
487) {
488    let Some(vf) = variant_field else {
489        emit_return(out, non_union_fields, variant_name, "null");
490        return;
491    };
492
493    // Find the inner response struct
494    let resp_variant_name = format!("{}Result", sc.factory_name);
495    let outer_resp_variant = schema
496        .response_variants
497        .iter()
498        .find(|v| v.name == resp_variant_name);
499    let inner_resp_type = outer_resp_variant
500        .map(|v| v.type_name.as_str())
501        .unwrap_or("");
502    let inner_resp_struct = schema.structs.iter().find(|s| s.name == inner_resp_type);
503
504    let Some(irs) = inner_resp_struct else {
505        emit_return(out, non_union_fields, variant_name, "null");
506        return;
507    };
508
509    out.push_str(&format!(
510        "    {{\n      const _inner = {reader_var}.getStruct({}, {}, {});\n",
511        vf.slot_offset, irs.data_words, irs.pointer_words
512    ));
513
514    let resp_fields: Vec<String> = non_union_fields
515        .iter()
516        .map(|f| to_camel_case(&f.name))
517        .collect();
518    let fields_str = resp_fields.join(", ");
519    let comma = if fields_str.is_empty() { "" } else { ", " };
520
521    out.push_str(&format!(
522        "      if (!_inner) return {{ {fields_str}{comma}variant: '{variant_name}', data: null }};\n"
523    ));
524
525    // Read inner discriminant
526    let inner_disc_byte_off = irs.discriminant_offset * 2;
527    out.push_str(&format!(
528        "      const _innerDisc = _inner.getUint16({inner_disc_byte_off});\n"
529    ));
530    out.push_str("      switch (_innerDisc) {\n");
531
532    for inner_variant in &sc.inner_response_variants {
533        let inner_field = irs
534            .fields
535            .iter()
536            .find(|f| f.name == inner_variant.name && f.discriminant_value != 0xFFFF);
537
538        let inner_disc_value = inner_field.map(|f| f.discriminant_value).unwrap_or(0);
539
540        out.push_str(&format!(
541            "        case {inner_disc_value}: // {}\n",
542            inner_variant.name
543        ));
544
545        let inner_data = emit_inner_variant_read(inner_field, &inner_variant.type_name, schema);
546
547        out.push_str(&format!(
548            "          return {{ {fields_str}{comma}variant: '{variant_name}', data: {{ variant: '{}', data: {inner_data} }} }};\n",
549            inner_variant.name
550        ));
551    }
552
553    // Handle nested scoped response variants by recursively parsing
554    for nc in &sc.nested_clients {
555        let nested_resp_name = format!("{}Result", nc.factory_name);
556
557        // Skip if already handled in inner_response_variants loop
558        if sc
559            .inner_response_variants
560            .iter()
561            .any(|v| v.name == nested_resp_name)
562        {
563            continue;
564        }
565
566        // Find the matching discriminant field
567        let nested_field = irs
568            .fields
569            .iter()
570            .find(|f| f.name == nested_resp_name && f.discriminant_value != 0xFFFF);
571
572        let Some(nf) = nested_field else { continue };
573
574        // Find the nested response struct to know its layout
575        let nested_resp_struct = schema.structs.iter().find(|s| s.name == nf.type_name);
576
577        out.push_str(&format!(
578            "        case {}: // {} (nested scope)\n",
579            nf.discriminant_value, nested_resp_name
580        ));
581
582        if let Some(nrs) = nested_resp_struct {
583            // Read the nested struct and recursively parse its union
584            out.push_str(&format!(
585                "        {{\n          const _nested = _inner.getStruct({}, {}, {});\n",
586                nf.slot_offset, nrs.data_words, nrs.pointer_words
587            ));
588            out.push_str(&format!(
589                "          if (!_nested) return {{ {fields_str}{comma}variant: '{variant_name}', data: {{ variant: '{}', data: null }} }};\n",
590                nested_resp_name
591            ));
592
593            // Read nested discriminant and switch
594            let nested_disc_byte_off = nrs.discriminant_offset * 2;
595            out.push_str(&format!(
596                "          const _nestedDisc = _nested.getUint16({nested_disc_byte_off});\n"
597            ));
598            out.push_str("          switch (_nestedDisc) {\n");
599
600            // Emit each variant of the nested response
601            for nv in &nc.inner_response_variants {
602                let nv_field = nrs
603                    .fields
604                    .iter()
605                    .find(|f| f.name == nv.name && f.discriminant_value != 0xFFFF);
606                let nv_disc = nv_field.map(|f| f.discriminant_value).unwrap_or(0);
607                let nv_data =
608                    emit_inner_variant_read_from("_nested", nv_field, &nv.type_name, schema, 0);
609                out.push_str(&format!("            case {nv_disc}: // {}\n", nv.name));
610                out.push_str(&format!(
611                    "              return {{ {fields_str}{comma}variant: '{variant_name}', data: {{ variant: '{}', data: {{ variant: '{}', data: {nv_data} }} }} }};\n",
612                    nested_resp_name, nv.name
613                ));
614            }
615
616            // Handle nested-nested clients (e.g., worktree → ctl)
617            for nnc in &nc.nested_clients {
618                let nn_resp_name = format!("{}Result", nnc.factory_name);
619                if nc
620                    .inner_response_variants
621                    .iter()
622                    .any(|v| v.name == nn_resp_name)
623                {
624                    continue;
625                }
626                let nn_field = nrs
627                    .fields
628                    .iter()
629                    .find(|f| f.name == nn_resp_name && f.discriminant_value != 0xFFFF);
630                let Some(nnf) = nn_field else { continue };
631                let nn_struct = schema.structs.iter().find(|s| s.name == nnf.type_name);
632
633                out.push_str(&format!(
634                    "            case {}: // {} (nested scope)\n",
635                    nnf.discriminant_value, nn_resp_name
636                ));
637
638                if let Some(nns) = nn_struct {
639                    out.push_str(&format!(
640                        "            {{\n              const _deep = _nested.getStruct({}, {}, {});\n",
641                        nnf.slot_offset, nns.data_words, nns.pointer_words
642                    ));
643                    out.push_str(&format!(
644                        "              if (!_deep) return {{ {fields_str}{comma}variant: '{variant_name}', data: {{ variant: '{}', data: {{ variant: '{}', data: null }} }} }};\n",
645                        nested_resp_name, nn_resp_name
646                    ));
647                    let nn_disc_off = nns.discriminant_offset * 2;
648                    out.push_str(&format!(
649                        "              const _deepDisc = _deep.getUint16({nn_disc_off});\n"
650                    ));
651                    out.push_str("              switch (_deepDisc) {\n");
652                    for nnv in &nnc.inner_response_variants {
653                        let nnv_field = nns
654                            .fields
655                            .iter()
656                            .find(|f| f.name == nnv.name && f.discriminant_value != 0xFFFF);
657                        let nnv_disc = nnv_field.map(|f| f.discriminant_value).unwrap_or(0);
658                        let nnv_data = emit_inner_variant_read_from(
659                            "_deep",
660                            nnv_field,
661                            &nnv.type_name,
662                            schema,
663                            0,
664                        );
665                        out.push_str(&format!(
666                            "                case {nnv_disc}: // {}\n",
667                            nnv.name
668                        ));
669                        out.push_str(&format!(
670                            "                  return {{ {fields_str}{comma}variant: '{variant_name}', data: {{ variant: '{}', data: {{ variant: '{}', data: {{ variant: '{}', data: {nnv_data} }} }} }} }};\n",
671                            nested_resp_name, nn_resp_name, nnv.name
672                        ));
673                    }
674                    out.push_str(&format!(
675                        "                default:\n                  return {{ {fields_str}{comma}variant: '{variant_name}', data: {{ variant: '{}', data: {{ variant: '{}', data: {{ variant: 'unknown', data: null }} }} }} }};\n",
676                        nested_resp_name, nn_resp_name
677                    ));
678                    out.push_str("              }\n");
679                    out.push_str("            }\n");
680                } else {
681                    out.push_str(&format!(
682                        "              return {{ {fields_str}{comma}variant: '{variant_name}', data: {{ variant: '{}', data: {{ variant: '{}', data: null }} }} }};\n",
683                        nested_resp_name, nn_resp_name
684                    ));
685                }
686            }
687
688            out.push_str(&format!(
689                "            default:\n              return {{ {fields_str}{comma}variant: '{variant_name}', data: {{ variant: '{}', data: {{ variant: 'unknown', data: null }} }} }};\n",
690                nested_resp_name
691            ));
692            out.push_str("          }\n");
693            out.push_str("        }\n");
694        } else {
695            // Can't find nested struct — fall back to null
696            out.push_str(&format!(
697                "          return {{ {fields_str}{comma}variant: '{variant_name}', data: {{ variant: '{}', data: null }} }};\n",
698                nested_resp_name
699            ));
700        }
701    }
702
703    out.push_str("        default:\n");
704    out.push_str(&format!(
705        "          return {{ {fields_str}{comma}variant: '{variant_name}', data: {{ variant: 'unknown', data: null }} }};\n"
706    ));
707    out.push_str("      }\n");
708    out.push_str("    }\n");
709}
710
711/// Generate an inline expression to read an inner variant's data.
712///
713/// `reader_var` is the variable name of the reader to use (e.g., "_inner", "_el").
714/// `depth` is threaded through to `emit_struct_pointer_expr` to avoid `_p{n}` TDZ collisions.
715fn emit_inner_variant_read_from(
716    reader_var: &str,
717    field: Option<&FieldDef>,
718    type_name: &str,
719    schema: &ParsedSchema,
720    depth: usize,
721) -> String {
722    let Some(f) = field else {
723        return "null".into();
724    };
725
726    match type_name {
727        "Void" => "undefined".into(),
728        "Bool" => {
729            let byte_off = data_byte_offset(f);
730            let bit = bool_bit_index(f);
731            format!("{reader_var}.getBool({byte_off}, {bit})")
732        }
733        "Text" => format!("{reader_var}.getText({})", f.slot_offset),
734        "Data" => format!("{reader_var}.getData({})", f.slot_offset),
735        t if is_data_scalar(t) => {
736            let byte_off = data_byte_offset(f);
737            let method = super::getter_method(type_name);
738            format!("{reader_var}.{method}({byte_off})")
739        }
740        t if t.starts_with("List(") => {
741            let inner = super::extract_list_inner_type(t).unwrap_or("");
742            if let Some(method) = super::list_getter_method(inner) {
743                format!("{reader_var}.{method}({})", f.slot_offset)
744            } else if let Some(nested_inner) = super::extract_list_inner_type(inner) {
745                if let Some(method) = super::nested_list_getter_method(nested_inner) {
746                    format!("{reader_var}.{method}({})", f.slot_offset)
747                } else {
748                    panic!(
749                        "ts_codegen: inner variant `{type_name}` is a nested list of \
750                         `{nested_inner}` — not yet supported by the capnp.ts runtime \
751                         (only primitive-scalar List(List(_)) shapes are implemented) (#758)."
752                    );
753                }
754            } else if let Some(sd) = schema.structs.iter().find(|s| s.name == inner) {
755                emit_struct_list_field_expr(reader_var, f.slot_offset, sd, schema)
756            } else {
757                panic!(
758                    "ts_codegen: inner variant `{type_name}` references struct `{inner}`, \
759                     which was not found in the parsed schema — dangling reference, must \
760                     not silently degrade (#725)."
761                );
762            }
763        }
764        _ => {
765            // Struct — read its fields as an object via getStruct
766            if let Some(sd) = schema.structs.iter().find(|s| s.name == type_name) {
767                emit_struct_pointer_expr(reader_var, f.slot_offset, sd, schema, depth)
768            } else {
769                "null".into()
770            }
771        }
772    }
773}
774
775/// Convenience wrapper using `_inner` as the reader variable (for scoped response parsing).
776fn emit_inner_variant_read(
777    field: Option<&FieldDef>,
778    type_name: &str,
779    schema: &ParsedSchema,
780) -> String {
781    emit_inner_variant_read_from("_inner", field, type_name, schema, 0)
782}
783
784// ---------------------------------------------------------------------------
785// List(Struct) helpers
786// ---------------------------------------------------------------------------
787
788/// Emit an inline IIFE that reads a struct pointer and returns an object literal.
789///
790/// Uses `_p{depth}` variable names to avoid temporal dead zone collisions in nested IIFEs.
791fn emit_struct_pointer_expr(
792    reader_var: &str,
793    slot: u32,
794    sd: &StructDef,
795    schema: &ParsedSchema,
796    depth: usize,
797) -> String {
798    if depth > 4 {
799        return "null".into(); // guard against hypothetical recursive schemas
800    }
801    let var_name = format!("_p{depth}");
802
803    if sd.has_union {
804        // Union struct pointer — generate discriminant switch inside an IIFE
805        let disc_byte_off = sd.discriminant_offset * 2;
806
807        let non_union_fields: Vec<&FieldDef> = sd.non_union_fields().collect();
808        let union_fields: Vec<&FieldDef> = sd.union_fields().collect();
809
810        let mut s = format!(
811            "(() => {{ const {var_name} = {reader_var}.getStruct({slot}, {}, {}); if (!{var_name}) return null;\n",
812            sd.data_words, sd.pointer_words
813        );
814
815        // Read non-union fields
816        let mut nuf_names = Vec::new();
817        for f in &non_union_fields {
818            let camel = to_camel_case(&f.name);
819            let read = emit_struct_element_field_read_inner(&var_name, f, schema, depth + 1);
820            s.push_str(&format!("  const {camel} = {read};\n"));
821            nuf_names.push(camel);
822        }
823
824        let nuf_str = nuf_names.join(", ");
825        let nuf_comma = if nuf_str.is_empty() { "" } else { ", " };
826
827        s.push_str(&format!(
828            "  const _disc = {var_name}.getUint16({disc_byte_off});\n"
829        ));
830        s.push_str("  switch (_disc) {\n");
831
832        for uf in &union_fields {
833            s.push_str(&format!("    case {}: {{\n", uf.discriminant_value));
834            let data_expr = if let Some(leaves) = super::group_arm_leaves(sd, uf) {
835                emit_group_arm_read(&var_name, leaves, schema)
836            } else {
837                emit_inner_variant_read_from(&var_name, Some(uf), &uf.type_name, schema, depth + 1)
838            };
839            s.push_str(&format!(
840                "      return {{ {nuf_str}{nuf_comma}variant: '{}' as const, data: {data_expr} }};\n",
841                uf.name
842            ));
843            s.push_str("    }\n");
844        }
845
846        s.push_str(&format!(
847            "    default: return {{ {nuf_str}{nuf_comma}variant: 'unknown' as const, data: null }};\n"
848        ));
849        s.push_str("  }\n");
850        s.push_str("})()");
851        s
852    } else {
853        let fields: Vec<String> = sd
854            .non_union_fields()
855            .map(|sf| {
856                let camel = to_camel_case(&sf.name);
857                let read = emit_struct_element_field_read_inner(&var_name, sf, schema, depth + 1);
858                format!("{camel}: {read}")
859            })
860            .collect();
861        format!(
862            "(() => {{ const {var_name} = {reader_var}.getStruct({slot}, {}, {}); return {var_name} ? {{ {} }} : null; }})()",
863            sd.data_words, sd.pointer_words, fields.join(", ")
864        )
865    }
866}
867
868/// Generate an inline read expression for a single struct field (thin wrapper).
869fn emit_struct_element_field_read(
870    reader_var: &str,
871    field: &FieldDef,
872    schema: &ParsedSchema,
873) -> String {
874    emit_struct_element_field_read_inner(reader_var, field, schema, 0)
875}
876
877/// Emit a read expression for a pointer-section field.
878///
879/// Handles: List(Text), List(Data), List(Struct), Struct, Text, Data.
880fn emit_pointer_read_expr(
881    reader_var: &str,
882    field: &FieldDef,
883    schema: &ParsedSchema,
884    depth: usize,
885) -> String {
886    match super::extract_list_inner_type(&field.type_name) {
887        Some(inner) => {
888            if let Some(method) = super::list_getter_method(inner) {
889                format!("{reader_var}.{method}({})", field.slot_offset)
890            } else if let Some(nested_inner) = super::extract_list_inner_type(inner) {
891                if let Some(method) = super::nested_list_getter_method(nested_inner) {
892                    format!("{reader_var}.{method}({})", field.slot_offset)
893                } else {
894                    panic!(
895                        "ts_codegen: field `{}: {}` is a nested list of `{nested_inner}` — \
896                         not yet supported by the capnp.ts runtime (only primitive-scalar \
897                         List(List(_)) shapes are implemented) (#758).",
898                        field.name, field.type_name
899                    );
900                }
901            } else if let Some(isd) = schema.structs.iter().find(|s| s.name == inner) {
902                emit_struct_list_field_expr(reader_var, field.slot_offset, isd, schema)
903            } else {
904                panic!(
905                    "ts_codegen: field `{}: {}` references struct `{inner}`, which was not \
906                     found in the parsed schema — dangling reference, must not silently \
907                     degrade to an empty array (#725).",
908                    field.name, field.type_name
909                );
910            }
911        }
912        None => {
913            // Non-list pointer: Struct, Text, Data, or unknown
914            if let Some(sd) = schema.structs.iter().find(|s| s.name == field.type_name) {
915                if let Some(inner_name) = sd.option_inner_type() {
916                    emit_option_read_expr(reader_var, field, sd, inner_name, schema)
917                } else {
918                    emit_struct_pointer_expr(reader_var, field.slot_offset, sd, schema, depth)
919                }
920            } else if field.type_name == "Text" || field.type_name == "Data" {
921                let method = super::getter_method(&field.type_name);
922                format!("{reader_var}.{method}({})", field.slot_offset)
923            } else {
924                // Unknown pointer type (AnyPointer, Interface, etc.)
925                "null".into()
926            }
927        }
928    }
929}
930
931/// Generate an inline read expression for a single struct field.
932/// Handles data scalars, pointers (Text, Data, List(Text), List(Struct), Struct), and groups.
933fn emit_struct_element_field_read_inner(
934    reader_var: &str,
935    field: &FieldDef,
936    schema: &ParsedSchema,
937    depth: usize,
938) -> String {
939    match field.section {
940        FieldSection::Data => {
941            if field.type_name == "Void" {
942                return "undefined".into();
943            }
944            let byte_off = data_byte_offset(field);
945            if field.type_name == "Bool" {
946                let bit = bool_bit_index(field);
947                format!("{reader_var}.getBool({byte_off}, {bit})")
948            } else if !super::is_data_scalar(&field.type_name) {
949                // Enum type — stored as UInt16 in data section
950                if let Some(ed) = schema.enums.iter().find(|e| e.name == field.type_name) {
951                    super::emit_enum_getter_expr(reader_var, byte_off, &field.type_name, ed)
952                } else {
953                    format!("{reader_var}.getUint16({byte_off})")
954                }
955            } else {
956                let method = super::getter_method(&field.type_name);
957                format!("{reader_var}.{method}({byte_off})")
958            }
959        }
960        FieldSection::Pointer => emit_pointer_read_expr(reader_var, field, schema, depth),
961        FieldSection::Group => "undefined".into(),
962    }
963}
964
965/// Read an inline union `group` arm's leaf fields into an object literal
966/// matching its synthesized interface: `{ leaf1: <read>, leaf2: <read> }`.
967///
968/// The leaves live in the ENCLOSING struct's sections, so they read from the
969/// same `reader_var` at their own slot offsets (a group has no own pointer).
970fn emit_group_arm_read(reader_var: &str, leaves: &[FieldDef], schema: &ParsedSchema) -> String {
971    let parts: Vec<String> = leaves
972        .iter()
973        .map(|leaf| {
974            let camel = to_camel_case(&leaf.name);
975            let read = emit_struct_element_field_read_inner(reader_var, leaf, schema, 0);
976            format!("{camel}: {read}")
977        })
978        .collect();
979    format!("{{ {} }}", parts.join(", "))
980}
981
982/// Generate an inline expression that reads a List(Struct) and maps elements to objects.
983///
984/// For non-union structs: maps to `{ field1, field2, ... }`.
985/// For union structs: maps to `{ variant, data, ...nonUnionFields }` via discriminant switch.
986fn emit_struct_list_field_expr(
987    reader_var: &str,
988    slot: u32,
989    sd: &StructDef,
990    schema: &ParsedSchema,
991) -> String {
992    if sd.has_union {
993        return emit_union_struct_list_field_expr(reader_var, slot, sd, schema);
994    }
995
996    let fields: Vec<String> = sd
997        .non_union_fields()
998        .map(|f| {
999            let camel = to_camel_case(&f.name);
1000            let read = emit_struct_element_field_read_inner("_el", f, schema, 0);
1001            format!("{camel}: {read}")
1002        })
1003        .collect();
1004    format!(
1005        "{reader_var}.getStructList({}, {}, {}).map(_el => ({{ {} }}))",
1006        slot,
1007        sd.data_words,
1008        sd.pointer_words,
1009        fields.join(", ")
1010    )
1011}
1012
1013/// Generate a multi-line expression for reading a List(UnionStruct).
1014///
1015/// Each element is parsed as `{ variant: string; data: unknown }` with optional
1016/// non-union fields (for mixed structs like TuiFrame).
1017fn emit_union_struct_list_field_expr(
1018    reader_var: &str,
1019    slot: u32,
1020    sd: &StructDef,
1021    schema: &ParsedSchema,
1022) -> String {
1023    let disc_byte_off = sd.discriminant_offset * 2;
1024
1025    let non_union_fields: Vec<&FieldDef> = sd.non_union_fields().collect();
1026    let union_fields: Vec<&FieldDef> = sd.union_fields().collect();
1027
1028    let mut s = format!(
1029        "{reader_var}.getStructList({slot}, {}, {}).map(_el => {{\n",
1030        sd.data_words, sd.pointer_words
1031    );
1032
1033    // Read non-union fields
1034    let mut nuf_names = Vec::new();
1035    for f in &non_union_fields {
1036        let camel = to_camel_case(&f.name);
1037        let read = emit_struct_element_field_read_inner("_el", f, schema, 0);
1038        s.push_str(&format!("    const {camel} = {read};\n"));
1039        nuf_names.push(camel);
1040    }
1041
1042    let nuf_str = nuf_names.join(", ");
1043    let nuf_comma = if nuf_str.is_empty() { "" } else { ", " };
1044
1045    s.push_str(&format!(
1046        "    const _disc = _el.getUint16({disc_byte_off});\n"
1047    ));
1048    s.push_str("    switch (_disc) {\n");
1049
1050    for uf in &union_fields {
1051        s.push_str(&format!(
1052            "      case {}: // {}\n",
1053            uf.discriminant_value, uf.name
1054        ));
1055        let data_expr = if let Some(leaves) = super::group_arm_leaves(sd, uf) {
1056            emit_group_arm_read("_el", leaves, schema)
1057        } else {
1058            emit_inner_variant_read_from("_el", Some(uf), &uf.type_name, schema, 0)
1059        };
1060        // `as const` narrows the literal so the mapped array types as the typed
1061        // discriminated union (e.g. StreamPayload[]) rather than widening to
1062        // `{ variant: string; ... }[]`.
1063        s.push_str(&format!(
1064            "        return {{ {nuf_str}{nuf_comma}variant: '{}' as const, data: {data_expr} }};\n",
1065            uf.name
1066        ));
1067    }
1068
1069    s.push_str(&format!(
1070        "      default:\n        return {{ {nuf_str}{nuf_comma}variant: 'unknown' as const, data: null }};\n"
1071    ));
1072    s.push_str("    }\n");
1073    s.push_str("  })");
1074    s
1075}
1076
1077/// Emit a top-level List(Struct) variant read wrapped in a block.
1078fn emit_struct_list_read(
1079    out: &mut String,
1080    reader_var: &str,
1081    ptr_field: &FieldDef,
1082    struct_def: &StructDef,
1083    non_union_fields: &[&FieldDef],
1084    variant_name: &str,
1085    schema: &ParsedSchema,
1086) {
1087    let expr = emit_struct_list_field_expr(reader_var, ptr_field.slot_offset, struct_def, schema);
1088    out.push_str(&format!("    {{\n      const _items = {expr};\n"));
1089    emit_return(out, non_union_fields, variant_name, "_items");
1090    out.push_str("    }\n");
1091}
1092
1093// ---------------------------------------------------------------------------
1094// Helpers
1095// ---------------------------------------------------------------------------
1096
1097fn emit_reader_field(
1098    out: &mut String,
1099    reader_var: &str,
1100    field: &FieldDef,
1101    local_name: &str,
1102    indent: &str,
1103    schema: &ParsedSchema,
1104) {
1105    match field.section {
1106        FieldSection::Data => {
1107            if field.type_name == "Void" {
1108                out.push_str(&format!("{indent}const {local_name} = undefined;\n"));
1109                return;
1110            }
1111            let byte_off = data_byte_offset(field);
1112            if field.type_name == "Bool" {
1113                let bit = bool_bit_index(field);
1114                out.push_str(&format!(
1115                    "{indent}const {local_name} = {reader_var}.getBool({byte_off}, {bit});\n"
1116                ));
1117            } else if !super::is_data_scalar(&field.type_name) {
1118                // Enum type — stored as UInt16 in data section
1119                if let Some(ed) = schema.enums.iter().find(|e| e.name == field.type_name) {
1120                    let expr =
1121                        super::emit_enum_getter_expr(reader_var, byte_off, &field.type_name, ed);
1122                    out.push_str(&format!("{indent}const {local_name} = {expr};\n"));
1123                } else {
1124                    out.push_str(&format!(
1125                        "{indent}const {local_name} = {reader_var}.getUint16({byte_off});\n"
1126                    ));
1127                }
1128            } else {
1129                let method = super::getter_method(&field.type_name);
1130                out.push_str(&format!(
1131                    "{indent}const {local_name} = {reader_var}.{method}({byte_off});\n"
1132                ));
1133            }
1134        }
1135        FieldSection::Pointer => {
1136            let read_expr = emit_pointer_read_expr(reader_var, field, schema, 0);
1137            out.push_str(&format!("{indent}const {local_name} = {read_expr};\n"));
1138        }
1139        FieldSection::Group => {
1140            out.push_str(&format!(
1141                "{indent}const {local_name} = undefined; // group\n"
1142            ));
1143        }
1144    }
1145}
1146
1147fn emit_return(
1148    out: &mut String,
1149    non_union_fields: &[&FieldDef],
1150    variant_name: &str,
1151    data_expr: &str,
1152) {
1153    let fields: Vec<String> = non_union_fields
1154        .iter()
1155        .map(|f| to_camel_case(&f.name))
1156        .collect();
1157    let fields_str = fields.join(", ");
1158    let comma = if fields_str.is_empty() { "" } else { ", " };
1159    // `as const` narrows the discriminant literal so the return matches the
1160    // corresponding arm of the typed `…Result` discriminated union.
1161    out.push_str(&format!(
1162        "      return {{ {fields_str}{comma}variant: '{variant_name}' as const, data: {data_expr} }};\n"
1163    ));
1164}
1165
1166fn emit_struct_read(
1167    out: &mut String,
1168    reader_var: &str,
1169    ptr_field: &FieldDef,
1170    struct_def: &StructDef,
1171    non_union_fields: &[&FieldDef],
1172    variant_name: &str,
1173    schema: &ParsedSchema,
1174) {
1175    out.push_str("    {\n");
1176
1177    if super::emits_union_alias(schema, struct_def) {
1178        // Union-having payload: parse the discriminated union (shared named
1179        // fields + per-variant data + unknown fallback) via the same IIFE the
1180        // scoped parsers use. A named-fields-only read would silently drop the
1181        // inner union — emitting `{}` for pure union envelopes — and fail the
1182        // declared alias type (#1616).
1183        let expr =
1184            emit_struct_pointer_expr(reader_var, ptr_field.slot_offset, struct_def, schema, 0);
1185        out.push_str(&format!("      const _data = {expr};\n"));
1186    } else {
1187        out.push_str(&format!(
1188            "      const _s = {reader_var}.getStruct({}, {}, {});\n",
1189            ptr_field.slot_offset, struct_def.data_words, struct_def.pointer_words
1190        ));
1191
1192        let visible_fields: Vec<&FieldDef> = struct_def.non_union_fields().collect();
1193
1194        out.push_str("      const _data = _s ? {\n");
1195        for sf in &visible_fields {
1196            let camel = to_camel_case(&sf.name);
1197            let read_expr = emit_struct_element_field_read("_s", sf, schema);
1198            out.push_str(&format!("        {camel}: {read_expr},\n"));
1199        }
1200        out.push_str("      } : null;\n");
1201    }
1202
1203    let response_fields: Vec<String> = non_union_fields
1204        .iter()
1205        .map(|f| to_camel_case(&f.name))
1206        .collect();
1207    let fields_str = response_fields.join(", ");
1208    let comma = if fields_str.is_empty() { "" } else { ", " };
1209    out.push_str(&format!(
1210        "      return {{ {fields_str}{comma}variant: '{variant_name}', data: _data }};\n"
1211    ));
1212    out.push_str("    }\n");
1213}
1214
1215/// Generate an inline expression that reads an Option* wrapper struct pointer.
1216///
1217/// Returns `T | undefined`: reads the struct pointer, checks the discriminant,
1218/// and returns the inner value if discriminant == 1 (some), else `undefined`.
1219fn emit_option_read_expr(
1220    reader_var: &str,
1221    field: &FieldDef,
1222    opt_struct: &StructDef,
1223    inner_type_name: &str,
1224    schema: &ParsedSchema,
1225) -> String {
1226    let disc_byte_off = opt_struct.discriminant_offset * 2;
1227
1228    let read_val = if inner_type_name == "Text" {
1229        "_optR.getText(0)".to_owned()
1230    } else if inner_type_name == "Data" {
1231        "_optR.getData(0)".to_owned()
1232    } else {
1233        // Data-section scalar or enum: find the 'some' field to get its byte offset
1234        let some_field = opt_struct.fields.iter().find(|f| f.name == "some");
1235        if let Some(sf) = some_field {
1236            let some_byte_off = super::data_byte_offset(sf);
1237            // Enum types are stored as UInt16 — generate array lookup + cast
1238            if let Some(ed) = schema.enums.iter().find(|e| e.name == inner_type_name) {
1239                super::emit_enum_getter_expr("_optR", some_byte_off, inner_type_name, ed)
1240            } else if inner_type_name == "Bool" {
1241                let bit = super::bool_bit_index(sf);
1242                format!("_optR.getBool({some_byte_off}, {bit})")
1243            } else {
1244                let getter = super::getter_method(inner_type_name);
1245                format!("_optR.{getter}({some_byte_off})")
1246            }
1247        } else {
1248            "undefined".to_owned()
1249        }
1250    };
1251
1252    format!(
1253        "(() => {{ const _optR = {reader_var}.getStruct({}, {}, {}); \
1254         if (!_optR) return undefined; \
1255         return _optR.getUint16({disc_byte_off}) === 1 ? {read_val} : undefined; }})()",
1256        field.slot_offset, opt_struct.data_words, opt_struct.pointer_words
1257    )
1258}
1259
1260#[cfg(test)]
1261mod tests {
1262    #![allow(clippy::expect_used, clippy::unwrap_used)]
1263
1264    use std::path::Path;
1265
1266    use hyprstream_rpc_build::schema::parse_from_cgr_path;
1267    use hyprstream_rpc_build::schema::types::ParsedSchema;
1268
1269    /// A union struct with a shared non-union field plus Void / Text / scalar arms.
1270    const UNION_SCHEMA: &str = r#"
1271@0xd00dfeedd00dfeed;
1272
1273struct Payload {
1274  seq @0 :UInt32;
1275  union {
1276    none @1 :Void;
1277    text @2 :Text;
1278    count @3 :UInt64;
1279  }
1280}
1281"#;
1282
1283    /// A service-shaped schema: `{Pascal}Request`/`{Pascal}Response` unions so the
1284    /// CGR reader populates `response_struct` and the top-level `generate_parsers`
1285    /// path runs.
1286    const SERVICE_SCHEMA: &str = r#"
1287@0xbeefcafebeefcafe;
1288
1289# Mandatory scope (S3, #547), mandatory dispatch pair (v16 §6, WS-D), and
1290# mandatory mutation semantics (v16 §4.8/§6.1): a method with no `$scope` or
1291# with neither `$dispatchMac`/`$dispatchPublic` is a build error, and every
1292# non-read scoped leaf must declare `$mutationSemantics`. Minimal local
1293# annotations mirror the real annotations.capnp shapes for this fixture.
1294enum ScopeAction {
1295  query @0;
1296  write @1;
1297}
1298annotation scope(field) :ScopeAction;
1299annotation dispatchMac(field) :Text;
1300annotation mutationSemantics(field) :Text;
1301
1302struct PayloadRequest {
1303  union {
1304    ping @0 :Void $scope(query) $dispatchMac("internal:pq-hybrid");
1305    # A synthetic pure echo performs no durable application effect, so a
1306    # repeated call converges — the `naturally-idempotent` class.
1307    echo @1 :Text $scope(write) $dispatchMac("internal:pq-hybrid") $mutationSemantics("naturally-idempotent");
1308  }
1309}
1310
1311struct PayloadResponse {
1312  seq @0 :UInt32;
1313  union {
1314    ok @1 :Text;
1315    fail @2 :UInt64;
1316  }
1317}
1318"#;
1319
1320    /// Compile `schema_src` to a CGR keyed on `name` and parse it. Uses a
1321    /// per-(pid, name) temp dir so parallel tests don't collide.
1322    fn parse_schema(name: &str, schema_src: &str) -> ParsedSchema {
1323        let tmp = std::env::temp_dir().join(format!("hyprstream_ts_{name}_{}", std::process::id()));
1324        std::fs::create_dir_all(&tmp).expect("create temp dir");
1325
1326        let capnp_path = tmp.join(format!("{name}.capnp"));
1327        std::fs::write(&capnp_path, schema_src).expect("write capnp");
1328
1329        let cgr_path = tmp.join(format!("{name}.cgr"));
1330        capnpc::CompilerCommand::new()
1331            .src_prefix(&tmp)
1332            .file(&capnp_path)
1333            .raw_code_generator_request_path(&cgr_path)
1334            .run()
1335            .expect("compile capnp to CGR");
1336
1337        let parsed = parse_from_cgr_path(Path::new(&cgr_path), name).expect("parse CGR");
1338        let _ = std::fs::remove_dir_all(&tmp);
1339        parsed
1340    }
1341
1342    /// [`parse_schema`], but returning the pipeline's own parse error so the
1343    /// schema-gate rejection boundaries themselves are testable.
1344    fn try_parse_schema(name: &str, schema_src: &str) -> Result<ParsedSchema, String> {
1345        let tmp = std::env::temp_dir().join(format!("hyprstream_ts_{name}_{}", std::process::id()));
1346        std::fs::create_dir_all(&tmp).expect("create temp dir");
1347
1348        let capnp_path = tmp.join(format!("{name}.capnp"));
1349        std::fs::write(&capnp_path, schema_src).expect("write capnp");
1350
1351        let cgr_path = tmp.join(format!("{name}.cgr"));
1352        capnpc::CompilerCommand::new()
1353            .src_prefix(&tmp)
1354            .file(&capnp_path)
1355            .raw_code_generator_request_path(&cgr_path)
1356            .run()
1357            .expect("compile capnp to CGR");
1358
1359        let parsed = parse_from_cgr_path(Path::new(&cgr_path), name);
1360        let _ = std::fs::remove_dir_all(&tmp);
1361        parsed
1362    }
1363
1364    #[test]
1365    fn struct_parser_emits_typed_discriminated_union() {
1366        let schema = parse_schema("structfix", UNION_SCHEMA);
1367        let mut out = String::new();
1368        super::generate_struct_parsers(&mut out, &schema);
1369
1370        // The result type must be a typed discriminated union — NOT the old
1371        // `interface … { variant: string; data: unknown }` stub.
1372        assert!(
1373            out.contains("export type PayloadResult ="),
1374            "expected a typed union alias, got:\n{out}"
1375        );
1376        assert!(
1377            !out.contains("variant: string;"),
1378            "must not emit the degenerate `variant: string` stub:\n{out}"
1379        );
1380        assert!(
1381            !out.contains("data: unknown;"),
1382            "must not emit the degenerate `data: unknown` stub:\n{out}"
1383        );
1384
1385        // Each arm carries the shared non-union field and a typed `data` slot.
1386        assert!(
1387            out.contains("| { seq: number; variant: 'none'; data: undefined }"),
1388            "Void arm shape wrong:\n{out}"
1389        );
1390        assert!(
1391            out.contains("| { seq: number; variant: 'text'; data: string }"),
1392            "Text arm shape wrong:\n{out}"
1393        );
1394        assert!(
1395            out.contains("| { seq: number; variant: 'count'; data: bigint }"),
1396            "scalar arm shape wrong:\n{out}"
1397        );
1398        // Plus the parser's default `unknown` arm.
1399        assert!(
1400            out.contains("| { seq: number; variant: 'unknown'; data: null };"),
1401            "fallback arm shape wrong:\n{out}"
1402        );
1403
1404        // Parser `return`s narrow the discriminant with `as const` so they match
1405        // the union arms.
1406        assert!(
1407            out.contains("variant: 'text' as const"),
1408            "variant return missing `as const`:\n{out}"
1409        );
1410        assert!(
1411            out.contains("variant: 'unknown' as const"),
1412            "default return missing `as const`:\n{out}"
1413        );
1414    }
1415
1416    #[test]
1417    fn top_level_response_parser_emits_typed_discriminated_union() {
1418        let schema = parse_schema("payload", SERVICE_SCHEMA);
1419        let mut out = String::new();
1420        super::generate_parsers(&mut out, "payload", &schema);
1421
1422        // Top-level `{Service}ResponseResult` is now a typed union, not the
1423        // `interface … { variant: string; data: unknown }` stub.
1424        assert!(
1425            out.contains("export type PayloadResponseResult ="),
1426            "expected a typed union alias, got:\n{out}"
1427        );
1428        assert!(
1429            !out.contains("variant: string;"),
1430            "must not emit the degenerate `variant: string` stub:\n{out}"
1431        );
1432        assert!(
1433            !out.contains("data: unknown;"),
1434            "must not emit the degenerate `data: unknown` stub:\n{out}"
1435        );
1436        assert!(
1437            out.contains("| { seq: number; variant: 'ok'; data: string }"),
1438            "Text arm shape wrong:\n{out}"
1439        );
1440        assert!(
1441            out.contains("| { seq: number; variant: 'fail'; data: bigint }"),
1442            "scalar arm shape wrong:\n{out}"
1443        );
1444        assert!(
1445            out.contains("| { seq: number; variant: 'unknown'; data: null };"),
1446            "fallback arm shape wrong:\n{out}"
1447        );
1448        assert!(
1449            out.contains("variant: 'ok' as const"),
1450            "variant return missing `as const`:\n{out}"
1451        );
1452    }
1453
1454    /// P2 (`PRRT_kwDONmv2Pc6gGRV2`) pipeline fixture: a nonread selector whose
1455    /// payload is a local pure union. The actual schema gate (`parse_from_cgr`
1456    /// → `validate_mandatory_mutation_policy`) accepts the selector-level
1457    /// `$mutationSemantics` — this pins that acceptance and the verbatim
1458    /// extraction the derive's leaf walk inherits down to each descendant
1459    /// leaf (the inheritance itself is pinned in hyprstream-rpc-derive's
1460    /// `mutation_semantics_inherits_through_a_hand_dispatched_selector`).
1461    const PURE_UNION_SELECTOR_SCHEMA: &str = r#"
1462@0xe5c1ec70e5e1e57a;
1463
1464enum ScopeAction {
1465  query @0;
1466  write @1;
1467}
1468annotation scope(field) :ScopeAction;
1469annotation scopeExempt(field) :Text;
1470annotation dispatchMac(field) :Text;
1471annotation dispatchPublic(field) :Text;
1472annotation mutationSemantics(field) :Text;
1473
1474struct BatchOps {
1475  union {
1476    put @0 :Text;
1477    clear @1 :Void;
1478  }
1479}
1480
1481struct PipelineRequest {
1482  union {
1483    batch @0 :BatchOps $scope(write) $dispatchMac("internal:pq-hybrid") $mutationSemantics("transaction-ledger-required");
1484    ping @1 :Void $scope(query) $dispatchMac("internal:pq-hybrid");
1485    health @2 :Void $scopeExempt("unauthenticated liveness read") $dispatchPublic("unauthenticated liveness read for the load balancer");
1486  }
1487}
1488
1489struct PipelineResponse {
1490  union {
1491    ok @0 :Void;
1492    fail @1 :Text;
1493  }
1494}
1495"#;
1496
1497    #[test]
1498    fn pure_union_selector_mutation_metadata_passes_the_schema_gate() {
1499        let schema = parse_schema("pipeline", PURE_UNION_SELECTOR_SCHEMA);
1500        let batch = schema
1501            .request_variants
1502            .iter()
1503            .find(|v| v.name == "batch")
1504            .expect("batch variant present");
1505        assert_eq!(batch.scope, "write");
1506        assert_eq!(
1507            batch.mutation_semantics, "transaction-ledger-required",
1508            "the selector-level declaration must be extracted verbatim"
1509        );
1510        let health = schema
1511            .request_variants
1512            .iter()
1513            .find(|v| v.name == "health")
1514            .expect("health variant present");
1515        assert_eq!(
1516            health.dispatch_public, "unauthenticated liveness read for the load balancer",
1517            "the public reason is recorded exactly as declared"
1518        );
1519    }
1520
1521    /// The CGR path must retain arm-local metadata and the fact that an
1522    /// annotation exists.  The unannotated sibling inherits the selector's
1523    /// MAC/effect policy, while the local arm overrides the inherited values.
1524    #[test]
1525    fn pure_union_arms_preserve_local_overrides_and_presence() {
1526        let schema = parse_schema(
1527            "armmetadata",
1528            r#"@0x9a1b2c3d4e5f6071;
1529
1530enum ScopeAction { query @0; write @1; }
1531annotation scope(field) :ScopeAction;
1532annotation dispatchMac(field) :Text;
1533annotation dispatchPublic(field) :Text;
1534annotation mutationSemantics(field) :Text;
1535
1536struct BatchOps {
1537  union {
1538    put @0 :Text $dispatchMac("internal:pq-hybrid") $mutationSemantics("naturally-idempotent");
1539    clear @1 :Void;
1540  }
1541}
1542struct ArmmetadataRequest {
1543  union {
1544    batch @0 :BatchOps $scope(write) $dispatchMac("secret:pq-hybrid") $mutationSemantics("transaction-ledger-required");
1545    status @1 :Void $scope(query) $dispatchMac("internal:pq-hybrid");
1546  }
1547}
1548struct ArmmetadataResponse { union { ok @0 :Void; other @1 :Void; } }
1549"#,
1550        );
1551        let batch = schema
1552            .structs
1553            .iter()
1554            .find(|s| s.name == "BatchOps")
1555            .expect("real CGR retains local pure union");
1556        let put = &batch.union_arms[0];
1557        assert!(put.dispatch_mac_present && put.mutation_semantics_present);
1558        assert_eq!(put.dispatch_mac, "internal:pq-hybrid");
1559        let clear = &batch.union_arms[1];
1560        assert!(!clear.dispatch_mac_present && !clear.mutation_semantics_present);
1561        let selector = &schema.request_variants[0];
1562        assert_eq!(selector.dispatch_mac, "secret:pq-hybrid");
1563        assert_eq!(selector.mutation_semantics, "transaction-ledger-required");
1564    }
1565
1566    #[test]
1567    fn pure_union_cgr_rejects_invalid_mac_both_and_explicit_empty_policy() {
1568        let invalid = r#"@0x9a1b2c3d4e5f6072;
1569enum ScopeAction { query @0; write @1; }
1570annotation scope(field) :ScopeAction;
1571annotation dispatchMac(field) :Text;
1572annotation mutationSemantics(field) :Text;
1573struct Ops { union { bad @0 :Void $dispatchMac("not-a-mac"); good @1 :Void $dispatchMac("internal:pq-hybrid"); } }
1574struct InvalidRequest { union { run @0 :Ops $scope(query) $dispatchMac("internal:pq-hybrid"); other @1 :Void $scope(query) $dispatchMac("internal:pq-hybrid"); } }
1575struct InvalidResponse { union { ok @0 :Void; other @1 :Void; } }
1576"#;
1577        assert!(try_parse_schema("invalid", invalid)
1578            .unwrap_err()
1579            .contains("dispatchMac"));
1580
1581        let both = r#"@0x9a1b2c3d4e5f6074;
1582enum ScopeAction { query @0; write @1; }
1583annotation scope(field) :ScopeAction;
1584annotation dispatchMac(field) :Text;
1585annotation dispatchPublic(field) :Text;
1586struct Ops { union { bad @0 :Void $dispatchMac("internal:pq-hybrid"); good @1 :Void $dispatchMac("internal:pq-hybrid"); } }
1587struct BothRequest { union { run @0 :Ops $scope(query) $dispatchMac("internal:pq-hybrid") $dispatchPublic("reason"); other @1 :Void $scope(query) $dispatchMac("internal:pq-hybrid"); } }
1588struct BothResponse { union { ok @0 :Void; other @1 :Void; } }
1589"#;
1590        assert!(try_parse_schema("both", both).unwrap_err().contains("BOTH"));
1591
1592        let empty = r#"@0x9a1b2c3d4e5f6073;
1593enum ScopeAction { query @0; write @1; }
1594annotation scope(field) :ScopeAction;
1595annotation dispatchMac(field) :Text;
1596annotation mutationSemantics(field) :Text;
1597struct Ops { union { bad @0 :Void $mutationSemantics(""); good @1 :Void $mutationSemantics("naturally-idempotent"); } }
1598struct EmptyRequest { union { run @0 :Ops $scope(write) $dispatchMac("internal:pq-hybrid"); other @1 :Void $scope(query) $dispatchMac("internal:pq-hybrid"); } }
1599struct EmptyResponse { union { ok @0 :Void; other @1 :Void; } }
1600"#;
1601        assert!(try_parse_schema("empty", empty)
1602            .unwrap_err()
1603            .contains("mutationSemantics"));
1604    }
1605
1606    /// Recursive pure-union selectors must validate their own declarations
1607    /// before a valid grandchild can shadow them. This uses the complete
1608    /// capnpc -> CGR -> schema-gate path rather than constructing metadata.
1609    #[test]
1610    fn recursive_selectors_validate_local_declarations_before_inheritance() {
1611        fn schema(top: &str, nested: &str, top_mutation: &str) -> String {
1612            format!(
1613                r#"@0x91a2b3c4d5e6f701;
1614
1615enum ScopeAction {{ query @0; write @1; }}
1616annotation scope(field) :ScopeAction;
1617annotation scopeExempt(field) :Text;
1618annotation dispatchMac(field) :Text;
1619annotation dispatchPublic(field) :Text;
1620annotation mutationSemantics(field) :Text;
1621
1622struct Inner {{
1623  union {{
1624    first @0 :Void $dispatchMac("internal:pq-hybrid") $mutationSemantics("naturally-idempotent");
1625    second @1 :Void $dispatchMac("internal:pq-hybrid") $mutationSemantics("naturally-idempotent");
1626  }}
1627}}
1628struct Outer {{
1629  union {{
1630    inner @0 :Inner {nested}
1631    sibling @1 :Void $dispatchMac("internal:pq-hybrid") $mutationSemantics("naturally-idempotent");
1632  }}
1633}}
1634struct RecursiveRequest {{
1635  union {{
1636    route @0 :Outer $scope(write) $dispatchMac("{top}") $mutationSemantics("{top_mutation}");
1637    health @1 :Void $scope(query) $dispatchMac("internal:pq-hybrid");
1638  }}
1639}}
1640struct RecursiveResponse {{ union {{ ok @0 :Void; other @1 :Void; }} }}
1641"#,
1642                nested = nested,
1643                top = top,
1644                top_mutation = top_mutation,
1645            )
1646        }
1647
1648        let top_bad_mac = schema(
1649            "not-a-mac",
1650            " $dispatchMac(\"internal:pq-hybrid\") $mutationSemantics(\"naturally-idempotent\");",
1651            "naturally-idempotent",
1652        );
1653        let err = try_parse_schema("recursive", &top_bad_mac).unwrap_err();
1654        assert!(
1655            err.contains("dispatchMac") && err.contains("not-a-mac"),
1656            "{err}"
1657        );
1658
1659        let top_empty_mutation = schema(
1660            "internal:pq-hybrid",
1661            " $dispatchMac(\"internal:pq-hybrid\") $mutationSemantics(\"naturally-idempotent\");",
1662            "",
1663        );
1664        let err = try_parse_schema("recursive", &top_empty_mutation).unwrap_err();
1665        assert!(err.contains("mutationSemantics"), "{err}");
1666
1667        let nested_bad_mac = schema(
1668            "internal:pq-hybrid",
1669            " $dispatchMac(\"not-a-mac\") $mutationSemantics(\"naturally-idempotent\");",
1670            "naturally-idempotent",
1671        );
1672        let err = try_parse_schema("recursive", &nested_bad_mac).unwrap_err();
1673        assert!(
1674            err.contains("dispatchMac") && err.contains("not-a-mac"),
1675            "{err}"
1676        );
1677
1678        let nested_empty_mutation = schema(
1679            "internal:pq-hybrid",
1680            " $dispatchMac(\"internal:pq-hybrid\") $mutationSemantics(\"\");",
1681            "naturally-idempotent",
1682        );
1683        let err = try_parse_schema("recursive", &nested_empty_mutation).unwrap_err();
1684        assert!(err.contains("mutationSemantics"), "{err}");
1685
1686        let nested_public = schema(
1687            "internal:pq-hybrid",
1688            " $dispatchPublic(\"nested public\") $mutationSemantics(\"naturally-idempotent\");",
1689            "naturally-idempotent",
1690        );
1691        let err = try_parse_schema("recursive", &nested_public).unwrap_err();
1692        assert!(err.contains("public is legal only on leaves"), "{err}");
1693
1694        let nested_both = schema(
1695            "internal:pq-hybrid",
1696            " $dispatchMac(\"internal:pq-hybrid\") $dispatchPublic(\"nested both\") $mutationSemantics(\"naturally-idempotent\");",
1697            "naturally-idempotent",
1698        );
1699        let err = try_parse_schema("recursive", &nested_both).unwrap_err();
1700        assert!(err.contains("BOTH"), "{err}");
1701
1702        // A local public leaf clears the inherited MAC while its unannotated
1703        // sibling keeps that selector MAC. The public leaf is scope-exempt.
1704        let valid = r#"@0x91a2b3c4d5e6f702;
1705
1706enum ScopeAction { query @0; }
1707annotation scope(field) :ScopeAction;
1708annotation scopeExempt(field) :Text;
1709annotation dispatchMac(field) :Text;
1710annotation dispatchPublic(field) :Text;
1711annotation mutationSemantics(field) :Text;
1712struct Inner {
1713  union {
1714    publicLeaf @0 :Void $scopeExempt("liveness") $dispatchPublic("nested public leaf");
1715    inheritedLeaf @1 :Void;
1716  }
1717}
1718struct Outer { union { inner @0 :Inner; sibling @1 :Void; } }
1719struct ValidRequest {
1720  union {
1721    route @0 :Outer $scopeExempt("route") $dispatchMac("internal:pq-hybrid");
1722    health @1 :Void $scopeExempt("health") $dispatchPublic("valid public control");
1723  }
1724}
1725struct ValidResponse { union { ok @0 :Void; other @1 :Void; } }
1726"#;
1727        let parsed = try_parse_schema("valid", valid).expect("valid recursive schema");
1728        let inner = parsed
1729            .structs
1730            .iter()
1731            .find(|s| s.name == "Inner")
1732            .expect("Inner");
1733        assert!(inner.union_arms[0].dispatch_public_present);
1734        assert!(!inner.union_arms[1].dispatch_mac_present);
1735    }
1736
1737    /// A local MAC/Public pair must remain contradictory even when public
1738    /// would otherwise clear an inherited selector MAC. Presence bits include
1739    /// an explicitly empty MAC annotation.
1740    #[test]
1741    fn local_leaf_dispatch_conflicts_fail_at_direct_and_recursive_depths() {
1742        let direct = r#"@0x91a2b3c4d5e6f703;
1743annotation scopeExempt(field) :Text;
1744annotation dispatchMac(field) :Text;
1745annotation dispatchPublic(field) :Text;
1746struct DirectInner {
1747  union {
1748    conflict @0 :Void $dispatchMac("") $dispatchPublic("local conflict");
1749    sibling @1 :Void $dispatchMac("internal:pq-hybrid");
1750  }
1751}
1752struct DirectRequest {
1753  union {
1754    run @0 :DirectInner $scopeExempt("control") $dispatchMac("internal:pq-hybrid");
1755    health @1 :Void $scopeExempt("health") $dispatchPublic("valid health");
1756  }
1757}
1758struct DirectResponse { union { ok @0 :Void; other @1 :Void; } }
1759"#;
1760        let err = try_parse_schema("direct", direct).unwrap_err();
1761        assert!(
1762            err.contains("BOTH") && err.contains("dispatchPublic"),
1763            "{err}"
1764        );
1765
1766        let nested = r#"@0x91a2b3c4d5e6f704;
1767annotation scopeExempt(field) :Text;
1768annotation dispatchMac(field) :Text;
1769annotation dispatchPublic(field) :Text;
1770struct NestedLeaf {
1771  union {
1772    conflict @0 :Void $dispatchMac("internal:pq-hybrid") $dispatchPublic("nested conflict");
1773    sibling @1 :Void $dispatchMac("internal:pq-hybrid");
1774  }
1775}
1776struct NestedMiddle { union { descend @0 :NestedLeaf; sibling @1 :Void $dispatchMac("internal:pq-hybrid"); } }
1777struct NestedRequest {
1778  union {
1779    run @0 :NestedMiddle $scopeExempt("control") $dispatchMac("internal:pq-hybrid");
1780    health @1 :Void $scopeExempt("health") $dispatchPublic("valid health");
1781  }
1782}
1783struct NestedResponse { union { ok @0 :Void; other @1 :Void; } }
1784"#;
1785        let err = try_parse_schema("nested", nested).unwrap_err();
1786        assert!(
1787            err.contains("BOTH") && err.contains("dispatchPublic"),
1788            "{err}"
1789        );
1790    }
1791
1792    /// P2 (`PRRT_kwDONmv2Pc6gGRV5`) reason boundaries through the actual
1793    /// schema gate: a padded reason is a parse error (never silently
1794    /// trimmed), whitespace-only stays an error, and a trimmed valid reason
1795    /// is recorded as its exact declared bytes.
1796    fn public_reason_schema(reason: &str) -> String {
1797        format!(
1798            r#"@0xc0ffee5ed15c1a55;
1799
1800enum ScopeAction {{
1801  query @0;
1802  write @1;
1803}}
1804annotation scope(field) :ScopeAction;
1805annotation scopeExempt(field) :Text;
1806annotation dispatchMac(field) :Text;
1807annotation dispatchPublic(field) :Text;
1808
1809struct ReasonRequest {{
1810  union {{
1811    health @0 :Void $scopeExempt("unauthenticated liveness read") $dispatchPublic("{reason}");
1812    dispatch @1 :Void $scope(query) $dispatchMac("internal:pq-hybrid");
1813  }}
1814}}
1815
1816struct ReasonResponse {{
1817  union {{
1818    ok @0 :Void;
1819    fail @1 :Text;
1820  }}
1821}}
1822"#
1823        )
1824    }
1825
1826    #[test]
1827    fn dispatch_public_reason_boundaries_through_the_schema_gate() {
1828        for padded in ["  padded reason  ", " leading", "trailing "] {
1829            let err = try_parse_schema("reason", &public_reason_schema(padded))
1830                .expect_err("a padded public reason must fail the schema gate");
1831            assert!(err.contains("padded"), "{padded:?}: {err}");
1832        }
1833        let err = try_parse_schema("reason", &public_reason_schema("   "))
1834            .expect_err("a whitespace-only reason must fail the schema gate");
1835        assert!(err.contains("empty or whitespace-only"), "{err}");
1836
1837        let ok = try_parse_schema("reason", &public_reason_schema("two exact words"))
1838            .expect("a trimmed valid reason parses");
1839        assert_eq!(
1840            ok.request_variants[0].dispatch_public, "two exact words",
1841            "the recorded reason is the exact declared text"
1842        );
1843    }
1844
1845    /// A pure-union struct with an inline `group` arm carrying leaf fields —
1846    /// mirrors streaming.capnp's OverflowPolicy.dropOldest.
1847    const GROUP_SCHEMA: &str = r#"
1848@0x9009900990099009;
1849
1850struct Overflow {
1851  union {
1852    block @0 :Void;
1853    dropOldest :group {
1854      highWaterMark @1 :UInt32;
1855    }
1856  }
1857}
1858"#;
1859
1860    #[test]
1861    fn inline_union_group_arm_emits_interface_type_and_build_parse() {
1862        let schema = parse_schema("groupfix", GROUP_SCHEMA);
1863
1864        // 1. Interface: a synthesized `{Struct}{Arm}` interface + a typed arm
1865        //    referencing it (NOT the undefined bare `Group`).
1866        let mut ifaces = String::new();
1867        super::super::interfaces::generate_interfaces(&mut ifaces, &schema);
1868        assert!(
1869            ifaces.contains("export interface OverflowDropOldest {"),
1870            "missing synthesized group interface:\n{ifaces}"
1871        );
1872        assert!(
1873            ifaces.contains("highWaterMark: number;"),
1874            "group leaf field missing from interface:\n{ifaces}"
1875        );
1876        assert!(
1877            ifaces.contains("| { variant: 'dropOldest'; data: OverflowDropOldest | null }"),
1878            "group arm not typed to its interface:\n{ifaces}"
1879        );
1880        assert!(
1881            !ifaces.contains("data: Group"),
1882            "must not emit the undefined bare `Group` type:\n{ifaces}"
1883        );
1884
1885        // 2. Parser: the group arm reads its leaf into an object literal, not
1886        //    `undefined`/`null`.
1887        let mut parser = String::new();
1888        super::generate_struct_parsers(&mut parser, &schema);
1889        assert!(
1890            parser.contains("variant: 'dropOldest' as const, data: { highWaterMark:"),
1891            "group arm parse must read leaves into an object:\n{parser}"
1892        );
1893
1894        // 3. Builder: the per-arm builder takes the group interface and writes
1895        //    the leaf.
1896        let mut builder = String::new();
1897        super::super::builders::generate_struct_builders(&mut builder, &schema);
1898        assert!(
1899            builder.contains("buildOverflow_dropOldest(p: OverflowDropOldest)"),
1900            "group arm builder must take the group interface:\n{builder}"
1901        );
1902        assert!(
1903            builder.contains("p.highWaterMark"),
1904            "group arm builder must write the leaf:\n{builder}"
1905        );
1906    }
1907
1908    /// A struct with a `List(Data)` field (mirrors #725's `certHashes: List(Data)`
1909    /// repro) plus a `List(Int64)` field (mirrors `worker.capnp`'s
1910    /// `supplementalGroups`) — both must read through a real runtime getter,
1911    /// never the old silent `[]` fallback.
1912    const LIST_SCHEMA: &str = r#"
1913@0xd00dfeeda00dfeef;
1914
1915struct Reach {
1916  addr @0 :Text;
1917  certHashes @1 :List(Data);
1918  supplementalGroups @2 :List(Int64);
1919}
1920"#;
1921
1922    #[test]
1923    fn list_data_and_list_scalar_fields_parse_with_real_getters() {
1924        let schema = parse_schema("reachparse", LIST_SCHEMA);
1925        let mut out = String::new();
1926        super::generate_struct_parsers(&mut out, &schema);
1927
1928        assert!(
1929            out.contains(".getDataList("),
1930            "expected a real getDataList call for List(Data):\n{out}"
1931        );
1932        assert!(
1933            out.contains(".getInt64List("),
1934            "expected a real getInt64List call for List(Int64), not the old \
1935             `([] as bigint[])` silent fallback:\n{out}"
1936        );
1937        assert!(
1938            !out.contains("([] as "),
1939            "must never silently fall back to a typed empty array:\n{out}"
1940        );
1941    }
1942
1943    /// Regression for #725 defect 2 (dropped `EndpointInfo.pubkey`/`selfProof`
1944    /// fields): every field declared on a struct — including `Data` fields,
1945    /// which is the field type that was dropped — must show up in both the
1946    /// generated interface and the parser's return object. No field is ever
1947    /// silently narrowed out of a regenerated struct.
1948    const ENDPOINT_INFO_SCHEMA: &str = r#"
1949@0xd00dfeeda00dfeec;
1950
1951struct EndpointInfo {
1952  socketKind @0 :Text;
1953  endpoint @1 :Text;
1954  pubkey @2 :Data;
1955  selfProof @3 :Data;
1956  tlsDomain @4 :Text;
1957}
1958"#;
1959
1960    #[test]
1961    fn all_struct_fields_are_preserved_none_silently_dropped() {
1962        let schema = parse_schema("endpointinfo", ENDPOINT_INFO_SCHEMA);
1963
1964        let mut ifaces = String::new();
1965        super::super::interfaces::generate_interfaces(&mut ifaces, &schema);
1966        for field in ["socketKind", "endpoint", "pubkey", "selfProof", "tlsDomain"] {
1967            assert!(
1968                ifaces.contains(&format!("{field}:")),
1969                "interface is missing field `{field}` — a regen must never \
1970                 silently drop a schema field:\n{ifaces}"
1971            );
1972        }
1973
1974        let mut parser = String::new();
1975        super::generate_struct_parsers(&mut parser, &schema);
1976        for field in ["socketKind", "endpoint", "pubkey", "selfProof", "tlsDomain"] {
1977            assert!(
1978                parser.contains(field),
1979                "parser is missing field `{field}` — a regen must never \
1980                 silently drop a schema field:\n{parser}"
1981            );
1982        }
1983        // The two Data fields specifically must read through the real getter,
1984        // not be skipped.
1985        assert!(parser.contains(".getData("), "{parser}");
1986    }
1987
1988    /// A nested-list (`List(List(Float32))`) field, mirroring the
1989    /// `embeddings` field of `EmbedImagesResponse` in `inference.capnp` (the
1990    /// #758 repro: a full regen of `inference.ts`/`model.ts` aborted on
1991    /// exactly this shape because nested lists had no codegen support).
1992    const NESTED_LIST_SCHEMA: &str = r#"
1993@0xd00dfeeda00dfeee;
1994
1995struct EmbedImagesResponse {
1996  embeddings @0 :List(List(Float32));
1997  dimensions @1 :UInt32;
1998}
1999"#;
2000
2001    #[test]
2002    fn nested_list_field_parses_with_real_getter() {
2003        let schema = parse_schema("embedparse", NESTED_LIST_SCHEMA);
2004        let mut out = String::new();
2005        super::generate_struct_parsers(&mut out, &schema);
2006
2007        // Must read through the real nested-list runtime getter, never the
2008        // old #725 hard-panic ("nested list ... not yet supported") and
2009        // never a silent `[]` fallback.
2010        assert!(
2011            out.contains("reader.getFloat32ListList(0)"),
2012            "expected a real getFloat32ListList call for List(List(Float32)):\n{out}"
2013        );
2014        assert!(
2015            !out.contains("not yet supported"),
2016            "must never emit the old #725 nested-list panic path:\n{out}"
2017        );
2018        // The sibling scalar field must still parse correctly alongside it.
2019        assert!(out.contains("reader.getUint32(0)"), "{out}");
2020    }
2021
2022    /// A field whose type references a struct that isn't in the parsed
2023    /// schema's `structs` list is a dangling reference — a genuine generator
2024    /// bug — and must be a hard build failure, never a silently emitted
2025    /// empty-array fallback.
2026    #[test]
2027    #[should_panic(expected = "dangling reference")]
2028    fn dangling_struct_reference_in_list_response_variant_panics() {
2029        use hyprstream_rpc_build::schema::types::{
2030            FieldDef, FieldSection, StructDef, UnionVariant,
2031        };
2032
2033        let response_struct = StructDef {
2034            name: "GhostResponse".to_owned(),
2035            fields: vec![FieldDef {
2036                name: "ghosts".to_owned(),
2037                type_name: "List(GhostStruct)".to_owned(),
2038                description: String::new(),
2039                fixed_size: None,
2040                max_len: None,
2041                optional: false,
2042                slot_offset: 0,
2043                section: FieldSection::Pointer,
2044                discriminant_value: 0,
2045                serde_rename: None,
2046                domain_type: None,
2047            }],
2048            has_union: true,
2049            domain_type: None,
2050            origin_file: None,
2051            data_words: 0,
2052            pointer_words: 1,
2053            discriminant_count: 1,
2054            discriminant_offset: 0,
2055            union_arms: vec![],
2056        };
2057        let schema = ParsedSchema {
2058            request_variants: vec![],
2059            response_variants: vec![UnionVariant {
2060                name: "ghosts".to_owned(),
2061                type_name: "List(GhostStruct)".to_owned(),
2062                description: String::new(),
2063                scope: String::new(),
2064                scope_exempt: false,
2065                cli_hidden: false,
2066                doc_example: String::new(),
2067                vfs_path: String::new(),
2068                vfs_kind: String::new(),
2069                vfs_bulk: false,
2070                vfs_hidden: false,
2071                vfs_mac: String::new(),
2072                dispatch_mac: String::new(),
2073                dispatch_public: String::new(),
2074                mutation_semantics: String::new(),
2075                dispatch_mac_present: false,
2076                dispatch_public_present: false,
2077                mutation_semantics_present: false,
2078            }],
2079            structs: vec![],
2080            scoped_clients: vec![],
2081            enums: vec![],
2082            request_struct: None,
2083            response_struct: Some(response_struct),
2084        };
2085
2086        let mut out = String::new();
2087        super::generate_parsers(&mut out, "ghost", &schema);
2088    }
2089}