actr-web-protoc-codegen 0.3.0

Protoc plugin for generating actr-web code from protobuf definitions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
//! TypeScript code generator.

use crate::{GeneratedFile, ProtoService, config::WebCodegenConfig, error::Result};

/// Generate TypeScript type definitions.
pub(crate) fn generate_types(
    config: &WebCodegenConfig,
    services: &[ProtoService],
) -> Result<Vec<GeneratedFile>> {
    let mut files = Vec::new();

    for service in services {
        let file = generate_types_for_service(config, service)?;
        files.push(file);
    }

    // Generate `index.ts`.
    let index_file = generate_ts_index_file(config, services)?;
    files.push(index_file);

    Ok(files)
}

/// Generate TypeScript types for one service.
fn generate_types_for_service(
    config: &WebCodegenConfig,
    service: &ProtoService,
) -> Result<GeneratedFile> {
    use heck::ToKebabCase;

    let file_name = format!("{}.types.ts", service.name.to_kebab_case());
    let file_path = config.ts_output_dir.join(&file_name);

    let mut content = format!(
        r#"/**
 * Auto-generated type definitions
 * Service: {}
 * Package: {}
 *
 * Do not edit this file manually.
 */

"#,
        service.name, service.package
    );

    // Add protobuf helper functions.
    content.push_str(generate_ts_protobuf_utils());

    // Generate message types plus encode/decode helpers.
    for message in &service.messages {
        content.push_str(&generate_ts_message_type(message));
        content.push('\n');
        content.push_str(&generate_ts_encode_function(message));
        content.push('\n');
        content.push_str(&generate_ts_decode_function(message));
        content.push('\n');
    }

    Ok(GeneratedFile::new(file_path, content))
}

