server-less-macros 0.6.0

Proc macros for server-less
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
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
//! GraphQL handler generation using async-graphql dynamic schemas.
//!
//! Generates GraphQL schemas and resolvers from impl blocks using async-graphql.
//!
//! # Query vs Mutation
//!
//! Methods are classified based on naming conventions:
//! - Queries: `get_*`, `fetch_*`, `read_*`, `list_*`, `find_*`, `search_*`, `count_*`, `exists_*`, `is_*`, `has_*`
//! - Mutations: Everything else (create, update, delete, etc.)
//!
//! # Field Naming
//!
//! Method names are converted to camelCase for GraphQL fields:
//! - `get_user` → `getUser`
//! - `create_user` → `createUser`
//!
//! # Type Mapping
//!
//! Rust types are mapped to GraphQL types:
//! - `String` → String
//! - `i32`, `i64` → Int
//! - `f32`, `f64` → Float
//! - `bool` → Boolean
//! - `Vec<T>` → [T]
//! - `Option<T>` → T (nullable)
//!
//! # Custom Scalars
//!
//! async-graphql provides built-in support for common custom scalars:
//! - `chrono::DateTime<Utc>` → DateTime
//! - `uuid::Uuid` → UUID
//! - `url::Url` → Url
//! - `serde_json::Value` → JSON
//!
//! These work automatically - just use them in your method signatures:
//!
//! ```ignore
//! use chrono::{DateTime, Utc};
//! use uuid::Uuid;
//!
//! #[graphql]
//! impl UserService {
//!     async fn get_user(&self, user_id: Uuid) -> Option<User> { /* ... */ }
//!     async fn list_events(&self, since: DateTime<Utc>) -> Vec<Event> { /* ... */ }
//! }
//! ```
//!
//! # Generated Methods
//!
//! - `graphql_schema(self) -> async_graphql::dynamic::Schema` - Dynamic schema
//! - `graphql_router(self) -> axum::Router` - HTTP + Playground server
//! - `graphql_sdl(self) -> String` - Schema Definition Language
//!
//! # Example
//!
//! ```ignore
//! use server_less::graphql;
//!
//! #[derive(Clone)]
//! struct UserService;
//!
//! #[graphql(name = "UserAPI")]
//! impl UserService {
//!     /// Get user by ID (Query)
//!     async fn get_user(&self, id: i32) -> Option<String> {
//!         Some(format!("User {}", id))
//!     }
//!
//!     /// Create a new user (Mutation)
//!     async fn create_user(&self, name: String) -> String {
//!         format!("Created: {}", name)
//!     }
//! }
//!
//! // Use it:
//! let service = UserService;
//! let app = service.graphql_router();  // Serves GraphQL + Playground at /graphql
//! ```

use crate::app::extract_app_meta;
use crate::context::{partition_context_params, should_inject_context};
use heck::ToLowerCamelCase;

use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use server_less_parse::{MethodInfo, extract_methods, get_impl_name, partition_methods};
use syn::{ItemImpl, Token, parse::Parse};

use crate::server_attrs::{has_server_hidden, has_server_skip, validate_server_attrs};

/// Arguments for the #[graphql] attribute
#[derive(Default)]
pub(crate) struct GraphqlArgs {
    pub name: Option<String>,
    /// Enum types to register with the schema (from #[graphql_enum])
    pub enums: Vec<syn::Ident>,
    /// Input types to register with the schema (from #[graphql_input])
    pub inputs: Vec<syn::Ident>,
}

impl Parse for GraphqlArgs {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let mut args = GraphqlArgs::default();

        while !input.is_empty() {
            let ident: syn::Ident = input.parse()?;

            match ident.to_string().as_str() {
                "name" => {
                    input.parse::<Token![=]>()?;
                    let lit: syn::LitStr = input.parse()?;
                    args.name = Some(lit.value());
                }
                "enums" => {
                    // Parse enums(Type1, Type2, ...)
                    let content;
                    syn::parenthesized!(content in input);
                    let enum_types = content.parse_terminated(syn::Ident::parse, Token![,])?;
                    args.enums = enum_types.into_iter().collect();
                }
                "inputs" => {
                    // Parse inputs(Type1, Type2, ...)
                    let content;
                    syn::parenthesized!(content in input);
                    let input_types = content.parse_terminated(syn::Ident::parse, Token![,])?;
                    args.inputs = input_types.into_iter().collect();
                }
                other => {
                    const VALID: &[&str] = &["name", "enums", "inputs"];
                    let suggestion = crate::did_you_mean(other, VALID)
                        .map(|s| format!(" — did you mean `{s}`?"))
                        .unwrap_or_default();
                    return Err(syn::Error::new(
                        ident.span(),
                        format!(
                            "unknown argument `{other}`{suggestion}\n\
                             \n\
                             Valid arguments: name, enums, inputs\n\
                             \n\
                             Examples:\n\
                             - #[graphql(name = \"UserAPI\")]\n\
                             - #[graphql(enums(Status, Priority))]\n\
                             - #[graphql(inputs(CreateUserInput))]\n\
                             - #[graphql(name = \"MyAPI\", enums(Status), inputs(CreateUserInput))]"
                        ),
                    ));
                }
            }

            if input.peek(Token![,]) {
                input.parse::<Token![,]>()?;
            }
        }

