olai-codegen 0.0.12

Proto-driven code generation for REST handlers, clients, and resource registries
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
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
//! TypeScript client generation for idiomatic Node.js API.
//!
//! Generates a `client.ts` that wraps NAPI-RS native bindings with typed
//! protobuf decoding via `@bufbuild/protobuf`.

use std::collections::BTreeSet;

use convert_case::{Case, Casing};
use itertools::Itertools;

use super::caps::{is_napi_supported, is_required_message_body, message_type_name};
use crate::analysis::{EmitShape, RequestParam, RequestType};
use crate::codegen::{BindingMode, BindingsConfig, MethodHandler, ServiceHandler};
use crate::parsing::types::unified_to_typescript;
use crate::utils::last_segment;

/// JS globals that Biome's `noShadowRestrictedNames` rule forbids re-binding. A proto message
/// named after one of these (e.g. `Function`, `Object`, `Date`) would shadow the global when
/// imported under its bare name, so its TypeScript *type* reference is aliased via
/// [`ts_type_ident`]. Kept in sync with Biome's restricted set.
const RESTRICTED_GLOBAL_NAMES: &[&str] = &[
    "Array",
    "ArrayBuffer",
    "Atomics",
    "BigInt",
    "BigInt64Array",
    "BigUint64Array",
    "Boolean",
    "DataView",
    "Date",
    "Error",
    "EvalError",
    "Float32Array",
    "Float64Array",
    "Function",
    "Infinity",
    "Int16Array",
    "Int32Array",
    "Int8Array",
    "Intl",
    "JSON",
    "Map",
    "Math",
    "NaN",
    "Number",
    "Object",
    "Promise",
    "Proxy",
    "RangeError",
    "ReferenceError",
    "Reflect",
    "RegExp",
    "Set",
    "SharedArrayBuffer",
    "String",
    "Symbol",
    "SyntaxError",
    "TypeError",
    "URIError",
    "Uint16Array",
    "Uint32Array",
    "Uint8Array",
    "Uint8ClampedArray",
    "WeakMap",
    "WeakSet",
    "undefined",
];

/// The TypeScript identifier to use when *referencing* a model type. Most types are referenced by
/// their bare name; a type whose name collides with a JS global (see [`RESTRICTED_GLOBAL_NAMES`])
/// is referenced through a trailing-`$` alias so it doesn't shadow the global. The matching import
/// is emitted as `type Name as Name$` by [`ts_type_import_clause`].
///
/// Schema names (`<Name>Schema`) never collide, so they are left untouched.
fn ts_type_ident(name: &str) -> String {
    if RESTRICTED_GLOBAL_NAMES.contains(&name) {
        format!("{name}$")
    } else {
        name.to_string()
    }
}

/// The `type` import clause for a model type: `type Name`, or `type Name as Name$` when the bare
/// name would shadow a JS global. Mirrors [`ts_type_ident`].
fn ts_type_import_clause(name: &str) -> String {
    if RESTRICTED_GLOBAL_NAMES.contains(&name) {
        format!("type {name} as {name}$")
    } else {
        format!("type {name}")
    }
}

/// Format optional documentation as a JSDoc comment block.
fn format_jsdoc(documentation: Option<&str>, indent: &str) -> String {
    let Some(doc) = documentation else {
        return String::new();
    };
    let trimmed = doc.trim();
    if trimmed.is_empty() {
        return String::new();
    }
    let lines: Vec<String> = trimmed
        .lines()
        .map(|l| format!("{}   * {}", indent, l.trim()))
        .collect();
    format!("{}/**\n{}\n{}   */\n", indent, lines.join("\n"), indent)
}