/// Generate one TypeScript message type.
fn generate_ts_message_type(message: &crate::ProtoMessage) -> String {
    let mut content = format!(
        r#"/**
 * {} message
 */
export interface {} {{
"#,
        message.name, message.name
    );

    for field in &message.fields {
        let ts_type = proto_type_to_typescript(&field.field_type);
        let field_type = if field.is_repeated {
            format!("{}[]", ts_type)
        } else {
            ts_type
        };

        let optional_marker = if field.is_optional { "?" } else { "" };

        content.push_str(&format!(
            "  {}{}: {};\n",
            field.name, optional_marker, field_type
        ));
    }

    content.push_str("}\n");
    content
}

/// Generate the encode function.
fn generate_ts_encode_function(message: &crate::ProtoMessage) -> String {
    let mut content = format!(
        r#"/**
 * Encode {} into a Uint8Array in Protobuf wire format
 */
export function encode{}(msg: {}): Uint8Array {{
  const parts: number[] = [];
"#,
        message.name, message.name, message.name
    );

    for field in &message.fields {
        let field_number = field.number;
        let wire_type = get_wire_type(&field.field_type);

        match field.field_type.as_str() {
            "string" => {
                content.push_str(&format!(
                    r#"
  // Field {}: {} (string)
  if (msg.{} !== undefined && msg.{} !== '') {{
    const text = new TextEncoder().encode(msg.{});
    parts.push({} << 3 | 2); // field tag
    pushVarint(parts, text.length);
    parts.push(...Array.from(text));
  }}
"#,
                    field_number, field.name, field.name, field.name, field.name, field_number
                ));
            }
            "bytes" => {
                content.push_str(&format!(
                    r#"
  // Field {}: {} (bytes)
  if (msg.{} !== undefined && msg.{}.length > 0) {{
    parts.push({} << 3 | 2); // field tag
    pushVarint(parts, msg.{}.length);
    parts.push(...Array.from(msg.{}));
  }}
"#,
                    field_number,
                    field.name,
                    field.name,
                    field.name,
                    field_number,
                    field.name,
                    field.name
                ));
            }
            "bool" => {
                content.push_str(&format!(
                    r#"
  // Field {}: {} (bool)
  if (msg.{} !== undefined) {{
    parts.push({} << 3 | 0); // field tag
    parts.push(msg.{} ? 1 : 0);
  }}
"#,
                    field_number, field.name, field.name, field_number, field.name
                ));
            }
            "int32" | "int64" | "uint32" | "uint64" | "sint32" | "sint64" => {
                content.push_str(&format!(
                    r#"
  // Field {}: {} ({})
  if (msg.{} !== undefined && msg.{} !== 0) {{
    parts.push({} << 3 | 0); // field tag
    pushVarint(parts, msg.{});
  }}
"#,
                    field_number,
                    field.name,
                    field.field_type,
                    field.name,
                    field.name,
                    field_number,
                    field.name
                ));
            }
            "float" | "double" => {
                let byte_size = if field.field_type == "float" { 4 } else { 8 };
                let wire = if field.field_type == "float" { 5 } else { 1 };
                content.push_str(&format!(
                    r#"
  // Field {}: {} ({})
  if (msg.{} !== undefined && msg.{} !== 0) {{
    parts.push({} << 3 | {}); // field tag
    const buf = new ArrayBuffer({});
    const view = new DataView(buf);
    view.set{}(0, msg.{}, true);
    parts.push(...Array.from(new Uint8Array(buf)));
  }}
"#,
                    field_number,
                    field.name,
                    field.field_type,
                    field.name,
                    field.name,
                    field_number,
                    wire,
                    byte_size,
                    if field.field_type == "float" {
                        "Float32"
                    } else {
                        "Float64"
                    },
                    field.name
                ));
            }
            "fixed32" | "sfixed32" => {
                content.push_str(&format!(
                    r#"
  // Field {}: {} ({})
  if (msg.{} !== undefined && msg.{} !== 0) {{
    parts.push({} << 3 | 5); // field tag (wire type 5 = 32-bit)
    const buf = new ArrayBuffer(4);
    const view = new DataView(buf);
    view.set{}(0, msg.{}, true);
    parts.push(...Array.from(new Uint8Array(buf)));
  }}
"#,
                    field_number,
                    field.name,
                    field.field_type,
                    field.name,
                    field.name,
                    field_number,
                    if field.field_type == "sfixed32" {
                        "Int32"
                    } else {
                        "Uint32"
                    },
                    field.name
                ));
            }
            "fixed64" | "sfixed64" => {
                content.push_str(&format!(
                    r#"
  // Field {}: {} ({})
  if (msg.{} !== undefined && msg.{} !== 0) {{
    parts.push({} << 3 | 1); // field tag (wire type 1 = 64-bit)
    const buf = new ArrayBuffer(8);
    const view = new DataView(buf);
    view.setBigInt64(0, BigInt(msg.{}), true);
    parts.push(...Array.from(new Uint8Array(buf)));
  }}
"#,
                    field_number,
                    field.name,
                    field.field_type,
                    field.name,
                    field.name,
                    field_number,
                    field.name
                ));
            }
            _ => {
                // Default to varint handling.
                content.push_str(&format!(
                    r#"
  // Field {}: {} (default varint)
  if (msg.{} !== undefined) {{
    parts.push({} << 3 | {}); // field tag
    pushVarint(parts, msg.{});
  }}
"#,
                    field_number, field.name, field.name, field_number, wire_type, field.name
                ));
            }
        }
    }

    content.push_str(
        r#"
  return new Uint8Array(parts);
}
"#,
    );

    content
}

/// Generate the decode function.
fn generate_ts_decode_function(message: &crate::ProtoMessage) -> String {
    let mut content = format!(
        r#"/**
 * Decode {} from a Uint8Array in Protobuf wire format
 */
export function decode{}(bytes: Uint8Array): {} {{
  const result: {} = {{{}}};
  let offset = 0;

  while (offset < bytes.length) {{
    const tagInfo = readVarint(bytes, offset);
    const tag = tagInfo.value;
    offset = tagInfo.offset;

    const fieldNumber = tag >> 3;
    const wireType = tag & 0x7;

    switch (fieldNumber) {{
"#,
        message.name,
        message.name,
        message.name,
        message.name,
        // Generate default values.
        message
            .fields
            .iter()
            .map(|f| format!(
                "{}: {}",
                f.name,
                get_default_value(&f.field_type, f.is_repeated)
            ))
            .collect::<Vec<_>>()
            .join(", ")
    );

    for field in &message.fields {
        let field_number = field.number;

        match field.field_type.as_str() {
            "string" => {
                content.push_str(&format!(
                    r#"      case {}: {{ // {}
        if (wireType !== 2) throw new Error('Expected wire type 2 for string');
        const lenInfo = readVarint(bytes, offset);
        offset = lenInfo.offset;
        const data = bytes.slice(offset, offset + lenInfo.value);
        result.{} = new TextDecoder().decode(data);
        offset += lenInfo.value;
        break;
      }}
"#,
                    field_number, field.name, field.name
                ));
            }
            "bytes" => {
                content.push_str(&format!(
                    r#"      case {}: {{ // {}
        if (wireType !== 2) throw new Error('Expected wire type 2 for bytes');
        const lenInfo = readVarint(bytes, offset);
        offset = lenInfo.offset;
        result.{} = bytes.slice(offset, offset + lenInfo.value);
        offset += lenInfo.value;
        break;
      }}
"#,
                    field_number, field.name, field.name
                ));
            }
            "bool" => {
                content.push_str(&format!(
                    r#"      case {}: {{ // {}
        if (wireType !== 0) throw new Error('Expected wire type 0 for bool');
        const valInfo = readVarint(bytes, offset);
        result.{} = valInfo.value !== 0;
        offset = valInfo.offset;
        break;
      }}
"#,
                    field_number, field.name, field.name
                ));
            }
            "int32" | "int64" | "uint32" | "uint64" | "sint32" | "sint64" => {
                content.push_str(&format!(
                    r#"      case {}: {{ // {}
        if (wireType !== 0) throw new Error('Expected wire type 0 for {}');
        const valInfo = readVarint(bytes, offset);
        result.{} = valInfo.value;
        offset = valInfo.offset;
        break;
      }}
"#,
                    field_number, field.name, field.field_type, field.name
                ));
            }
            "float" => {
                content.push_str(&format!(
                    r#"      case {}: {{ // {}
        if (wireType !== 5) throw new Error('Expected wire type 5 for float');
        const view = new DataView(bytes.buffer, bytes.byteOffset + offset, 4);
        result.{} = view.getFloat32(0, true);
        offset += 4;
        break;
      }}
"#,
                    field_number, field.name, field.name
                ));
            }
            "double" => {
                content.push_str(&format!(
                    r#"      case {}: {{ // {}
        if (wireType !== 1) throw new Error('Expected wire type 1 for double');
        const view = new DataView(bytes.buffer, bytes.byteOffset + offset, 8);
        result.{} = view.getFloat64(0, true);
        offset += 8;
        break;
      }}
"#,
                    field_number, field.name, field.name
                ));
            }
            "fixed32" | "sfixed32" => {
                content.push_str(&format!(
                    r#"      case {}: {{ // {}
        if (wireType !== 5) throw new Error('Expected wire type 5 for {}');
        const view = new DataView(bytes.buffer, bytes.byteOffset + offset, 4);
        result.{} = view.get{}(0, true);
        offset += 4;
        break;
      }}
"#,
                    field_number,
                    field.name,
                    field.field_type,
                    field.name,
                    if field.field_type == "sfixed32" {
                        "Int32"
                    } else {
                        "Uint32"
                    }
                ));
            }
            "fixed64" | "sfixed64" => {
                content.push_str(&format!(
                    r#"      case {}: {{ // {}
        if (wireType !== 1) throw new Error('Expected wire type 1 for {}');
        const view = new DataView(bytes.buffer, bytes.byteOffset + offset, 8);
        result.{} = Number(view.getBigInt64(0, true));
        offset += 8;
        break;
      }}
"#,
                    field_number, field.name, field.field_type, field.name
                ));
            }
            _ => {
                // Skip fields for unsupported types by default.
                content.push_str(&format!(
                    r#"      case {}: {{ // {} (unknown type: {})
        offset = skipField(bytes, offset, wireType);
        break;
      }}
"#,
                    field_number, field.name, field.field_type
                ));
            }
        }
    }

    content.push_str(
        r#"      default:
        // Skip unknown field
        offset = skipField(bytes, offset, wireType);
    }
  }

  return result;
}
"#,
    );

    content
}