        Ok(args)
    }
}

pub(crate) fn expand_graphql(args: GraphqlArgs, mut impl_block: ItemImpl) -> syn::Result<TokenStream2> {
    crate::reject_generic_impl(&impl_block)?;
    let app_meta = extract_app_meta(&mut impl_block.attrs);
    // args.name takes precedence over app_meta.name for GraphQL schema naming.
    // TODO: wire effective_name into the GraphQL schema name (used where struct name is currently hardcoded).
    let effective_name = args.name.or(app_meta.name);
    let _ = effective_name; // not yet wired in
    let struct_name = get_impl_name(&impl_block)?;
    let (impl_generics, _ty_generics, where_clause) = impl_block.generics.split_for_impl();
    let self_ty = &impl_block.self_ty;
    let methods = extract_methods(&impl_block)?;

    for m in &methods {
        validate_server_attrs(m)?;
    }
    // Partition into leaf methods (skip-filtered) and mount points (&T return types).
    let partitioned = partition_methods(&methods, has_server_skip);

    // Hidden methods are excluded from schema/SDL (not visible in type) but remain callable.
    let visible_leaf: Vec<_> = partitioned
        .leaf
        .iter()
        .copied()
        .filter(|m| !has_server_hidden(m))
        .collect();

    let leaf_methods = &visible_leaf;

    let (query_methods, mutation_methods): (Vec<_>, Vec<_>) = leaf_methods
        .iter()
        .copied()
        .partition(|m| is_query_method(&m.name_str()));

    let query_fields = generate_field_registrations(&query_methods);
    let mutation_fields = generate_field_registrations(&mutation_methods);

    let query_resolvers = generate_resolver_dispatch(&struct_name, &query_methods);
    let mutation_resolvers = generate_resolver_dispatch(&struct_name, &mutation_methods);

    let query_type_name = format!("{}Query", struct_name);
    let mutation_type_name = format!("{}Mutation", struct_name);

    // Generate mount composition calls — for each static mount `fn child(&self) -> &ChildService`,
    // inline the child's query and mutation fields into this service's schema objects.
    let mount_query_merges: Vec<_> = partitioned
        .static_mounts
        .iter()
        .map(|mount| {
            let method_ident = &mount.name;
            let inner_ty = mount.return_info.reference_inner.as_ref().unwrap();
            quote! {
                {
                    let child_arc = ::std::sync::Arc::new(service.#method_ident().clone());
                    obj = #inner_ty::__graphql_merge_query_fields(obj, child_arc);
                }
            }
        })
        .collect();

    // Each child's `__graphql_merge_mutation_fields` returns (Object, usize) where usize is the
    // number of fields it added. We accumulate the count to decide whether to register the
    // mutation type.
    let mount_mutation_merges: Vec<_> = partitioned
        .static_mounts
        .iter()
        .map(|mount| {
            let method_ident = &mount.name;
            let inner_ty = mount.return_info.reference_inner.as_ref().unwrap();
            quote! {
                {
                    let child_arc = ::std::sync::Arc::new(service.#method_ident().clone());
                    let (updated_obj, added) = #inner_ty::__graphql_merge_mutation_fields(obj, child_arc);
                    obj = updated_obj;
                    mutation_field_count += added;
                }
            }
        })
        .collect();

    // Whether this service has its own mutations (from leaf methods).
    let has_own_mutations = !mutation_methods.is_empty();
    // Whether this service has mount points (child services).
    let has_mounts = !partitioned.static_mounts.is_empty();

    // Collect custom scalars used across all non-skipped methods (mounts manage their own scalars).
    let custom_scalars = collect_custom_scalars(leaf_methods);
    let scalar_registrations: Vec<_> = custom_scalars
        .iter()
        .map(|name| {
            quote! {
                .register(Scalar::new(#name))
            }
        })
        .collect();

    // Generate enum type registrations from #[graphql(enums(...))]
    let enum_registrations: Vec<_> = args
        .enums
        .iter()
        .map(|enum_type| {
            quote! {
                .register(#enum_type::__graphql_enum_type())
            }
        })
        .collect();

    // Generate input type registrations from #[graphql(inputs(...))]
    let input_registrations: Vec<_> = args
        .inputs
        .iter()
        .map(|input_type| {
            quote! {
                .register(#input_type::__graphql_input_type())
            }
        })
        .collect();

    // Build the schema_build expression, based on what combination of own mutations and mounts
    // are present.
    //
    // - No mutations, no mounts: query-only schema.
    // - Own mutations only: always register mutation type (field count is known at compile time).
    // - Mounts only (no own mutations): build mutation object, let children add fields at runtime,
    //   register only if count > 0.
    // - Own mutations + mounts: build mutation object with own fields + child fields; always register.
    let schema_build = if has_own_mutations && has_mounts {
        // Own mutations + child mounts: merge both, always register mutation.
        quote! {
            let mut mutation_field_count: usize = 0;

            let mutation = {
                let service = service.clone();
                let mut obj = Object::new(#mutation_type_name);
                #(
                    {
                        let service = service.clone();
                        mutation_field_count += 1;
                        #mutation_fields
                    }
                )*
                // Merge child mutation fields from mount points.
                #(#mount_mutation_merges)*
                obj
            };

            // mutation_field_count > 0 because we have own mutations; always register.
            Schema::build(#query_type_name, Some(#mutation_type_name), None)
                .register(query)
                .register(mutation)
                #(#scalar_registrations)*
                #(#enum_registrations)*
                #(#input_registrations)*
                .finish()
                .expect("Failed to build GraphQL schema")
        }
    } else if has_own_mutations {
        // Own mutations only — no mounts. Always register mutation type.
        quote! {
            let mutation = {
                let service = service.clone();
                let mut obj = Object::new(#mutation_type_name);
                #(
                    {
                        let service = service.clone();
                        #mutation_fields
                    }
                )*
                obj
            };

            Schema::build(#query_type_name, Some(#mutation_type_name), None)
                .register(query)
                .register(mutation)
                #(#scalar_registrations)*
                #(#enum_registrations)*
                #(#input_registrations)*
                .finish()
                .expect("Failed to build GraphQL schema")
        }
    } else if has_mounts {
        // No own mutations, but child mounts may contribute mutation fields at runtime.
        quote! {
            let mut mutation_field_count: usize = 0;

            let mutation = {
                let mut obj = Object::new(#mutation_type_name);
                // Merge child mutation fields from mount points (each call updates mutation_field_count).
                #(#mount_mutation_merges)*
                obj
            };

            if mutation_field_count > 0 {
                Schema::build(#query_type_name, Some(#mutation_type_name), None)
                    .register(query)
                    .register(mutation)
                    #(#scalar_registrations)*
                    #(#enum_registrations)*
                    #(#input_registrations)*
                    .finish()
                    .expect("Failed to build GraphQL schema")
            } else {
                Schema::build(#query_type_name, None::<&str>, None)
                    .register(query)
                    #(#scalar_registrations)*
                    #(#enum_registrations)*
                    #(#input_registrations)*
                    .finish()
                    .expect("Failed to build GraphQL schema")
            }
        }
    } else {
        // No mutations and no mounts — query-only schema.
        quote! {
            Schema::build(#query_type_name, None::<&str>, None)
                .register(query)
                #(#scalar_registrations)*
                #(#enum_registrations)*
                #(#input_registrations)*
                .finish()
                .expect("Failed to build GraphQL schema")
        }
    };

    // Generate the field-merging helpers used by parent services that mount this service.
    // These allow a parent's `graphql_schema` to inline this service's fields into its own
    // query/mutation Objects without creating a nested schema.
    let merge_query_helper = generate_merge_query_helper(&struct_name, &query_methods);
    let merge_mutation_helper = generate_merge_mutation_helper(&struct_name, &mutation_methods);

    let maybe_impl = if crate::is_protocol_impl_emitter(&impl_block, "graphql") {
        quote! { #impl_block }
    } else {
        quote! {}
    };

    Ok(quote! {
        #maybe_impl

        impl #impl_generics #self_ty #where_clause {
            /// Convert a `serde_json::Value` into an `async_graphql::Value` recursively.
            ///
            /// Hoisted out of the per-field loop (Fix 1) so it is defined exactly once
            /// per generated `impl` block rather than once per method.
            #[doc(hidden)]
            #[allow(dead_code)]
            fn __graphql_json_to_value(json_val: ::serde_json::Value) -> ::async_graphql::Value {
                match json_val {
                    ::serde_json::Value::Null => ::async_graphql::Value::Null,
                    ::serde_json::Value::Bool(b) => ::async_graphql::Value::Boolean(b),
                    ::serde_json::Value::Number(n) => {
                        if let Some(i) = n.as_i64() {
                            ::async_graphql::Value::Number((i as i32).into())
                        } else if let Some(f) = n.as_f64() {
                            match ::serde_json::to_value(f) {
                                Ok(::serde_json::Value::Number(num)) => {
                                    ::async_graphql::Value::Number(num.into())
                                }
                                _ => ::async_graphql::Value::String(f.to_string()),
                            }
                        } else {
                            ::async_graphql::Value::Number(n.into())
                        }
                    }
                    ::serde_json::Value::String(s) => ::async_graphql::Value::String(s),
                    ::serde_json::Value::Array(arr) => {
                        let values: Vec<_> = arr
                            .into_iter()
                            .map(Self::__graphql_json_to_value)
                            .collect();
                        ::async_graphql::Value::List(values)
                    }
                    ::serde_json::Value::Object(obj) => {
                        let mut fields = ::async_graphql::indexmap::IndexMap::new();
                        for (key, value) in obj {
                            fields.insert(
                                ::async_graphql::Name::new(key),
                                Self::__graphql_json_to_value(value),
                            );
                        }
                        ::async_graphql::Value::Object(fields)
                    }
                }
            }

            /// Convert any `Serialize + Debug` value into an `async_graphql::Value`.
            ///
            /// Hoisted out of the per-field loop (Fix 1) so it is defined exactly once
            /// per generated `impl` block rather than once per method.
            #[doc(hidden)]
            #[allow(dead_code)]
            fn __graphql_to_value<T>(v: T) -> ::async_graphql::Value
            where
                T: ::serde::Serialize + ::std::fmt::Debug,
            {
                if let Ok(json_val) = ::serde_json::to_value(&v) {
                    Self::__graphql_json_to_value(json_val)
                } else {
                    ::async_graphql::Value::String(format!("{:?}", v))
                }
            }

            /// Build the GraphQL dynamic schema
            pub fn graphql_schema(self) -> ::async_graphql::dynamic::Schema
            where
                Self: Clone + Send + Sync + 'static,
            {
                use ::async_graphql::dynamic::*;

                let service = ::std::sync::Arc::new(self);

                let query = {
                    let service = service.clone();
                    let mut obj = Object::new(#query_type_name);
                    #(
                        {
                            let service = service.clone();
                            #query_fields
                        }
                    )*
                    // Merge child query fields from mount points.
                    #(#mount_query_merges)*
                    obj
                };

                #schema_build
            }

            #merge_query_helper
            #merge_mutation_helper

            /// Create an axum router with GraphQL endpoint
            pub fn graphql_router(self) -> ::server_less::axum::Router
            where
                Self: Clone + Send + Sync + 'static,
            {
                use ::server_less::axum::routing::{get, post};
                use ::server_less::axum::response::IntoResponse;

                let schema = self.graphql_schema();

                async fn graphql_handler(
                    schema: ::server_less::axum::extract::State<::async_graphql::dynamic::Schema>,
                    req: ::async_graphql_axum::GraphQLRequest,
                ) -> ::async_graphql_axum::GraphQLResponse {
                    schema.execute(req.into_inner()).await.into()
                }

                async fn playground() -> impl IntoResponse {
                    ::server_less::axum::response::Html(
                        ::async_graphql::http::playground_source(
                            ::async_graphql::http::GraphQLPlaygroundConfig::new("/graphql")
                        )
                    )
                }

                ::server_less::axum::Router::new()
                    .route("/graphql", get(playground).post(graphql_handler))
                    .with_state(schema)
            }

            /// Get the GraphQL SDL schema
            pub fn graphql_sdl(self) -> String
            where
                Self: Clone + Send + Sync + 'static,
            {
                self.graphql_schema().sdl()
            }

            /// Get OpenAPI paths for this GraphQL service (for composition with OpenApiBuilder)
            ///
            /// Returns endpoints for GraphQL query execution and playground.
            pub fn graphql_openapi_paths() -> ::std::vec::Vec<::server_less::OpenApiPath> {
                vec![
                    ::server_less::OpenApiPath {
                        path: "/graphql".to_string(),
                        method: "post".to_string(),
                        operation: ::server_less::OpenApiOperation {
                            summary: Some("GraphQL query endpoint".to_string()),
                            description: None,
                            operation_id: Some("graphql_query".to_string()),
                            tags: vec!["graphql".to_string()],
                            deprecated: false,
                            parameters: vec![],
                            request_body: Some(::server_less::serde_json::json!({
                                "required": true,
                                "content": {
                                    "application/json": {
                                        "schema": {
                                            "type": "object",
                                            "required": ["query"],
                                            "properties": {
                                                "query": {
                                                    "type": "string",
                                                    "description": "GraphQL query string"
                                                },
                                                "operationName": {
                                                    "type": "string",
                                                    "description": "Optional operation name"
                                                },
                                                "variables": {
                                                    "type": "object",
                                                    "description": "Optional query variables"
                                                }
                                            }
                                        }
                                    }
                                }
                            })),
                            responses: {
                                let mut r = ::server_less::serde_json::Map::new();
                                r.insert("200".to_string(), ::server_less::serde_json::json!({
                                    "description": "GraphQL response",
                                    "content": {
                                        "application/json": {
                                            "schema": {
                                                "type": "object",
                                                "properties": {
                                                    "data": {},
                                                    "errors": {
                                                        "type": "array",
                                                        "items": {
                                                            "type": "object",
                                                            "properties": {
                                                                "message": {"type": "string"},
                                                                "locations": {"type": "array"},
                                                                "path": {"type": "array"}
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }));
                                r
                            },
                            extra: ::server_less::serde_json::Map::new(),
                        },
                    },
                    ::server_less::OpenApiPath {
                        path: "/graphql".to_string(),
                        method: "get".to_string(),
                        operation: ::server_less::OpenApiOperation {
                            summary: Some("GraphQL Playground".to_string()),
                            description: None,
                            operation_id: Some("graphql_playground".to_string()),
                            tags: vec!["graphql".to_string()],
                            deprecated: false,
                            parameters: vec![],
                            request_body: None,
                            responses: {
                                let mut r = ::server_less::serde_json::Map::new();
                                r.insert("200".to_string(), ::server_less::serde_json::json!({
                                    "description": "GraphQL Playground HTML page",
                                    "content": {
                                        "text/html": {
                                            "schema": {"type": "string"}
                                        }
                                    }
                                }));
                                r
                            },
                            extra: ::server_less::serde_json::Map::new(),
                        },
                    }
                ]
            }

            fn __graphql_resolve_query(
                service: &::std::sync::Arc<Self>,
                method: &str,
                args: &::async_graphql::dynamic::ResolverContext,
            ) -> ::async_graphql::Result<::async_graphql::Value>
            where
                Self: Send + Sync,
            {
                match method {
                    #(#query_resolvers)*
                    _ => Err(::async_graphql::Error::new(format!("Unknown query: {}", method))),
                }
            }

            fn __graphql_resolve_mutation(
                service: &::std::sync::Arc<Self>,
                method: &str,
                args: &::async_graphql::dynamic::ResolverContext,
            ) -> ::async_graphql::Result<::async_graphql::Value>
            where
                Self: Send + Sync,
            {
                match method {
                    #(#mutation_resolvers)*
                    _ => Err(::async_graphql::Error::new(format!("Unknown mutation: {}", method))),
                }
            }
        }
    })
}

fn is_query_method(name: &str) -> bool {
    name.starts_with("get_")
        || name.starts_with("fetch_")
        || name.starts_with("read_")
        || name.starts_with("list_")
        || name.starts_with("find_")
        || name.starts_with("search_")
        || name.starts_with("count_")
        || name.starts_with("exists_")
        || name.starts_with("is_")
        || name.starts_with("has_")
}

fn generate_field_registrations(methods: &[&MethodInfo]) -> Vec<TokenStream2> {
    methods
        .iter()
        .map(|m| {
            let field_code = generate_field_registration(m);
            let cfg_attrs = &m.cfg_attrs;
            quote! {
                #(#cfg_attrs)*
                { #field_code }
            }
        })
        .collect()
}

fn generate_field_registration(method: &MethodInfo) -> TokenStream2 {
    let method_name = method.name_str();
    let method_ident = &method.name;
    let field_name = method_name.to_lower_camel_case();
    let description = method.docs.clone().unwrap_or_default();

    let ret = &method.return_info;
    let (type_ref, is_list) = infer_graphql_type_ref(ret);

    // Partition params: context params are injected; only user params go into the GraphQL schema.
    let (_ctx_param, user_params) =
        partition_context_params(&method.params).unwrap_or((None, method.params.iter().collect()));

    let arg_registrations: Vec<_> = user_params
        .iter()
        .map(|p| {
            let arg_name = p.name_str();
            let gql_type = rust_type_to_graphql(&p.ty);
            let is_required = !p.is_optional;
            if is_required {
                quote! {
                    .argument(InputValue::new(#arg_name, TypeRef::named_nn(#gql_type)))
                }
            } else {
                quote! {
                    .argument(InputValue::new(#arg_name, TypeRef::named(#gql_type)))
                }
            }
        })
        .collect();

    let arg_extractions: Vec<_> = user_params.iter().map(|p| {
        let arg_name = p.name_str();
        let param_name = &p.name;
        let ty = &p.ty;
        if p.is_optional {
            quote! {
                let #param_name: #ty = ctx.args.try_get(#arg_name).ok()
                    .and_then(|v| v.deserialize().ok());
            }
        } else {
            quote! {
                let #param_name: #ty = ctx.args.try_get(#arg_name)
                    .map_err(|_| ::async_graphql::Error::new(format!("Missing argument: {}", #arg_name)))?
                    .deserialize()
                    .map_err(|_| ::async_graphql::Error::new(format!("Invalid argument: {}", #arg_name)))?;
            }
        }
    }).collect();

    // Build arg list for method call: inject Context::new() where needed, pass others by name.
    let param_names: Vec<_> = method.params.iter().map(|p| {
        if should_inject_context(&p.ty, &method.params) {
            quote! { ::server_less::Context::new() }
        } else {
            let name = &p.name;
            quote! { #name }
        }
    }).collect();

    let method_call = if method.is_async {
        quote! { service.#method_ident(#(#param_names),*).await }
    } else {
        quote! { service.#method_ident(#(#param_names),*) }
    };

    let result_conversion = if ret.is_unit {
        quote! {
            #method_call;
            Ok(Some(::async_graphql::Value::Boolean(true)))
        }
    } else if ret.is_result {
        if is_list {
            quote! {
                match #method_call {
                    Ok(items) => {
                        let values: Vec<_> = items.into_iter()
                            .map(|item| Self::__graphql_to_value(item))
                            .collect();
                        Ok(Some(::async_graphql::Value::List(values)))
                    }
                    Err(e) => Err(::async_graphql::Error::new(format!("{}", e))),
                }
            }
        } else {
            quote! {
                match #method_call {
                    Ok(value) => Ok(Some(Self::__graphql_to_value(value))),
                    Err(e) => Err(::async_graphql::Error::new(format!("{}", e))),
                }
            }
        }
    } else if ret.is_option {
        quote! {
            match #method_call {
                Some(value) => Ok(Some(Self::__graphql_to_value(value))),
                None => Ok(None),
            }
        }
    } else if is_list {
        quote! {
            let items = #method_call;
            let values: Vec<_> = items.into_iter()
                .map(|item| Self::__graphql_to_value(item))
                .collect();
            Ok(Some(::async_graphql::Value::List(values)))
        }
    } else {
        quote! {
            let result = #method_call;
            Ok(Some(Self::__graphql_to_value(result)))
        }
    };

    // Note: the `json_to_graphql` / `value_to_graphql` helpers that were previously
    // emitted here (once per method) have been hoisted to `__graphql_json_to_value` /
    // `__graphql_to_value` on `Self`. Call sites now use `Self::__graphql_to_value`.
    quote! {
        let field = Field::new(#field_name, #type_ref, move |ctx| {
            let service = service.clone();
            FieldFuture::new(async move {
                #(#arg_extractions)*
                #result_conversion
            })
        })
        .description(#description)
        #(#arg_registrations)*;
        obj = obj.field(field);
    }
}

fn infer_graphql_type_ref(ret: &server_less_parse::ReturnInfo) -> (TokenStream2, bool) {
    if ret.is_unit {
        (quote! { TypeRef::named_nn(TypeRef::BOOLEAN) }, false)
    } else if let Some(ref ty) = ret.ty {
        let type_str = quote!(#ty).to_string();

        let is_list = type_str.contains("Vec");

        // Check for custom scalars first (async-graphql built-ins)
        let base_type = if type_str.contains("DateTime") {
            quote! { "DateTime" }
        } else if type_str.contains("Uuid") {
            quote! { "UUID" }
        } else if type_str.contains("Url") {
            quote! { "Url" }
        } else if type_str.contains("serde_json :: Value") || type_str == "Value" {
            quote! { "JSON" }
        } else if type_str.contains("String") || type_str.contains("str") {
            quote! { TypeRef::STRING }
        } else if type_str.contains("i32")
            || type_str.contains("i64")
            || type_str.contains("u32")
            || type_str.contains("u64")
            || type_str.contains("usize")
        {
            quote! { TypeRef::INT }
        } else if type_str.contains("f32") || type_str.contains("f64") {
            quote! { TypeRef::FLOAT }
        } else if type_str.contains("bool") {
            quote! { TypeRef::BOOLEAN }
        } else {
            // Unrecognised return type: fall back to the JSON scalar rather than
            // silently using String (which produces a wrong schema). Custom structs
            // that implement `Serialize` will serialize correctly through
            // `__graphql_to_value`; the schema will describe the field as JSON.
            //
            // The "JSON" scalar is always registered by `collect_custom_scalars`.
            //
            // For a properly-typed schema, annotate the method with
            // `#[route(response_type = "MyGraphQLType")]` and register the type via
            // `#[graphql(inputs(MyGraphQLType))]`.
            quote! { "JSON" }
        };

        if ret.is_option {
            if is_list {
                (
                    quote! { TypeRef::named(TypeRef::named_list(#base_type)) },
                    true,
                )
            } else {
                (quote! { TypeRef::named(#base_type) }, false)
            }
        } else if ret.is_result {
            if is_list {
                (quote! { TypeRef::named_nn_list(#base_type) }, true)
            } else {
                (quote! { TypeRef::named_nn(#base_type) }, false)
            }
        } else if is_list {
            (quote! { TypeRef::named_nn_list(#base_type) }, true)
        } else {
            (quote! { TypeRef::named_nn(#base_type) }, false)
        }
    } else {
        (quote! { TypeRef::named_nn(TypeRef::BOOLEAN) }, false)
    }
}

fn generate_resolver_dispatch(
    struct_name: &syn::Ident,
    methods: &[&MethodInfo],
) -> Vec<TokenStream2> {
    methods
        .iter()
        .map(|m| generate_resolver_arm(struct_name, m))
        .collect()
}

fn generate_resolver_arm(_struct_name: &syn::Ident, method: &MethodInfo) -> TokenStream2 {
    let method_name_str = method.name_str();

    quote! {
        #method_name_str => {
            // Dispatch is handled by FieldFuture closures registered in graphql_schema().
            // This arm is dead code; reaching it indicates a code-generation bug.
            unreachable!("BUG: resolver arm should not be called — dispatch is handled by FieldFuture")
        }
    }
}

fn rust_type_to_graphql(ty: &syn::Type) -> &'static str {
    let type_str = quote!(#ty).to_string();

    // Try to extract inner type for Vec<T>
    if type_str.contains("Vec") {
        return extract_vec_inner_type(&type_str);
    }

    // Check for custom scalars (async-graphql built-ins)
    if type_str.contains("DateTime") {
        return "DateTime";
    }
    if type_str.contains("Uuid") {
        return "UUID";
    }
    if type_str.contains("Url") {
        return "Url";
    }
    if type_str.contains("serde_json :: Value") || type_str == "Value" {
        return "JSON";
    }

    let json_type = server_less_rpc::infer_json_type(ty);
    match json_type {
        "integer" => "Int",
        "number" => "Float",
        "boolean" => "Boolean",
        "string" => "String",
        _ => "String", // Custom types default to String for now
    }
}

fn extract_vec_inner_type(type_str: &str) -> &'static str {
    // Try to extract T from Vec<T>
    if let Some(start) = type_str.find("Vec<") {
        let inner = &type_str[start + 4..];
        if let Some(end) = inner.find('>') {
            let inner_type = inner[..end].trim();
            return map_inner_type_to_graphql(inner_type);
        }
    }
    "String"
}

fn map_inner_type_to_graphql(inner: &str) -> &'static str {
    // Check for custom scalars first
    if inner.contains("DateTime") {
        return "DateTime";
    }
    if inner.contains("Uuid") {
        return "UUID";
    }
    if inner.contains("Url") {
        return "Url";
    }
    if inner.contains("serde_json :: Value") || inner == "Value" {
        return "JSON";
    }

    // Standard types
    if inner.contains("String") || inner.contains("str") {
        "String"
    } else if inner.contains("i32")
        || inner.contains("i64")
        || inner.contains("u32")
        || inner.contains("u64")
        || inner.contains("isize")
        || inner.contains("usize")
    {
        "Int"
    } else if inner.contains("f32") || inner.contains("f64") {
        "Float"
    } else if inner.contains("bool") {
        "Boolean"
    } else {
        // Unrecognised inner type: fall back to JSON scalar (always registered).
        "JSON"
    }
}

/// Collect custom scalar types used across all methods (parameters + return types).
///
/// Returns a deduplicated list of scalar names that need to be registered
/// with the dynamic schema builder.
///
/// "JSON" is always included because unrecognised return types fall back to it
/// (see `infer_graphql_type_ref` and `map_inner_type_to_graphql`).
fn collect_custom_scalars(methods: &[&MethodInfo]) -> Vec<String> {
    let mut scalars = std::collections::BTreeSet::new();

    // Always register the JSON scalar — unrecognised struct/enum return types fall
    // back to "JSON" rather than silently mapping to String.
    scalars.insert("JSON".to_string());

    for method in methods {
        for param in &method.params {
            let ty = &param.ty;
            check_type_for_scalars(&quote!(#ty).to_string(), &mut scalars);
        }
        if let Some(ref ty) = method.return_info.ty {
            check_type_for_scalars(&quote!(#ty).to_string(), &mut scalars);
        }
    }

    scalars.into_iter().collect()
}

/// Generate the `__graphql_merge_query_fields` helper method for a service.
///
/// This is called by parent services that mount this service as a child. It inlines
/// this service's query fields into the parent's Object builder, enabling schema composition.
fn generate_merge_query_helper(
    _struct_name: &syn::Ident,
    query_methods: &[&MethodInfo],
) -> TokenStream2 {
    let field_registrations = generate_field_registrations(query_methods);

    quote! {
        /// Merge this service's query fields into an existing Object builder.
        ///
        /// Called by parent services that include this service as a mount point.
        /// This inlines all query fields from this service into the parent's schema
        /// without creating a nested GraphQL type.
        #[doc(hidden)]
        pub fn __graphql_merge_query_fields(
            mut obj: ::async_graphql::dynamic::Object,
            service: ::std::sync::Arc<Self>,
        ) -> ::async_graphql::dynamic::Object
        where
            Self: Clone + Send + Sync + 'static,
        {
            use ::async_graphql::dynamic::*;

            #(
                {
                    let service = service.clone();
                    #field_registrations
                }
            )*

            obj
        }
    }
}

/// Generate the `__graphql_merge_mutation_fields` helper method for a service.
///
/// This is called by parent services that mount this service as a child. It inlines
/// this service's mutation fields into the parent's Object builder and returns how many
/// fields were added (so the parent can decide whether to register the mutation type).
fn generate_merge_mutation_helper(
    _struct_name: &syn::Ident,
    mutation_methods: &[&MethodInfo],
) -> TokenStream2 {
    let field_count = mutation_methods.len();
    let field_registrations = generate_field_registrations(mutation_methods);

    quote! {
        /// Merge this service's mutation fields into an existing Object builder.
        ///
        /// Returns the updated Object and the number of fields added. The parent uses
        /// the count to decide whether to register the mutation type with the schema.
        ///
        /// Called by parent services that include this service as a mount point.
        #[doc(hidden)]
        pub fn __graphql_merge_mutation_fields(
            mut obj: ::async_graphql::dynamic::Object,
            service: ::std::sync::Arc<Self>,
        ) -> (::async_graphql::dynamic::Object, usize)
        where
            Self: Clone + Send + Sync + 'static,
        {
            use ::async_graphql::dynamic::*;

            #(
                {
                    let service = service.clone();
                    #field_registrations
                }
            )*

            (obj, #field_count)
        }
    }
}

/// Check a type string for custom scalar types and add them to the set.
fn check_type_for_scalars(type_str: &str, scalars: &mut std::collections::BTreeSet<String>) {
    if type_str.contains("DateTime") {
        scalars.insert("DateTime".to_string());
    }
    if type_str.contains("Uuid") {
        scalars.insert("UUID".to_string());
    }
    if type_str.contains("Url") && !type_str.contains("UrlError") {
        scalars.insert("Url".to_string());
    }
    if type_str.contains("serde_json :: Value") || type_str == "Value" {
        scalars.insert("JSON".to_string());
    }
}