/// TypeScript error class definitions and `parseNativeError` helper.
fn generate_error_classes(bindings: &BindingsConfig) -> String {
    let base = &bindings.ts_error_base_class;
    let prefix = &bindings.ts_error_code_prefix;
    format!(
        r#"// ── {base} error hierarchy ────────────────────────────────────────────────────────

/** Base class for all {base} errors. */
export class {base} extends Error {{
  readonly errorCode: string;
  constructor(message: string, errorCode: string) {{
    super(message);
    this.name = "{base}";
    this.errorCode = errorCode;
  }}
}}

export class NotFoundError extends {base} {{
  constructor(message: string) {{
    super(message, "RESOURCE_NOT_FOUND");
    this.name = "NotFoundError";
  }}
}}

export class AlreadyExistsError extends {base} {{
  constructor(message: string) {{
    super(message, "RESOURCE_ALREADY_EXISTS");
    this.name = "AlreadyExistsError";
  }}
}}

export class PermissionDeniedError extends {base} {{
  constructor(message: string) {{
    super(message, "PERMISSION_DENIED");
    this.name = "PermissionDeniedError";
  }}
}}

export class UnauthenticatedError extends {base} {{
  constructor(message: string) {{
    super(message, "UNAUTHENTICATED");
    this.name = "UnauthenticatedError";
  }}
}}

export class InvalidParameterError extends {base} {{
  constructor(message: string) {{
    super(message, "INVALID_PARAMETER_VALUE");
    this.name = "InvalidParameterError";
  }}
}}

export class RequestLimitError extends {base} {{
  constructor(message: string) {{
    super(message, "REQUEST_LIMIT_EXCEEDED");
    this.name = "RequestLimitError";
  }}
}}

export class InternalServerError extends {base} {{
  constructor(message: string) {{
    super(message, "INTERNAL_ERROR");
    this.name = "InternalServerError";
  }}
}}

export class ServiceUnavailableError extends {base} {{
  constructor(message: string) {{
    super(message, "TEMPORARILY_UNAVAILABLE");
    this.name = "ServiceUnavailableError";
  }}
}}

type ErrorConstructor = new (message: string) => {base};

const ERROR_MAP: Record<string, ErrorConstructor> = {{
  RESOURCE_NOT_FOUND: NotFoundError,
  RESOURCE_ALREADY_EXISTS: AlreadyExistsError,
  PERMISSION_DENIED: PermissionDeniedError,
  UNAUTHENTICATED: UnauthenticatedError,
  INVALID_PARAMETER_VALUE: InvalidParameterError,
  REQUEST_LIMIT_EXCEEDED: RequestLimitError,
  INTERNAL_ERROR: InternalServerError,
  TEMPORARILY_UNAVAILABLE: ServiceUnavailableError,
}};

/**
 * Parse a native NAPI error that may carry a `{prefix}:<CODE>:<message>` prefix
 * and re-throw as the appropriate typed subclass of `{base}`.
 */
function parseNativeError(e: unknown): never {{
  if (e instanceof Error) {{
    const match = e.message.match(/^{prefix}:([^:]+):([\s\S]*)$/);
    if (match) {{
      const [, code, message] = match;
      const Ctor = ERROR_MAP[code] ?? {base};
      throw new Ctor(message);
    }}
  }}
  throw e;
}}

// ── end {base} error hierarchy ─────────────────────────────────────────────────────

"#
    )
}

