olai-codegen 0.0.13

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
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
//! End-to-end generation-path tests driven by the committed `example.bin`
//! `FileDescriptorSet`.
//!
//! These exercise generators that previously had no integration coverage:
//! - HTTP client method generation (URL building, query params, error handling)
//! - Handler trait generation
//! - Resource-enum + conversion generation (`Resource`/`ObjectLabel`, `TryFrom`,
//!   `RESOURCE_DESCRIPTORS`)
//! - Node TypeScript bindings

use std::path::{Path, PathBuf};

use olai_codegen::parsing::parse_file_descriptor_set;
use olai_codegen::{BindingsConfig, CodeGenConfig, CodeGenMetadata, CodeGenOutput, generate_code};
use protobuf::Message;
use protobuf::descriptor::FileDescriptorSet;
use tempfile::TempDir;

fn metadata() -> CodeGenMetadata {
    let bytes = include_bytes!("../proto/example.bin");
    let fds = FileDescriptorSet::parse_from_bytes(bytes).expect("valid descriptor");
    parse_file_descriptor_set(&fds).expect("parse succeeds")
}

fn walk(dir: &Path) -> Vec<PathBuf> {
    let mut files = Vec::new();
    if let Ok(rd) = std::fs::read_dir(dir) {
        for e in rd.flatten() {
            let p = e.path();
            if p.is_dir() {
                files.extend(walk(&p));
            } else {
                files.push(p);
            }
        }
    }
    files
}

fn read_all(dir: &Path) -> String {
    walk(dir)
        .iter()
        .filter_map(|p| std::fs::read_to_string(p).ok())
        .collect::<Vec<_>>()
        .join("\n")
}

/// Build a config that drives the Rust server/client/models generators.
fn rust_config(tmp: &Path) -> CodeGenConfig {
    let common = tmp.join("common");
    let models = tmp.join("models");
    let server = tmp.join("server");
    let client = tmp.join("client");
    for d in [&common, &models, &server, &client] {
        std::fs::create_dir_all(d).expect("create dir");
    }
    CodeGenConfig {
        context_type_path: "crate::Context".into(),
        result_type_path: "crate::Result".into(),
        models_path_template: "example_common::models::{service}::v1".into(),
        models_path_crate_template: "crate::models::{service}::v1".into(),
        resource_store_crate_name: "olai_store".into(),
        runtime: olai_codegen::Runtime::Prost,
        transport_type_path: olai_codegen::DEFAULT_TRANSPORT_TYPE_PATH.into(),
        dual_transport: false,
        client_protocols: olai_codegen::ClientProtocols::default(),
        connect_client_path: None,
        rest_client: Default::default(),
        output: CodeGenOutput {
            common: Some(common),
            models: Some(models),
            models_subdir: "_gen".into(),
            server: Some(server),
            client: Some(client),
            python: None,
            node: None,
            node_ts: None,
            wasm: None,
            generate_resource_clients: false,
        },
        generate_resource_enum: true,
        generate_store_integration: true,
        error_type_path: Some("crate::Error".into()),
        generate_object_conversions: false,
        bindings: None,
    }
}

// ── WASM transport seam ──────────────────────────────────────────────────────

/// With a custom (WASM) transport configured, generated clients store and import that transport
/// instead of `CloudClient`, and the aggregate omits the cloud-only constructors — while the
/// output still parses as valid Rust.
#[test]
fn wasm_transport_is_substituted_into_generated_clients() {
    let tmp = TempDir::new().unwrap();
    let mut config = rust_config(tmp.path());
    config.transport_type_path = "olai_http_wasm::WasmClient".into();
    // The aggregate client (which carries the cloud-only ctors) is only emitted when bindings
    // are configured, so set them to exercise the ctor-gating path too.
    config.bindings = Some(BindingsConfig {
        aggregate_client_name: "ExampleClient".into(),
        client_crate_name: "example_client".into(),
        py_error_type: "PyExampleError".into(),
        py_result_type: "PyExampleResult".into(),
        napi_error_ext_trait: "NapiErrorExt".into(),
        ts_error_base_class: "ExampleError".into(),
        ts_error_code_prefix: "EX".into(),
        python: Default::default(),
    });
    generate_code(&metadata(), &config).expect("generation succeeds");

    let client_src = read_all(&tmp.path().join("client"));

    assert!(
        client_src.contains("olai_http_wasm :: WasmClient")
            || client_src.contains("olai_http_wasm::WasmClient"),
        "expected the WASM transport to be imported into generated client code"
    );
    assert!(
        !client_src.contains("use olai_http :: CloudClient")
            && !client_src.contains("use olai_http::CloudClient"),
        "CloudClient must not be imported when a WASM transport is configured"
    );
    // Cloud-only convenience ctors are meaningless for the browser transport.
    assert!(
        !client_src.contains("new_unauthenticated") && !client_src.contains("new_with_token"),
        "cloud-only aggregate ctors must not be emitted for a non-CloudClient transport"
    );

    // Every emitted client file must still parse.
    for path in walk(&tmp.path().join("client"))
        .into_iter()
        .filter(|p| p.extension().is_some_and(|e| e == "rs"))
    {
        let src = std::fs::read_to_string(&path).expect("read generated file");
        syn::parse_file(&src)
            .unwrap_or_else(|e| panic!("generated {} is invalid Rust: {e}", path.display()));
    }
}

