1mod 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#[allow(clippy::print_stdout)]
24pub fn generate_all<B: CodegenBackend>(
25 backend: &B,
26 schemas: &[(String, ParsedSchema)],
27 output_dir: &Path,
28) {
29 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 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 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
62fn 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 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 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::generate_interfaces(&mut out, schema);
98
99 builders::generate_builders(&mut out, service_name, schema);
101 parsers::generate_parsers(&mut out, service_name, schema);
102
103 builders::generate_struct_builders(&mut out, schema);
105 parsers::generate_struct_parsers(&mut out, schema);
106
107 if is_service {
109 client::generate_client(&mut out, service_name, schema);
110 }
111
112 out
113}
114
115fn 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 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
156fn 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 if field.section == FieldSection::Data {
174 field.slot_offset * 2
175 } else {
176 field.slot_offset
177 }
178 }
179 }
180}
181
182fn bool_bit_index(field: &FieldDef) -> u32 {
184 field.slot_offset % 8
185}
186
187fn 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, })
207}
208
209pub(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
236pub(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
257pub(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
286pub(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
305fn 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
318fn 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 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
347pub(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
365fn 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
374pub(crate) fn is_primitive(type_name: &str) -> bool {
379 hyprstream_rpc_build::schema::types::is_primitive_capnp_type(type_name)
380}
381
382pub(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 return capnp_to_ts_type(tn);
406 }
407 if is_primitive(tn) {
409 return capnp_to_ts_type(tn);
410 }
411 if tn.starts_with("Option") {
415 return capnp_to_ts_type(tn);
416 }
417 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
427pub(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
450pub(crate) fn group_arm_type_name(struct_name: &str, arm_name: &str) -> String {
453 format!("{struct_name}{}", to_pascal_case(arm_name))
454}
455
456pub(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
470pub(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 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
494pub(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
521pub(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
554pub(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
571pub(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
591fn 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
603pub(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
620pub(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
635pub 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 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
690fn 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
718fn generate_index(
733 all_names: &[String],
734 client_names: &[String],
735 module_contents: &[(String, String)],
736) -> String {
737 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 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 out.push_str(&format!("export * from './{name}';\n"));
782 continue;
783 }
784
785 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 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 #[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 #[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 assert!(!out.contains("export * from './events';"), "{out}");
869 assert!(!out.contains("export * from './streaming';"), "{out}");
870
871 assert!(out.contains("QoS as EventsQoS"), "{out}");
873 assert!(out.contains("QoS as StreamingQoS"), "{out}");
874 assert!(out.contains("EventEnvelope"), "{out}");
877 assert!(out.contains("StreamInfo"), "{out}");
878 }
879
880 #[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}