/// Generate the `models/index.ts` barrel that re-exports every service's generated protobuf-es
/// modules (both the message types in `models_pb` and the service request/response types in
/// `svc_pb`).
///
/// `client.ts` imports message and response types from `"./models"`, so this barrel must surface
/// both `*_pb` files. The path for each is derived from the service's proto package
/// (e.g. `example.tags.v1` → `./gen/example/tags/v1/{models_pb,svc_pb}`).
pub(crate) fn generate_models_barrel(services: &[ServiceHandler<'_>]) -> String {
    let mut paths: Vec<String> = services
        .iter()
        .map(|s| s.plan.package.replace('.', "/"))
        .sorted()
        .dedup()
        .flat_map(|pkg| {
            [
                format!("export * from \"./gen/{pkg}/models_pb\";"),
                format!("export * from \"./gen/{pkg}/svc_pb\";"),
            ]
        })
        .collect();
    paths.push(String::new()); // trailing newline
    paths.join("\n")
}

/// Generate the complete `client.ts` file for all services.
pub(crate) fn generate_client_ts(services: &[ServiceHandler<'_>]) -> String {
    let bindings = services
        .first()
        .expect("binding output has a service")
        .config
        .bindings_config();

    // Sort once up-front so all loops below produce stable output regardless of
    // the HashMap iteration order of `CodeGenMetadata::services`.
    let sorted: Vec<&ServiceHandler<'_>> = services
        .iter()
        .sorted_by_key(|s| &s.plan.service_name)
        .collect();

    let mut out = String::new();

    out.push_str(&generate_imports_sorted(&sorted));
    out.push('\n');
    out.push_str(&generate_error_classes(bindings));

    // Generate options interfaces for all services
    for service in &sorted {
        for method in service.methods() {
            if let Some(iface) = generate_options_interface(&method) {
                out.push_str(&iface);
                out.push('\n');
            }
        }
    }

    // Generate resource client classes
    for service in &sorted {
        if let Some(class) = generate_resource_client_class(service) {
            out.push_str(&class);
            out.push('\n');
        }
    }

    // Generate the main aggregate client class
    out.push_str(&generate_aggregate_client_sorted(&sorted, bindings));

    out
}

fn generate_imports_sorted(services: &[&ServiceHandler<'_>]) -> String {
    let bindings = services
        .first()
        .expect("binding output has a service")
        .config
        .bindings_config();

    let napi_aggregate_name = format!("Napi{}", bindings.aggregate_client_name);

    let mut type_names: BTreeSet<String> = BTreeSet::new();

    for service in services {
        if let Some(resource) = service.resource() {
            type_names.insert(last_segment(&resource.type_name).to_string());
        }

        for method in service.methods() {
            // Only methods that actually surface on a client emit `fromBinary`/`toBinary` calls,
            // so only those contribute imports. A method that is dropped from both the scoped and
            // aggregate surfaces (e.g. a resource-collection custom verb on a Scoped service) must
            // not pull its types in, or Biome flags them as unused. See `method_is_emitted`.
            if !method_is_emitted(service, &method) {
                continue;
            }

            // Import exactly the type each method's generated code decodes (see
            // `decoded_type_name`): item type for standard list unwrapping, otherwise the full
            // output message. This keeps imports in lockstep with emitted `fromBinary` calls,
            // including resource-less (Flat) services that decode `*Response` messages directly.
            type_names.extend(decoded_type_name(&method));

            // Required message bodies are encoded with `toBinary(<Type>Schema, value)` before
            // crossing to the native binding, so import each body's type and schema too.
            type_names.extend(
                method
                    .required_parameters()
                    .filter(|param| is_required_message_body(param))
                    .filter_map(message_type_name),
            );
        }
    }

    let schema_names: BTreeSet<String> = type_names.iter().map(|n| format!("{n}Schema")).collect();

    let mut native_classes: Vec<String> = vec![format!("{} as NativeClient", napi_aggregate_name)];
    for service in services {
        if service.emits_scoped_binding() {
            let napi_name = format!("Napi{}", service.client_type());
            let native_alias = format!("Native{}", service.client_type());
            native_classes.push(format!("{napi_name} as {native_alias}"));
        }
    }
    // native_classes already stable since services slice is pre-sorted; sort for safety
    native_classes.sort();

    let type_imports = type_names
        .iter()
        .map(|t| format!("  {},", ts_type_import_clause(t)))
        .collect::<Vec<_>>()
        .join("\n");

    let schema_imports = schema_names
        .iter()
        .map(|s| format!("  {s},"))
        .collect::<Vec<_>>()
        .join("\n");

    let native_imports = native_classes
        .iter()
        .map(|n| format!("  {n},"))
        .collect::<Vec<_>>()
        .join("\n");

    format!(
        r#"import {{ fromBinary, toBinary }} from "@bufbuild/protobuf";
import {{
{type_imports}
{schema_imports}
}} from "./models";
import {{
{native_imports}
}} from "./native";
"#
    )
}

/// The model type name that a method's generated code decodes via `fromBinary`, if any.
///
/// Mirrors the per-request-type emit logic so the import set stays in lockstep with the emitted
/// `fromBinary(<Type>Schema, ...)` calls:
/// - standard `List` methods unwrap the repeated field → the item type (e.g. `Catalog`);
/// - every other returning method decodes its full output message (e.g. `TagAssignment`,
///   `ListTagAssignmentsResponse`);
/// - `Empty`-returning (void) methods decode nothing → `None`.
fn decoded_type_name(method: &MethodHandler<'_>) -> Option<String> {
    match &method.plan.request_type {
        RequestType::List => Some(
            method
                .list_output_field()?
                .unified_type
                .type_ident()
                .to_string(),
        ),
        _ => method.output_type().map(|t| t.to_string()),
    }
}

/// Whether a method produces any code on the generated client surface — and therefore contributes
/// imports. This mirrors the emit decisions made by [`generate_resource_client_class`] (the scoped
/// client) and [`generate_aggregate_client_sorted`] (the root client):
///
/// - **Flat** services emit *every* method onto the root client.
/// - **Scoped** services emit only their standard instance verbs (`Get`/`Update`/`Delete`) onto the
///   scoped client, plus their `List`/`Create` collection methods onto the root client. Both
///   surfaces match strictly on `request_type` — a `Custom` verb on a Scoped service is emitted by
///   neither, so its decoded/body types must not be imported or Biome flags them as unused.
fn method_is_emitted(service: &ServiceHandler<'_>, method: &MethodHandler<'_>) -> bool {
    match service.binding_mode() {
        BindingMode::Flat => true,
        BindingMode::Scoped => match &method.plan.request_type {
            // Surfaced on the scoped client (see `generate_resource_client_class`).
            RequestType::Get | RequestType::Update | RequestType::Delete => true,
            // Surfaced on the root client when classified as a collection method
            // (see `generate_aggregate_client_sorted`).
            RequestType::List | RequestType::Create => method.is_collection_method(),
            // Custom verbs on a Scoped service land on neither surface.
            RequestType::Custom(_) => false,
        },
    }
}

/// Generate an options interface for a method's optional parameters.
fn generate_options_interface(method: &MethodHandler<'_>) -> Option<String> {
    let optional_params: Vec<&RequestParam> = method
        .optional_parameters()
        .filter(|p| !p.is_path_param() && is_napi_supported(p))
        .collect();

    if optional_params.is_empty() {
        return None;
    }

    let interface_name = format!("{}Options", method.plan.metadata.method_name);

    let mut fields = String::new();
    for param in &optional_params {
        let ts_name = param.name().to_case(Case::Camel);
        let ts_type = unified_to_typescript(param.field_type());
        // Strip the " | undefined" suffix since we use `?:` syntax
        let ts_type = ts_type.strip_suffix(" | undefined").unwrap_or(&ts_type);
        if let Some(doc) = param.documentation() {
            let cleaned = doc.trim().replace('\n', "\n   * ");
            fields.push_str(&format!("  /** {cleaned} */\n"));
        }
        fields.push_str(&format!("  {ts_name}?: {ts_type};\n"));
    }

    Some(format!(
        "export interface {interface_name} {{\n{fields}}}\n"
    ))
}

/// Generate a resource client class (e.g. CatalogClient, SchemaClient).
///
/// Emitted only for services with a string-component scoped binding
/// ([`ServiceHandler::emits_scoped_binding`]): the class wraps a `Native<Client>` NAPI handle
/// and is `new`ed from the aggregate accessor. A resource whose identity a scoped client can't
/// express (e.g. a model version keyed by a composite `{full_name}` + integer `{version}`) has
/// no such NAPI class nor import, so emitting the wrapper here would reference an undeclared
/// `Native<Client>` and break `tsc`. Its methods live on the aggregate client instead.
fn generate_resource_client_class(service: &ServiceHandler<'_>) -> Option<String> {
    if !service.emits_scoped_binding() {
        return None;
    }
    let resource = service.resource()?;
    let type_name = resource
        .type_name
        .split('.')
        .next_back()
        .unwrap_or(&resource.type_name);
    let client_type = service.client_type().to_string();
    let native_type = format!("Native{client_type}");

    let mut methods = String::new();

    // The TS scoped class surfaces only the standard instance verbs (get/update/delete). Other
    // methods (collection methods, resource-targeted customs) live on the aggregate client.
    for method in service.methods() {
        match &method.plan.request_type {
            RequestType::Get => {
                methods.push_str(&generate_resource_get_method(
                    &method,
                    type_name,
                    BindingMode::Scoped,
                ));
            }
            RequestType::Update => {
                methods.push_str(&generate_resource_update_method(
                    &method,
                    type_name,
                    BindingMode::Scoped,
                ));
            }
            RequestType::Delete => {
                methods.push_str(&generate_resource_delete_method(
                    &method,
                    BindingMode::Scoped,
                ));
            }
            _ => {}
        }
    }

    // A scoped resource with no instance verbs (no get/update/delete) yields a class with no
    // members that read `inner`. Declaring `private readonly inner` + assigning it would then trip
    // Biome's `noUnusedPrivateClassMembers`; a plain `constructor(inner) {}` trips
    // `noUselessConstructor`. A TypeScript parameter property (`constructor(private readonly
    // inner)`) threads between both — the accessor can still `new` it with the native handle, and
    // the unused-field signal is at worst a non-failing warning on an intentionally inert class.
    let body = if methods.is_empty() {
        format!(
            r#"  /** @internal */
  constructor(private readonly inner: {native_type}) {{}}
"#
        )
    } else {
        format!(
            r#"  private readonly inner: {native_type};

  /** @internal */
  constructor(inner: {native_type}) {{
    this.inner = inner;
  }}

{methods}"#
        )
    };

    Some(format!(
        r#"export class {client_type} {{
{body}}}
"#
    ))
}

/// The required/optional param split for an instance-style (get/update/delete) TS method, using the
/// shared [`MethodHandler::param_plan_split`] for path/`page_token` filtering plus the NAPI
/// capability filter. Required params keep message bodies (passed as bytes); optional params don't.
fn ts_param_split<'a>(
    method: &'a MethodHandler<'a>,
    mode: BindingMode,
) -> (Vec<&'a RequestParam>, Vec<&'a RequestParam>) {
    let (required, optional) = method.param_plan_split(mode);
    (
        ts_capability_filter(required, true),
        ts_capability_filter(optional, false),
    )
}