/// The default config leaves `CloudClient` exactly as before (guards against the seam leaking
/// the new transport path into default output — the golden tests cover bytes, this covers intent).
#[test]
fn default_transport_still_uses_cloud_client() {
    let tmp = TempDir::new().unwrap();
    let config = rust_config(tmp.path());
    assert_eq!(config.transport_type_path, "olai_http::CloudClient");
    generate_code(&metadata(), &config).expect("generation succeeds");

    let client_src = read_all(&tmp.path().join("client"));
    assert!(
        client_src.contains("CloudClient"),
        "default transport must still emit CloudClient"
    );
    assert!(
        !client_src.contains("WasmClient"),
        "default transport must not mention the WASM transport"
    );
}

// ── WASM bindings (#[wasm_bindgen] + .d.ts) ───────────────────────────────────

/// The `wasm` output emits a `#[wasm_bindgen]` wrapper layer (valid Rust, wired to the WASM
/// transport + serde-wasm-bindgen) and a `client.d.ts` describing the JS surface.
#[test]
fn wasm_bindings_and_dts_are_emitted() {
    let tmp = TempDir::new().unwrap();
    let common = tmp.path().join("common");
    let client = tmp.path().join("client");
    let wasm = tmp.path().join("wasm");
    for d in [&common, &client, &wasm] {
        std::fs::create_dir_all(d).expect("create dir");
    }
    let config = CodeGenConfig {
        context_type_path: "crate::Context".into(),
        result_type_path: "crate::Result".into(),
        models_path_template: "example_common::models::{service}::v1".into(),
        models_path_crate_template: "crate::models::{service}::v1".into(),
        resource_store_crate_name: "olai_store".into(),
        // serde-native models + the browser transport are the intended pairing for wasm output.
        runtime: olai_codegen::Runtime::Buffa,
        transport_type_path: "olai_http_wasm::WasmClient".into(),
        dual_transport: false,
        client_protocols: olai_codegen::ClientProtocols::default(),
        connect_client_path: None,
        rest_client: Default::default(),
        output: CodeGenOutput {
            common: Some(common),
            models: None,
            models_subdir: "_gen".into(),
            server: None,
            client: Some(client),
            python: None,
            node: None,
            node_ts: None,
            wasm: Some(wasm.clone()),
            generate_resource_clients: false,
        },
        generate_resource_enum: false,
        generate_store_integration: false,
        error_type_path: None,
        generate_object_conversions: false,
        bindings: Some(BindingsConfig {
            aggregate_client_name: "ExampleClient".into(),
            client_crate_name: "example_client".into(),
            py_error_type: "PyExampleError".into(),
            py_result_type: "PyExampleResult".into(),
            napi_error_ext_trait: "NapiErrorExt".into(),
            ts_error_base_class: "ExampleError".into(),
            ts_error_code_prefix: "EX".into(),
            python: Default::default(),
        }),
    };
    generate_code(&metadata(), &config).expect("generation succeeds");

    // mod.rs: valid Rust, wasm-bindgen-annotated, wired to the wasm transport + serde bridge.
    // Emitted as `mod.rs` so the client crate mounts it with a plain `mod wasm;`.
    let bindings_rs = std::fs::read_to_string(wasm.join("mod.rs")).expect("wasm mod.rs written");
    syn::parse_file(&bindings_rs).expect("generated wasm mod.rs is valid Rust");
    assert!(
        bindings_rs.contains("wasm_bindgen"),
        "missing #[wasm_bindgen]"
    );
    assert!(
        bindings_rs.contains("olai_http_wasm") && bindings_rs.contains("WasmClient"),
        "wasm bindings must use the WasmClient transport"
    );
    assert!(
        bindings_rs.contains("serde_wasm_bindgen"),
        "wasm bindings must marshal via serde-wasm-bindgen"
    );
    // The aggregate wrapper is constructed from a base URL (browser-session model).
    assert!(
        bindings_rs.contains("WasmExampleClient")
            && bindings_rs.contains("js_class = \"ExampleClient\""),
        "expected the aggregate wasm wrapper exposed to JS as ExampleClient"
    );
    // The constructor takes optional options and wires bearer-token auth / credentials mode onto
    // the transport without forcing cookie mode off when no token is supplied.
    assert!(
        bindings_rs.contains("options: Option<JsValue>")
            && bindings_rs.contains("auth_token")
            && bindings_rs.contains("with_auth")
            && bindings_rs.contains("with_credentials"),
        "wasm bindings constructor must support an optional auth-token / credentials options object"
    );

    // client.d.ts: declares the aggregate class with a string-URL constructor.
    let dts = std::fs::read_to_string(wasm.join("client.d.ts")).expect("client.d.ts written");
    assert!(
        dts.contains("export class ExampleClient"),
        "d.ts must declare the aggregate class"
    );
    assert!(
        dts.contains("constructor(baseUrl: string"),
        "d.ts aggregate must take a base URL"
    );
    // The constructor accepts optional auth/session options (bearer token + credentials mode)
    // while keeping the base-URL-only call working.
    assert!(
        dts.contains("options?:") && dts.contains("authToken?:"),
        "d.ts aggregate constructor must document the optional auth options"
    );
    assert!(
        dts.contains("): Promise<"),
        "d.ts methods must return Promises"
    );
}