/// Convert a proto type into a TypeScript type.
fn proto_type_to_typescript(proto_type: &str) -> String {
    match proto_type {
        "string" => "string".to_string(),
        "bytes" => "Uint8Array".to_string(),
        "int32" | "sint32" | "sfixed32" | "int64" | "sint64" | "sfixed64" | "uint32"
        | "fixed32" | "uint64" | "fixed64" | "float" | "double" => "number".to_string(),
        "bool" => "boolean".to_string(),
        // Preserve custom types as-is.
        custom => custom.to_string(),
    }
}

/// Return the protobuf wire type.
fn get_wire_type(proto_type: &str) -> u8 {
    match proto_type {
        "int32" | "int64" | "uint32" | "uint64" | "sint32" | "sint64" | "bool" => 0, // Varint
        "fixed64" | "sfixed64" | "double" => 1,                                      // 64-bit
        "string" | "bytes" => 2,               // Length-delimited
        "fixed32" | "sfixed32" | "float" => 5, // 32-bit
        _ => 0,                                // Default to varint
    }
}

/// Return the default value for a field.
fn get_default_value(proto_type: &str, is_repeated: bool) -> &'static str {
    if is_repeated {
        return "[]";
    }
    match proto_type {
        "string" => "''",
        "bytes" => "new Uint8Array()",
        "bool" => "false",
        "int32" | "int64" | "uint32" | "uint64" | "sint32" | "sint64" | "float" | "double"
        | "fixed32" | "sfixed32" | "fixed64" | "sfixed64" => "0",
        _ => "undefined as any",
    }
}