/// The required/optional param split for a collection-style (list/create) TS method.
///
/// These helpers historically take an explicit `drop_path` flag (the scoped aggregate path passes
/// `true`, the flat path `false`) and filter `page_token` only on list methods, so we apply those
/// flags directly here rather than going through `param_plan_split` — preserving the TS-specific
/// behavior exactly. The NAPI capability filter is shared via [`ts_capability_filter`].
fn ts_collection_param_split<'a>(
    method: &'a MethodHandler<'a>,
    drop_path: bool,
    drop_page_token: bool,
) -> (Vec<&'a RequestParam>, Vec<&'a RequestParam>) {
    let required = method
        .required_parameters()
        .filter(|p| !(drop_path && p.is_path_param()))
        .collect();
    let optional = method
        .optional_parameters()
        .filter(|p| !(drop_path && p.is_path_param()))
        .filter(|p| !(drop_page_token && p.name() == "page_token"))
        .collect();
    (
        ts_capability_filter(required, true),
        ts_capability_filter(optional, false),
    )
}

/// Apply the NAPI capability filter shared by the Node and TS bindings: drop params NAPI can't pass.
/// Required params additionally keep message bodies (which cross as serialized bytes).
fn ts_capability_filter(
    params: Vec<&RequestParam>,
    keep_message_bodies: bool,
) -> Vec<&RequestParam> {
    params
        .into_iter()
        .filter(|p| is_napi_supported(p) || (keep_message_bodies && is_required_message_body(p)))
        .collect()
}