/// When WASM output is enabled, the generated client crate is built to compile
/// BOTH natively (`CloudClient`) and for the browser (`WasmClient`), selected by
/// `cfg(target_arch = "wasm32")` — so one crate serves server-side Rust consumers
/// and the frontend. The cloud-only ctors are gated to native; a browser ctor is
/// gated to wasm.
#[test]
fn wasm_output_emits_dual_cfg_gated_transport() {
    let tmp = TempDir::new().unwrap();
    let common = tmp.path().join("common");
    let client = tmp.path().join("client");
    let wasm = tmp.path().join("wasm");
    for d in [&common, &client, &wasm] {
        std::fs::create_dir_all(d).expect("create dir");
    }
    let mut config = rust_config(tmp.path());
    // Enabling wasm output flips the client into dual-transport mode.
    config.output.wasm = Some(wasm);
    config.bindings = Some(BindingsConfig {
        aggregate_client_name: "ExampleClient".into(),
        client_crate_name: "example_client".into(),
        py_error_type: "PyExampleError".into(),
        py_result_type: "PyExampleResult".into(),
        napi_error_ext_trait: "NapiErrorExt".into(),
        ts_error_base_class: "ExampleError".into(),
        ts_error_code_prefix: "EX".into(),
        python: Default::default(),
    });
    generate_code(&metadata(), &config).expect("generation succeeds");

    let client_src = read_all(&tmp.path().join("client"));

    // Both transports present, each gated by target arch.
    assert!(
        client_src.contains("cfg(target_arch = \"wasm32\")")
            || client_src.contains("cfg(target_arch = \"wasm32\")"),
        "dual-transport client must gate on target_arch"
    );
    assert!(
        client_src.contains("CloudClient") && client_src.contains("WasmClient"),
        "dual-transport client must reference both CloudClient and WasmClient"
    );
    // Cloud ctors gated to native; browser ctor gated to wasm.
    assert!(
        client_src.contains("new_with_token") && client_src.contains("new_in_browser"),
        "expected native cloud ctors + the browser ctor"
    );

    // Every emitted client file must still parse as valid Rust.
    for path in walk(&tmp.path().join("client"))
        .into_iter()
        .filter(|p| p.extension().is_some_and(|e| e == "rs"))
    {
        let src = std::fs::read_to_string(&path).expect("read generated file");
        syn::parse_file(&src)
            .unwrap_or_else(|e| panic!("generated {} is invalid Rust: {e}", path.display()));
    }
}

/// `dual_transport = true` (without any `output.wasm`) emits the same cfg-gated
/// `CloudClient`/`WasmClient` `Transport` alias as WASM output does, but WITHOUT
/// the `#[wasm_bindgen]` JS binding layer. This lets a project build one client
/// crate for native + `wasm32` while keeping the crate free of a JS ABI.
#[test]
fn dual_transport_flag_emits_alias_without_wasm_bindings() {
    let tmp = TempDir::new().unwrap();
    let mut config = rust_config(tmp.path());
    // The wasm transport requires the buffa runtime; no `output.wasm` is set.
    config.runtime = olai_codegen::Runtime::Buffa;
    config.dual_transport = true;
    assert!(
        config.output.wasm.is_none(),
        "no JS bindings output configured"
    );
    generate_code(&metadata(), &config).expect("generation succeeds");

    let client_src = read_all(&tmp.path().join("client"));

    // The cfg-gated dual alias is present…
    assert!(
        client_src.contains("cfg(target_arch = \"wasm32\")")
            && client_src.contains("CloudClient")
            && client_src.contains("WasmClient"),
        "dual_transport must emit the cfg-gated CloudClient/WasmClient alias"
    );
    // …but NOT the wasm-bindgen JS layer.
    assert!(
        !client_src.contains("wasm_bindgen"),
        "dual_transport alone must not emit #[wasm_bindgen] bindings"
    );

    // Every emitted client file must still parse as valid Rust.
    for path in walk(&tmp.path().join("client"))
        .into_iter()
        .filter(|p| p.extension().is_some_and(|e| e == "rs"))
    {
        let src = std::fs::read_to_string(&path).expect("read generated file");
        syn::parse_file(&src)
            .unwrap_or_else(|e| panic!("generated {} is invalid Rust: {e}", path.display()));
    }
}