/// Generate TypeScript protobuf helper functions.
fn generate_ts_protobuf_utils() -> &'static str {
    r#"// ========== Protobuf encode/decode helpers ==========

/**
 * Push a varint into a number array
 */
function pushVarint(arr: number[], value: number): void {
  value = value >>> 0; // Convert to an unsigned integer.
  while (value > 127) {
    arr.push((value & 0x7f) | 0x80);
    value = value >>> 7;
  }
  arr.push(value);
}

/**
 * Read a varint from a byte array
 */
function readVarint(bytes: Uint8Array, offset: number): { value: number; offset: number } {
  let result = 0;
  let shift = 0;
  let byte: number;
  do {
    byte = bytes[offset++];
    result |= (byte & 0x7f) << shift;
    shift += 7;
  } while (byte >= 0x80);
  return { value: result >>> 0, offset };
}

/**
 * Skip an unknown field
 */
function skipField(bytes: Uint8Array, offset: number, wireType: number): number {
  switch (wireType) {
    case 0: // Varint
      while (bytes[offset++] >= 0x80) {}
      return offset;
    case 1: // 64-bit
      return offset + 8;
    case 2: // Length-delimited
      const lenInfo = readVarint(bytes, offset);
      return lenInfo.offset + lenInfo.value;
    case 5: // 32-bit
      return offset + 4;
    default:
      throw new Error(`Unknown wire type: ${wireType}`);
  }
}

"#
}

/// Generate ActorRef wrappers.
pub(crate) fn generate_actor_refs(
    config: &WebCodegenConfig,
    services: &[ProtoService],
) -> Result<Vec<GeneratedFile>> {
    let mut files = Vec::new();

    for service in services {
        let file = generate_actor_ref_for_service(config, service)?;
        files.push(file);
    }

    Ok(files)
}