/// The TS method name and the native (NAPI) call name for a get/update/delete-style method.
///
/// - [`BindingMode::Scoped`]: short verb (`get`/`update`/`delete`) on the scoped client.
/// - [`BindingMode::Flat`]: the full base method name (camelCased) on the root client, matching
///   the NAPI-exposed flat method (snake_case Rust → camelCase JS).
fn instance_method_names(
    method: &MethodHandler<'_>,
    mode: BindingMode,
    verb: &str,
) -> (String, String) {
    match mode {
        BindingMode::Scoped => (verb.to_string(), verb.to_string()),
        BindingMode::Flat => {
            let name = method.js_method_name();
            (name.clone(), name)
        }
    }
}

fn generate_resource_get_method(
    method: &MethodHandler<'_>,
    type_name: &str,
    mode: BindingMode,
) -> String {
    generate_instance_returning_method(method, type_name, mode, "get")
}

fn generate_resource_update_method(
    method: &MethodHandler<'_>,
    type_name: &str,
    mode: BindingMode,
) -> String {
    generate_instance_returning_method(method, type_name, mode, "update")
}

/// Shared body for get/update-style methods: forward params and decode a typed response.
fn generate_instance_returning_method(
    method: &MethodHandler<'_>,
    type_name: &str,
    mode: BindingMode,
    verb: &str,
) -> String {
    let schema_name = format!("{type_name}Schema");
    let type_ref = ts_type_ident(type_name);
    let jsdoc = format_jsdoc(method.plan.metadata.documentation.as_deref(), "  ");
    let (ts_name, native_name) = instance_method_names(method, mode, verb);

    let (required_params, optional_params) = ts_param_split(method, mode);
    let spec = MethodCallSpec::build(method, &required_params, &optional_params);
    let MethodCallSpec {
        full_param_list,
        optional_destructure,
        all_args,
    } = spec;

    format!(
        r#"{jsdoc}  async {ts_name}({full_param_list}): Promise<{type_ref}> {{
{optional_destructure}    try {{
      return fromBinary({schema_name}, await this.inner.{native_name}({all_args}));
    }} catch (e) {{ throw parseNativeError(e); }}
  }}