// ── Generated code is syntactically valid Rust ───────────────────────────────

/// Every emitted `.rs` file must parse as a Rust source file.
///
/// The substring assertions elsewhere in this suite can't catch structural defects like
/// duplicate `pub mod` blocks (E0428) or stray tokens — only a real parse can. This is the
/// cheap guard that keeps the generator's core invariant ("the output is valid Rust") honest
/// without standing up a full `cargo check` fixture crate.
#[test]
fn all_generated_rust_files_parse() {
    let tmp = TempDir::new().unwrap();
    let mut config = rust_config(tmp.path());
    config.generate_object_conversions = true;
    generate_code(&metadata(), &config).expect("generation succeeds");

    let rust_files: Vec<PathBuf> = ["common", "models", "server", "client"]
        .iter()
        .flat_map(|d| walk(&tmp.path().join(d)))
        .filter(|p| p.extension().is_some_and(|e| e == "rs"))
        .collect();

    assert!(
        !rust_files.is_empty(),
        "expected generated .rs files, found none"
    );

    for path in &rust_files {
        let src = std::fs::read_to_string(path).expect("read generated file");
        if let Err(err) = syn::parse_file(&src) {
            panic!(
                "generated file {} is not valid Rust: {err}\n---\n{src}",
                path.display()
            );
        }
    }
}

// ── HTTP client method generation ───────────────────────────────────────────

#[test]
fn client_methods_build_urls_query_and_error_handling() {
    let tmp = TempDir::new().unwrap();
    let config = rust_config(tmp.path());
    generate_code(&metadata(), &config).expect("generation succeeds");

    let client = read_all(&tmp.path().join("client"));

    // GET-by-name builds a templated path from the percent-encoded request field.
    assert!(
        client.contains("\"catalogs/{}\", encode_path_value(& request.name, false)"),
        "GET path templating missing:\n{client}"
    );
    assert!(
        client.contains("fn encode_path_value("),
        "path encoding helper missing"
    );
    // Collection POST hits the bare collection URL.
    assert!(
        client.contains("self.base_url.join(\"catalogs\")"),
        "collection URL join missing"
    );
    // List method appends query params.
    assert!(
        client.contains("append_pair(\"max_results\"")
            && client.contains("append_pair(\"page_token\""),
        "list query-param appends missing"
    );
    // Non-success responses are converted to errors, not unwrapped.
    assert!(
        client.contains("if !response.status().is_success()")
            && client.contains("parse_error_response(response)"),
        "client error-handling missing"
    );
    // HTTP verbs are dispatched correctly per RPC.
    assert!(client.contains(".post(url)"), "POST verb missing");
    assert!(client.contains(".patch(url)"), "PATCH verb missing");
    assert!(client.contains(".delete(url)"), "DELETE verb missing");
}

// ── Per-resource client features + client handler impls ──────────────────────

/// A client config that also emits the aggregate and resource-scoped clients, so every gated
/// site (service modules, aggregate accessors, child navigators) is exercised.
fn full_client_config(tmp: &Path) -> CodeGenConfig {
    let mut config = rust_config(tmp);
    config.output.generate_resource_clients = true;
    config.bindings = Some(BindingsConfig {
        aggregate_client_name: "ExampleClient".into(),
        client_crate_name: "example_client".into(),
        py_error_type: "PyExampleError".into(),
        py_result_type: "PyExampleResult".into(),
        napi_error_ext_trait: "NapiErrorExt".into(),
        ts_error_base_class: "ExampleError".into(),
        ts_error_code_prefix: "EX".into(),
        python: Default::default(),
    });
    config
}

fn assert_client_files_parse(client_dir: &Path) {
    for path in walk(client_dir)
        .into_iter()
        .filter(|p| p.extension().is_some_and(|e| e == "rs"))
    {
        let src = std::fs::read_to_string(&path).expect("read generated file");
        syn::parse_file(&src)
            .unwrap_or_else(|e| panic!("generated {} is invalid Rust: {e}", path.display()));
    }
}

#[test]
fn client_resource_features_gate_services_on_model_package() {
    let tmp = TempDir::new().unwrap();
    let mut config = full_client_config(tmp.path());
    config.rest_client.resource_features = true;
    generate_code(&metadata(), &config).expect("generation succeeds");

    let codegen = tmp.path().join("client");
    let root = std::fs::read_to_string(codegen.join("mod.rs")).unwrap();
    // Features are named after the model package, not the service: both catalog-package services
    // share `catalog`.
    for (feature, module) in [
        ("catalog", "catalog"),
        ("catalog", "query"),
        ("schemas", "schema"),
        ("tags", "tag_assignments"),
    ] {
        let gated = format!("#[cfg(feature = \"{feature}\")]\npub mod {module};");
        assert!(root.contains(&gated), "missing `{gated}` in:\n{root}");
    }

    // Each service's aggregate accessors live in their own gated impl block.
    let aggregate = std::fs::read_to_string(codegen.join("client.rs")).unwrap();
    assert!(
        aggregate.contains("#[cfg(feature = \"schemas\")]\nimpl ExampleClient"),
        "aggregate accessors are not gated per service:\n{aggregate}"
    );

    // A parent's child navigators carry the child's gate.
    let catalog_resource = std::fs::read_to_string(codegen.join("catalog/resource.rs")).unwrap();
    assert!(
        catalog_resource.contains("#[cfg(feature = \"schemas\")]"),
        "child navigators are not gated on the child's feature:\n{catalog_resource}"
    );

    assert_client_files_parse(&tmp.path().join("client"));
}