/// Generate an ActorRef wrapper for one service.
fn generate_actor_ref_for_service(
    config: &WebCodegenConfig,
    service: &ProtoService,
) -> Result<GeneratedFile> {
    use heck::{ToKebabCase, ToPascalCase};

    let file_name = format!("{}.actor-ref.ts", service.name.to_kebab_case());
    let file_path = config.ts_output_dir.join(&file_name);
    let class_name = format!("{}ActorRef", service.name.to_pascal_case());

    // Collect all message types and encode/decode helpers.
    let mut type_imports = std::collections::HashSet::new();
    let mut encode_imports = std::collections::HashSet::new();
    let mut decode_imports = std::collections::HashSet::new();
    for method in &service.methods {
        type_imports.insert(method.input_type.clone());
        type_imports.insert(method.output_type.clone());
        encode_imports.insert(format!("encode{}", method.input_type));
        decode_imports.insert(format!("decode{}", method.output_type));
    }

    let mut content = format!(
        r#"/**
 * Auto-generated ActorRef wrapper
 * Service: {}
 *
 * Do not edit this file manually.
 */

import {{ ActorRef }} from '@actr/web';
import type {{ {} }} from './{}.types';
import {{ {} }} from './{}.types';

/**
 * {} actor reference
 */
export class {} extends ActorRef {{
  /**
   * Create a new ActorRef instance
   */
  constructor(actorId: string) {{
    super(actorId);
  }}

"#,
        service.name,
        type_imports
            .iter()
            .map(|s| s.as_str())
            .collect::<Vec<_>>()
            .join(", "),
        service.name.to_kebab_case(),
        encode_imports
            .iter()
            .chain(decode_imports.iter())
            .map(|s| s.as_str())
            .collect::<Vec<_>>()
            .join(", "),
        service.name.to_kebab_case(),
        service.name,
        class_name
    );

    // Generate methods.
    for method in &service.methods {
        content.push_str(&generate_ts_actor_ref_method(method, &service.name));
        content.push('\n');
    }

    content.push_str("}\n");

    Ok(GeneratedFile::new(file_path, content))
}

/// Generate one ActorRef method.
fn generate_ts_actor_ref_method(method: &crate::ProtoMethod, service_name: &str) -> String {
    use heck::ToLowerCamelCase;

    let method_name = method.name.to_lower_camel_case();
    let input_type = &method.input_type;
    let output_type = &method.output_type;
    let route_key = format!("{}:{}", service_name, method.name);

    if method.is_streaming {
        // Streaming method: use `subscribe`.
        format!(
            r#"  /**
   * Streaming method for {}
   */
  subscribe{}(callback: (data: {}) => void): () => void {{
    return this.subscribe('{}', (bytes: Uint8Array) => {{
      callback(decode{}(bytes));
    }});
  }}
"#,
            method.name, method.name, output_type, route_key, output_type
        )
    } else {
        // Standard RPC method: use `callRaw`.
        format!(
            r#"  /**
   * RPC method for {}
   */
  async {}(request: {}): Promise<{}> {{
    const requestBytes = encode{}(request);
    const responseBytes = await this.callRaw('{}', requestBytes);
    return decode{}(responseBytes);
  }}
"#,
            method.name, method_name, input_type, output_type, input_type, route_key, output_type
        )
    }
}

/// Generate React Hooks.
pub(crate) fn generate_react_hooks(
    config: &WebCodegenConfig,
    services: &[ProtoService],
) -> Result<Vec<GeneratedFile>> {
    let mut files = Vec::new();

    for service in services {
        let file = generate_react_hook_for_service(config, service)?;
        files.push(file);
    }

    Ok(files)
}

/// Generate a React Hook for one service.
fn generate_react_hook_for_service(
    config: &WebCodegenConfig,
    service: &ProtoService,
) -> Result<GeneratedFile> {
    use heck::{ToKebabCase, ToPascalCase};

    let file_name = format!("use-{}.ts", service.name.to_kebab_case());
    let file_path = config.ts_output_dir.join(&file_name);
    let hook_name = format!("use{}", service.name.to_pascal_case());
    let class_name = format!("{}ActorRef", service.name.to_pascal_case());

    let mut content = format!(
        r#"/**
 * Auto-generated React Hook
 * Service: {}
 *
 * Do not edit this file manually.
 */

import {{ useState, useEffect, useCallback }} from 'react';
import {{ {} }} from './{}.actor-ref';

/**
 * {} React Hook
 */
export function {}(actorId: string) {{
  const [actorRef] = useState(() => new {}(actorId));
  const [isConnected, setIsConnected] = useState(false);

  useEffect(() => {{
    // Listen for connection state changes.
    const unlisten = actorRef.on('connection-state-changed', (state) => {{
      setIsConnected(state === 'connected');
    }});

    return () => {{
      unlisten();
    }};
  }}, [actorRef]);

"#,
        service.name,
        class_name,
        service.name.to_kebab_case(),
        service.name,
        hook_name,
        class_name
    );

    // Generate convenience hook functions for each method.
    for method in &service.methods {
        if !method.is_streaming {
            content.push_str(&generate_react_hook_method(method));
        }
    }

    content.push_str(
        r#"
  return {
    actorRef,
    isConnected,
  };
}
"#,
    );

    Ok(GeneratedFile::new(file_path, content))
}

/// Generate one React Hook method.
fn generate_react_hook_method(method: &crate::ProtoMethod) -> String {
    use heck::ToLowerCamelCase;

    let method_name = method.name.to_lower_camel_case();
    let input_type = &method.input_type;
    let _output_type = &method.output_type;

    format!(
        r#"  /**
   * Convenience wrapper for {}
   */
  const {} = useCallback(
    async (request: {}) => {{
      return actorRef.{}(request);
    }},
    [actorRef]
  );

"#,
        method.name, method_name, input_type, method_name
    )
}

/// Generate `index.ts`.
fn generate_ts_index_file(
    config: &WebCodegenConfig,
    services: &[ProtoService],
) -> Result<GeneratedFile> {
    use heck::ToKebabCase;

    let file_path = config.ts_output_dir.join("index.ts");

    let mut content = String::from(
        r#"/**
 * Auto-generated exports
 *
 * Do not edit this file manually.
 */

"#,
    );

    // Export types.
    content.push_str("// Type definitions\n");
    for service in services {
        let file_name = service.name.to_kebab_case();
        content.push_str(&format!("export * from './{}.types';\n", file_name));
    }

    content.push('\n');

    // Export ActorRef classes.
    content.push_str("// ActorRef classes\n");
    for service in services {
        let file_name = service.name.to_kebab_case();
        content.push_str(&format!("export * from './{}.actor-ref';\n", file_name));
    }

    // Export React Hooks when enabled.
    if config.generate_react_hooks {
        content.push('\n');
        content.push_str("// React Hooks\n");
        for service in services {
            let file_name = service.name.to_kebab_case();
            content.push_str(&format!("export * from './use-{}';\n", file_name));
        }
    }

    Ok(GeneratedFile::new(file_path, content))
}