"#
    )
}

fn generate_resource_delete_method(method: &MethodHandler<'_>, mode: BindingMode) -> String {
    let jsdoc = format_jsdoc(method.plan.metadata.documentation.as_deref(), "  ");
    let (ts_name, native_name) = instance_method_names(method, mode, "delete");

    let (required_params, optional_params) = ts_param_split(method, mode);
    let spec = MethodCallSpec::build(method, &required_params, &optional_params);
    let MethodCallSpec {
        full_param_list,
        optional_destructure,
        all_args,
    } = spec;

    format!(
        r#"{jsdoc}  async {ts_name}({full_param_list}): Promise<void> {{
{optional_destructure}    try {{
      await this.inner.{native_name}({all_args});
    }} catch (e) {{ throw parseNativeError(e); }}
  }}

"#
    )
}

/// Emit a single method for a resource-less (Flat) service onto the root client.
///
/// Every method of a resource-less service is emitted here, lowered [`BindingMode::Flat`] so the
/// signature includes all params (including path params) and forwards them to the native client
/// method of the same (camelCased) name. The emit shape is chosen by request type:
/// list/stream, create-with-return (or void), get/update-style returning, or delete (void).
fn generate_flat_method(method: &MethodHandler<'_>) -> String {
    let mode = BindingMode::Flat;
    // Flat methods never drop path params (the root client passes everything).
    match method.emit_shape() {
        EmitShape::List => {
            let mut out = generate_collection_list_method(method, false);
            out.push_str(&generate_collection_list_stream_method(method, false));
            out
        }
        EmitShape::Create => generate_collection_create_method(method, false),
        EmitShape::Delete => generate_resource_delete_method(method, mode),
        // Get / Update / resource-targeted custom: forward all params and decode the typed response.
        // An `Empty`-returning RPC produces a `Promise<void>`.
        EmitShape::GetUpdate => match method.output_type() {
            Some(output_type) => {
                generate_resource_get_method(method, &output_type.to_string(), mode)
            }
            None => generate_resource_delete_method(method, mode),
        },
    }
}

/// Generate the main aggregate client class (e.g. `MyServiceClient`).
fn generate_aggregate_client_sorted(
    services: &[&ServiceHandler<'_>],
    bindings: &BindingsConfig,
) -> String {
    let aggregate_client_name = &bindings.aggregate_client_name;

    let mut methods = String::new();

    for service in services {
        match service.binding_mode() {
            // Resource-scoped services contribute only collection-style methods to the root client;
            // their instance methods live on the scoped client. Path params are dropped here.
            BindingMode::Scoped => {
                for method in service.methods() {
                    if !method.is_collection_method() {
                        continue;
                    }
                    match &method.plan.request_type {
                        RequestType::List => {
                            methods.push_str(&generate_collection_list_method(&method, true));
                            methods
                                .push_str(&generate_collection_list_stream_method(&method, true));
                        }
                        RequestType::Create => {
                            methods.push_str(&generate_collection_create_method(&method, true));
                        }
                        _ => {}
                    }
                }

                // Resource accessor methods (e.g. .catalog("name"), .schema("cat", "schema")).
                // Skipped for resources without a string-component scoped client (see
                // `ServiceHandler::supports_scoped_client`).
                if service.supports_scoped_client()
                    && let Some(accessor) = generate_resource_accessor(service)
                {
                    methods.push_str(&accessor);
                }
            }
            // Resource-less services contribute *every* method to the root client, lowered flat:
            // each passes all params (including path params) straight to the native client.
            BindingMode::Flat => {
                for method in service.methods() {
                    methods.push_str(&generate_flat_method(&method));
                }
            }
        }
    }

    format!(
        r#"export class {aggregate_client_name} {{
  private readonly inner: NativeClient;

  constructor(url: string, token?: string) {{
    this.inner = NativeClient.fromUrl(url, token);
  }}

{methods}}}
"#
    )
}