#[test]
fn client_output_is_ungated_by_default() {
    let tmp = TempDir::new().unwrap();
    generate_code(&metadata(), &full_client_config(tmp.path())).expect("generation succeeds");

    let client_src = read_all(&tmp.path().join("client"));
    assert!(
        !client_src.contains("cfg(feature"),
        "default client output must not carry feature gates"
    );
    assert!(
        !walk(&tmp.path().join("client"))
            .iter()
            .any(|p| p.ends_with("handler.rs")),
        "handler impls must be opt-in"
    );
}

#[test]
fn client_handler_impls_forward_to_service_clients() {
    let tmp = TempDir::new().unwrap();
    let mut config = full_client_config(tmp.path());
    config.rest_client.handler_impls = Some(olai_codegen::ClientHandlerImpls {
        crate_path: "example_handlers".into(),
        feature: "handlers".into(),
        skip: vec!["tag_assignments".into()],
    });
    generate_code(&metadata(), &config).expect("generation succeeds");

    let catalogs = tmp.path().join("client/catalog");
    let module = std::fs::read_to_string(catalogs.join("mod.rs")).unwrap();
    assert!(
        module.contains(
            "#[cfg(all(feature = \"handlers\", not(target_arch = \"wasm32\")))]\nmod handler;"
        ),
        "handler module is not mounted behind the feature:\n{module}"
    );

    let handler = std::fs::read_to_string(catalogs.join("handler.rs")).unwrap();
    assert!(
        handler.contains("example_handlers::catalog::CatalogHandler<Cx>")
            && handler.contains("for CatalogServiceClient"),
        "missing handler impl for the service client:\n{handler}"
    );
    assert!(
        handler.contains("CatalogServiceClient::get_catalog(self, &request)")
            && handler.contains("-> example_handlers::Result<"),
        "trait methods must forward to the inherent client method:\n{handler}"
    );

    assert!(
        !tmp.path()
            .join("client/tag_assignments/handler.rs")
            .exists(),
        "skipped services must not get a generated impl"
    );
    assert_client_files_parse(&tmp.path().join("client"));
}

// ── Handler trait generation ─────────────────────────────────────────────────

#[test]
fn handler_trait_has_async_methods_per_rpc() {
    let tmp = TempDir::new().unwrap();
    let config = rust_config(tmp.path());
    generate_code(&metadata(), &config).expect("generation succeeds");

    let server = read_all(&tmp.path().join("server"));

    assert!(
        server.contains("pub trait CatalogHandler"),
        "handler trait missing:\n{server}"
    );
    assert!(
        server.contains("#[async_trait]"),
        "async_trait attr missing"
    );
    // One async fn per RPC, taking the request + context and returning the result type.
    for method in [
        "async fn create_catalog",
        "async fn get_catalog",
        "async fn list_catalogs",
        "async fn update_catalog",
        "async fn delete_catalog",
    ] {
        assert!(server.contains(method), "handler missing `{method}`");
    }
    assert!(
        server.contains("context: Cx") && server.contains("-> Result<Catalog>"),
        "handler method signature shape unexpected"
    );
}

/// Query-param extractors must only mark optional/repeated fields `#[serde(default)]`.
///
/// Required query params (proto3 fields not marked `optional`) must have NO default, so omitting
/// one is a deserialization error rather than silently defaulting — regression guard for the
/// extractor `serde(default)` policy.
#[test]
fn required_query_params_have_no_serde_default() {
    let tmp = TempDir::new().unwrap();
    let config = rust_config(tmp.path());
    generate_code(&metadata(), &config).expect("generation succeeds");

    let common = read_all(&tmp.path().join("common"));

    // `max_results`/`page_token` on ListCatalogs are required scalars → emitted with no default.
    assert!(
        common.contains("max_results: i32,") && common.contains("page_token: String,"),
        "required query params should be plain fields:\n{common}"
    );
    assert!(
        !common.contains("#[serde(default)]\n            max_results")
            && !common.contains("#[serde(default)] max_results"),
        "required query param `max_results` must NOT carry #[serde(default)]:\n{common}"
    );
    // Repeated `tags` (Vec) still gets a default so an absent key → empty Vec.
    assert!(
        common.contains("tags: Vec<String>"),
        "repeated query param `tags` missing:\n{common}"
    );
}

// ── Resource-enum + conversions ──────────────────────────────────────────────

#[test]
fn resource_enum_and_conversions_generated() {
    let tmp = TempDir::new().unwrap();
    let config = rust_config(tmp.path());
    generate_code(&metadata(), &config).expect("generation succeeds");

    let labels = read_all(&tmp.path().join("models"));

    // Resource enum variant wraps the fully-qualified model path.
    assert!(
        labels.contains("pub enum Resource")
            && labels.contains("Catalog(super::catalog::v1::Catalog)"),
        "Resource enum variant missing:\n{labels}"
    );
    // ObjectLabel discriminant enum.
    assert!(
        labels.contains("pub enum ObjectLabel") && labels.contains("Catalog,"),
        "ObjectLabel enum missing"
    );
    // From + TryFrom<Resource> conversions (gated on error_type_path).
    assert!(
        labels.contains("impl From<super::catalog::v1::Catalog> for Resource"),
        "From<Catalog> for Resource missing"
    );
    assert!(
        labels.contains("impl TryFrom<Resource> for super::catalog::v1::Catalog"),
        "TryFrom<Resource> missing"
    );
    // resource_label() discriminant accessor.
    assert!(
        labels.contains("fn resource_label(&self) -> &ObjectLabel"),
        "resource_label accessor missing"
    );
}

#[test]
fn resource_registry_descriptors_generated() {
    let tmp = TempDir::new().unwrap();
    let config = rust_config(tmp.path());
    generate_code(&metadata(), &config).expect("generation succeeds");

    let labels = read_all(&tmp.path().join("models"));

    assert!(
        labels.contains("impl ::olai_store::Label for ObjectLabel"),
        "Label impl missing:\n{labels}"
    );
    assert!(
        labels.contains("pub static RESOURCE_DESCRIPTORS"),
        "RESOURCE_DESCRIPTORS static missing"
    );
    assert!(
        labels.contains("ObjectLabel::Catalog") && labels.contains("FieldRole::"),
        "descriptor entry contents missing"
    );
    // A flat resource's name decomposes to just `["name"]` — standard List fields like
    // `page_token` must not leak into the path components (regression guard for the
    // proto3-presence heuristic).
    assert!(
        labels.contains("path_names: &[\"name\"]"),
        "Catalog path_names should be [\"name\"], not include pagination fields:\n{labels}"
    );
    assert!(
        !labels.contains("page_token\", \"name"),
        "pagination field leaked into path_names:\n{labels}"
    );
}

#[test]
fn resource_enum_skipped_when_disabled() {
    let tmp = TempDir::new().unwrap();
    let mut config = rust_config(tmp.path());
    config.generate_resource_enum = false;
    config.generate_store_integration = false;
    config.error_type_path = None;
    generate_code(&metadata(), &config).expect("generation succeeds");

    // labels.rs should not be written when the resource enum is disabled.
    let labels_path = tmp.path().join("models").join("_gen").join("labels.rs");
    assert!(
        !labels_path.exists(),
        "labels.rs should not be generated when generate_resource_enum is false"
    );
}

// ── Node TypeScript bindings ──────────────────────────────────────────────────

#[test]
fn node_ts_bindings_generated() {
    let tmp = TempDir::new().unwrap();
    let common = tmp.path().join("common");
    let node_ts = tmp.path().join("node_ts");
    for d in [&common, &node_ts] {
        std::fs::create_dir_all(d).expect("create dir");
    }
    let config = CodeGenConfig {
        context_type_path: "crate::Context".into(),
        result_type_path: "crate::Result".into(),
        models_path_template: "example_common::models::{service}::v1".into(),
        models_path_crate_template: "crate::models::{service}::v1".into(),
        resource_store_crate_name: "olai_store".into(),
        runtime: olai_codegen::Runtime::Prost,
        transport_type_path: olai_codegen::DEFAULT_TRANSPORT_TYPE_PATH.into(),
        dual_transport: false,
        client_protocols: olai_codegen::ClientProtocols::default(),
        connect_client_path: None,
        rest_client: Default::default(),
        output: CodeGenOutput {
            common: Some(common),
            models: None,
            models_subdir: "_gen".into(),
            server: None,
            client: None,
            python: None,
            node: None,
            node_ts: Some(node_ts.clone()),
            wasm: None,
            generate_resource_clients: false,
        },
        generate_resource_enum: false,
        generate_store_integration: false,
        error_type_path: None,
        generate_object_conversions: false,
        bindings: Some(BindingsConfig {
            aggregate_client_name: "ExampleClient".into(),
            client_crate_name: "example_client".into(),
            py_error_type: "PyExampleError".into(),
            py_result_type: "PyExampleResult".into(),
            napi_error_ext_trait: "NapiErrorExt".into(),
            ts_error_base_class: "ExampleError".into(),
            ts_error_code_prefix: "EX".into(),
            python: Default::default(),
        }),
    };
    generate_code(&metadata(), &config).expect("generation succeeds");

    let ts = std::fs::read_to_string(node_ts.join("client.ts")).expect("client.ts written");
    assert!(
        ts.contains("ExampleClient"),
        "aggregate client name missing"
    );
    assert!(ts.contains("ExampleError"), "error base class missing");
}