/// Computed parameters for generating a typed aggregate-client method.
///
/// All three collection method variants (list, create-with-return, create-void) share
/// the same parameter-building logic. `MethodCallSpec` captures that shared state once
/// so the rendering functions only differ in their return type and native call expression.
struct MethodCallSpec {
    full_param_list: String,
    optional_destructure: String,
    all_args: String,
}

impl MethodCallSpec {
    fn build(
        method: &MethodHandler<'_>,
        required_params: &[&RequestParam],
        optional_params: &[&RequestParam],
    ) -> Self {
        let options_type = format!("{}Options", method.plan.metadata.method_name);

        let required_param_list = required_params
            .iter()
            .map(|p| {
                // A required message body is accepted as its typed object (e.g.
                // `tagPolicy: TagPolicy`) and serialized to bytes when forwarded to the native
                // binding (see `all_args` below). Reference the type through its (possibly aliased)
                // import name so a body named after a JS global resolves to its `$` alias.
                let ty = match message_type_name(p) {
                    Some(name) if is_required_message_body(p) => ts_type_ident(&name),
                    _ => unified_to_typescript(p.field_type()).replace(" | undefined", ""),
                };
                format!("{}: {}", p.name().to_case(Case::Camel), ty)
            })
            .collect::<Vec<_>>()
            .join(", ");

        let has_options = !optional_params.is_empty();

        let full_param_list = if has_options {
            if required_param_list.is_empty() {
                format!("options?: {options_type}")
            } else {
                format!("{required_param_list}, options?: {options_type}")
            }
        } else {
            required_param_list.clone()
        };

        let optional_destructure = if has_options {
            let fields = optional_params
                .iter()
                .map(|p| p.name().to_case(Case::Camel))
                .collect::<Vec<_>>()
                .join(", ");
            format!("    const {{ {fields} }} = options || {{}};\n")
        } else {
            String::new()
        };

        let mut args: Vec<String> = required_params
            .iter()
            .map(|p| {
                let name = p.name().to_case(Case::Camel);
                // Serialize required message bodies to protobuf bytes for the native binding.
                match message_type_name(p) {
                    // `toBinary` yields a `Uint8Array`; the native binding expects a Node `Buffer`.
                    Some(ty) if is_required_message_body(p) => {
                        format!("Buffer.from(toBinary({ty}Schema, {name}))")
                    }
                    _ => name,
                }
            })
            .collect();
        for p in optional_params {
            args.push(p.name().to_case(Case::Camel));
        }
        let all_args = args.join(", ");

        Self {
            full_param_list,
            optional_destructure,
            all_args,
        }
    }
}

fn generate_collection_list_method(method: &MethodHandler<'_>, drop_path: bool) -> String {
    let jsdoc = format_jsdoc(method.plan.metadata.documentation.as_deref(), "  ");
    let method_name = method.js_method_name();
    let items_field = match method.list_output_field() {
        Some(field) => field,
        None => return String::new(),
    };
    let item_type_name = items_field.unified_type.type_ident().to_string();
    let schema_name = format!("{item_type_name}Schema");
    let item_type_ref = ts_type_ident(&item_type_name);

    let (required_params, optional_params) = ts_collection_param_split(method, drop_path, true);

    let spec = MethodCallSpec::build(method, &required_params, &optional_params);
    let MethodCallSpec {
        full_param_list,
        optional_destructure,
        all_args,
    } = spec;

    format!(
        r#"{jsdoc}  async {method_name}({full_param_list}): Promise<{item_type_ref}[]> {{
{optional_destructure}    try {{
      return (await this.inner.{method_name}({all_args})).map((data) =>
        fromBinary({schema_name}, data),
      );
    }} catch (e) {{ throw parseNativeError(e); }}
  }}

"#
    )
}