// ── REST client and Python options ───────────────────────────────────────────

/// Every REST client and Python option at once: the output parses and has the expected parts.
/// The opt-in `tests/rest_client_e2e` fixture compiles and runs it against a server.
#[test]
fn rest_client_and_python_options_generate_valid_code() {
    let tmp = TempDir::new().unwrap();
    let mut config = rust_config(tmp.path());
    config.runtime = olai_codegen::Runtime::Buffa;
    config.transport_type_path = olai_codegen::REQWEST_TRANSPORT_TYPE_PATH.into();
    config.output.generate_resource_clients = true;
    let python = tmp.path().join("python");
    let package = tmp.path().join("pkg");
    config.output.python = Some(python.clone());
    config.rest_client = olai_codegen::RestClientOptions {
        json_int64_as_number: true,
        ignore_unknown_enum_values: true,
        error_module: Some(Default::default()),
        form_encoded_methods: vec![],
        path_fields_in_body_methods: vec![],
        json_query_packages: vec![],
        user_agent: Some("example-client".into()),
        ..Default::default()
    };
    config.bindings = Some(BindingsConfig {
        aggregate_client_name: "ExampleClient".into(),
        client_crate_name: "example_client".into(),
        py_error_type: "PyExampleError".into(),
        py_result_type: "PyExampleResult".into(),
        napi_error_ext_trait: "NapiErrorExt".into(),
        ts_error_base_class: "ExampleError".into(),
        ts_error_code_prefix: "EX".into(),
        python: Some(olai_codegen::PythonOptions {
            package: olai_codegen::PyPackageConfig {
                dir: package.clone(),
                name: "example".into(),
            },
            error_base_class: "ExampleError".into(),
            module: "example._core".into(),
            async_methods: true,
            keyword_only: true,
            public_modules: true,
            user_agent: Some("example-python".into()),
            exports: vec![
                "crate::extras::PyHelper".into(),
                "crate::extras::helper_fn".into(),
            ],
        }),
    });
    generate_code(&metadata(), &config).expect("generation succeeds");

    for dir in ["client", "python", "models"] {
        for path in walk(&tmp.path().join(dir))
            .into_iter()
            .filter(|p| p.extension().is_some_and(|e| e == "rs"))
        {
            let src = std::fs::read_to_string(&path).unwrap();
            syn::parse_file(&src)
                .unwrap_or_else(|e| panic!("generated {} is invalid Rust: {e}", path.display()));
        }
    }

    let client = read_all(&tmp.path().join("client"));
    assert!(
        client.contains("pub struct HttpClient"),
        "reqwest transport missing"
    );
    assert!(
        client.contains("pub struct ApiError"),
        "error module missing"
    );
    assert!(client.contains("ignore_unknown_enum_values(true)"));
    assert!(
        client.contains("\"example-client/\"") && client.contains("not(target_arch = \"wasm32\")"),
        "default User-Agent missing"
    );
    assert!(client.contains("pub fn with_user_agent("));

    let models = read_all(&tmp.path().join("models"));
    assert!(
        models.contains("pub mod json_int64"),
        "int64 helpers missing"
    );
    assert!(models.contains("frozen"), "frozen models missing");
    assert!(
        models.contains("const INPUT_TYPE"),
        "enum type hints missing"
    );
    assert!(models.contains("__python_repr"), "Python repr missing");

    let bindings = read_all(&python);
    assert!(bindings.contains("_async"), "async twins missing");
    assert!(
        bindings.contains("#[pymodule_export]\n    use crate::extras::PyHelper;")
            && bindings.contains("use crate::extras::helper_fn;"),
        "hand-written exports missing from the extension module"
    );
    assert!(
        bindings.contains("trait ApiErrorAnswer")
            && bindings.contains("impl ApiErrorAnswer for ClientError"),
        "client error mapping missing"
    );
    assert!(
        bindings.contains("#[pyo3(name = \"_core\", module = \"example\")]")
            && bindings.contains("pub mod extension_module"),
        "extension module missing"
    );
    assert!(bindings.contains("PyFuture"), "PyFuture helper missing");
    assert!(
        bindings.contains("\"example-python/\""),
        "Python User-Agent missing"
    );
    assert!(bindings.contains("pub fn rt()"), "runtime missing");

    let enums = std::fs::read_to_string(package.join("_enums.py")).unwrap();
    assert!(enums.contains("(enum.StrEnum):"), "{enums}");
    assert!(
        !enums.contains("_UNSPECIFIED ="),
        "hidden zero values: {enums}"
    );
    let schemas = std::fs::read_to_string(package.join("schemas.py")).unwrap();
    assert!(
        schemas.contains("from example._core.schemas import (\n    DeleteSchemaResponse,")
            && schemas.contains("    SchemaClient,\n)")
            && schemas.contains("from example._enums import (\n    GetSchemaRequestView,")
            && schemas.contains("    \"SchemaType\",\n]"),
        "{schemas}"
    );
    assert!(
        bindings.contains("extends = ExampleError")
            && bindings.contains("use crate::codegen::error::{\n        ExampleError,"),
        "PyO3 exception classes missing"
    );
}