/// Generate a streaming variant of a list method that yields items via `AsyncIterable<T>`.
///
/// The native Rust side returns a `ReadableStream<Buffer>` (napi-rs v3). On the TypeScript
/// side we wrap it in an async generator so callers can use `for await...of` directly.
/// Node.js 18+ (the minimum engine version) supports `for await...of` over `ReadableStream`.
fn generate_collection_list_stream_method(method: &MethodHandler<'_>, drop_path: bool) -> String {
    let jsdoc = format_jsdoc(method.plan.metadata.documentation.as_deref(), "  ");
    let base_method_name = method.js_method_name();
    let stream_method_name = format!("{base_method_name}Stream");

    let items_field = match method.list_output_field() {
        Some(field) => field,
        None => return String::new(),
    };
    let item_type_name = items_field.unified_type.type_ident().to_string();
    let schema_name = format!("{item_type_name}Schema");
    let item_type_ref = ts_type_ident(&item_type_name);

    let (required_params, optional_params) = ts_collection_param_split(method, drop_path, true);

    let spec = MethodCallSpec::build(method, &required_params, &optional_params);
    let MethodCallSpec {
        full_param_list,
        optional_destructure,
        all_args,
    } = spec;

    format!(
        r#"{jsdoc}  async *{stream_method_name}({full_param_list}): AsyncIterable<{item_type_ref}> {{
{optional_destructure}    try {{
      for await (const data of this.inner.{base_method_name}Stream({all_args})) {{
        yield fromBinary({schema_name}, data);
      }}
    }} catch (e) {{ throw parseNativeError(e); }}
  }}

"#
    )
}

fn generate_collection_create_method(method: &MethodHandler<'_>, drop_path: bool) -> String {
    let output_type = match method.output_type() {
        Some(t) => t.to_string(),
        None => return generate_void_create_method(method, drop_path),
    };
    let schema_name = format!("{output_type}Schema");
    let output_type_ref = ts_type_ident(&output_type);

    let jsdoc = format_jsdoc(method.plan.metadata.documentation.as_deref(), "  ");
    let method_name = method.js_method_name();

    let (required_params, optional_params) = ts_collection_param_split(method, drop_path, false);

    let spec = MethodCallSpec::build(method, &required_params, &optional_params);
    let MethodCallSpec {
        full_param_list,
        optional_destructure,
        all_args,
    } = spec;

    format!(
        r#"{jsdoc}  async {method_name}({full_param_list}): Promise<{output_type_ref}> {{
{optional_destructure}    try {{
      return fromBinary({schema_name}, await this.inner.{method_name}({all_args}));
    }} catch (e) {{ throw parseNativeError(e); }}
  }}

"#
    )
}

fn generate_void_create_method(method: &MethodHandler<'_>, drop_path: bool) -> String {
    let jsdoc = format_jsdoc(method.plan.metadata.documentation.as_deref(), "  ");
    let method_name = method.js_method_name();

    let (required_params, optional_params) = ts_collection_param_split(method, drop_path, false);
    let spec = MethodCallSpec::build(method, &required_params, &optional_params);
    let MethodCallSpec {
        full_param_list,
        optional_destructure,
        all_args,
    } = spec;

    format!(
        r#"{jsdoc}  async {method_name}({full_param_list}): Promise<void> {{
{optional_destructure}    try {{
      await this.inner.{method_name}({all_args});
    }} catch (e) {{ throw parseNativeError(e); }}
  }}

"#
    )
}

fn generate_resource_accessor(service: &ServiceHandler<'_>) -> Option<String> {
    let spec = service.accessor_spec()?;
    let method_name = spec.singular.to_case(Case::Camel);
    let client_type = service.client_type().to_string();

    // TS forwards every param to the NAPI accessor, which performs any full-name join internally —
    // so the TS layer doesn't branch on `spec.nested`, it just passes the params through.
    let param_list = spec
        .params
        .iter()
        .map(|p| format!("{}: string", p.to_case(Case::Camel)))
        .collect::<Vec<_>>()
        .join(", ");

    let arg_list = spec
        .params
        .iter()
        .map(|p| p.to_case(Case::Camel))
        .collect::<Vec<_>>()
        .join(", ");

    Some(format!(
        r#"  {method_name}({param_list}): {client_type} {{
    return new {client_type}(this.inner.{method_name}({arg_list}));
  }}

"#
    ))
}