// ── Without the common (extractor) output ────────────────────────────────────

#[test]
fn no_common_output_leaves_out_the_extractors() {
    let tmp = TempDir::new().unwrap();
    let mut config = rust_config(tmp.path());
    config.output.common = None;
    config.output.server = None;
    generate_code(&metadata(), &config).expect("generation succeeds");

    let models = tmp.path().join("models/_gen");
    assert!(
        !models.join("extractors").exists(),
        "no extractors without `common`"
    );
    let models_mod = std::fs::read_to_string(models.join("mod.rs")).expect("models mod.rs");
    assert!(
        !models_mod.contains("extractors"),
        "the models mod.rs must not declare the extractors"
    );
    syn::parse_file(&models_mod).expect("the models mod.rs is valid Rust");
}

#[test]
fn server_output_needs_the_common_output() {
    let tmp = TempDir::new().unwrap();
    let mut config = rust_config(tmp.path());
    config.output.common = None;
    let err = generate_code(&metadata(), &config).expect_err("a server needs `common`");
    assert!(err.to_string().contains("CodeGenOutput::common"), "{err}");
}

// ── JSON-named query keys ────────────────────────────────────────────────────

/// Methods whose input is in a `json_query_packages` package send (client) and read (server)
/// lowerCamelCase query keys; a package matches only at a `.` boundary, so `example.schema`
/// leaves `example.schemas.v1` on the proto names.
#[test]
fn json_query_packages_select_lower_camel_query_keys() {
    let tmp = TempDir::new().unwrap();
    let mut config = rust_config(tmp.path());
    config.rest_client.json_query_packages =
        vec!["example.catalog.v1".into(), "example.schema".into()];
    generate_code(&metadata(), &config).expect("generation succeeds");

    let catalog = read_all(&tmp.path().join("client/catalog"));
    let schemas = read_all(&tmp.path().join("client/schema"));
    assert!(
        catalog.contains("append_pair(\"maxResults\""),
        "the catalog client must send the JSON name:\n{catalog}"
    );
    assert!(
        schemas.contains("append_pair(\"max_results\"") && !schemas.contains("\"maxResults\""),
        "`example.schema` must not match `example.schemas.v1`:\n{schemas}"
    );

    // The server's query extractors are emitted with the models, per service.
    let extractor = |service: &str| {
        walk(&tmp.path().join("common"))
            .into_iter()
            .find(|p| p.ends_with(format!("extractors/{service}/server.rs")))
            .map(|p| std::fs::read_to_string(p).unwrap())
            .unwrap_or_else(|| panic!("no query extractor for {service}"))
    };
    let catalog_server = extractor("catalog");
    assert!(
        catalog_server.contains("#[serde(rename = \"maxResults\")]"),
        "the server extractor must read the key the client sends:\n{catalog_server}"
    );
    let schemas_server = extractor("schema");
    assert!(
        schemas_server.contains("max_results") && !schemas_server.contains("\"maxResults\""),
        "{schemas_server}"
    );
}

/// Without the generated client error module, the Python bindings still build on the client's
/// `error::Error`, but the client crate implements `ApiErrorAnswer` for it by hand: `error.rs`
/// declares the trait and leaves the impl out.
#[test]
fn python_bindings_without_error_module_leave_api_error_answer_to_the_crate() {
    let tmp = TempDir::new().unwrap();
    let mut config = full_client_config(tmp.path());
    let python = tmp.path().join("python");
    config.output.python = Some(python.clone());
    config.rest_client.error_module = None;
    config.bindings.as_mut().unwrap().python = Some(olai_codegen::PythonOptions {
        package: olai_codegen::PyPackageConfig {
            dir: tmp.path().join("pkg"),
            name: "example".into(),
        },
        error_base_class: "ExampleError".into(),
        module: "example._core".into(),
        async_methods: false,
        keyword_only: false,
        public_modules: false,
        user_agent: None,
        exports: vec![],
    });
    generate_code(&metadata(), &config).expect("generation succeeds");

    let errors = walk(&python)
        .into_iter()
        .find(|p| p.ends_with("error.rs"))
        .map(|p| std::fs::read_to_string(p).unwrap())
        .expect("python error.rs generated");
    syn::parse_file(&errors).expect("error.rs is valid Rust");
    assert!(
        errors.contains("pub trait ApiErrorAnswer")
            && !errors.contains("impl ApiErrorAnswer for ClientError")
            && !errors.contains("ClientError::Api"),
        "the ApiErrorAnswer impl is the client crate's without the error module:\n{errors}"
    );
}