Skip to main content

santity_pdk_macro/
lib.rs

1use proc_macro::TokenStream;
2use quote::{format_ident, quote};
3use syn::spanned::Spanned;
4use syn::{
5    parse_macro_input, parse::Parse, punctuated::Punctuated, token::Comma, Attribute, Ident,
6    ImplItem, ItemImpl, LitStr, Token,
7};
8
9#[derive(Clone)]
10struct OptionDef {
11    name: String,
12    description: String,
13    option_type: proc_macro2::TokenStream,
14    required: bool,
15    autocomplete: bool,
16}
17
18#[derive(Clone)]
19struct SubcommandDef {
20    fn_ident: Ident,
21    command: String,
22    subcommand: String,
23    group: Option<String>,
24    description: String,
25    takes_arg: bool,
26    options: Vec<OptionDef>,
27    opens_modal: bool,
28}
29
30struct CommandDef {
31    fn_ident: Ident,
32    cmd_name: String,
33    cmd_description: String,
34    takes_arg: bool,
35    options: Vec<OptionDef>,
36    opens_modal: bool,
37}
38
39struct ComponentDef {
40    fn_ident: Ident,
41    custom_id: String,
42    takes_arg: bool,
43}
44
45struct AutocompleteDef {
46    fn_ident: Ident,
47    command: String,
48    subcommand: Option<String>,
49    option: String,
50    takes_arg: bool,
51}
52
53struct TimerDef {
54    fn_ident: Ident,
55    tag: Option<String>,
56    takes_arg: bool,
57}
58
59struct EventDef {
60    fn_ident: Ident,
61    kind: Ident,
62    takes_arg: bool,
63}
64
65type CommandEntry<'a> = (String, Vec<OptionDef>, Vec<&'a SubcommandDef>, bool);
66
67/// Declarative arguments accepted by the `#[plugin(..)]` attribute.
68struct PluginArgs {
69    name: Option<String>,
70    version: Option<String>,
71    author: Option<String>,
72    description: Option<String>,
73    /// snake_case gateway event kinds declared by the plugin
74    events: Vec<Ident>,
75    /// capability domain strings requested from the host
76    capabilities: Vec<String>,
77}
78
79impl Parse for PluginArgs {
80    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
81        let mut args = PluginArgs {
82            name: None,
83            version: None,
84            author: None,
85            description: None,
86            events: Vec::new(),
87            capabilities: Vec::new(),
88        };
89
90        while !input.is_empty() {
91            let key: Ident = input.parse()?;
92            if key == "events" {
93                let content;
94                syn::parenthesized!(content in input);
95                let kinds = Punctuated::<Ident, Comma>::parse_terminated(&content)?;
96                args.events.extend(kinds);
97            } else if key == "capabilities" {
98                let content;
99                syn::parenthesized!(content in input);
100                let caps = Punctuated::<LitStr, Comma>::parse_terminated(&content)?;
101                args.capabilities.extend(caps.iter().map(|l| l.value()));
102            } else if matches!(
103                key.to_string().as_str(),
104                "name" | "version" | "author" | "description"
105            ) {
106                input.parse::<Token![=]>()?;
107                let value: LitStr = input.parse()?;
108                match key.to_string().as_str() {
109                    "name" => args.name = Some(value.value()),
110                    "version" => args.version = Some(value.value()),
111                    "author" => args.author = Some(value.value()),
112                    "description" => args.description = Some(value.value()),
113                    _ => unreachable!(),
114                }
115            } else {
116                return Err(syn::Error::new(
117                    key.span(),
118                    "unsupported plugin attribute key (expected name, version, author, description, events, capabilities)",
119                ));
120            }
121
122            if !input.is_empty() {
123                input.parse::<Comma>()?;
124            }
125        }
126        Ok(args)
127    }
128}
129
130/// snake_case event identifier -> WIT EventKind variant expression
131fn event_kind_expr(ident: &Ident) -> syn::Result<proc_macro2::TokenStream> {
132    let pascal: String = ident
133        .to_string()
134        .split('_')
135        .map(|seg| {
136            let mut chars = seg.chars();
137            match chars.next() {
138                Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
139                None => String::new(),
140            }
141        })
142        .collect();
143
144    const KNOWN: &[&str] = &[
145        "MemberJoin",
146        "MemberLeave",
147        "MemberUpdate",
148        "ReactionAdd",
149        "ReactionRemove",
150        "MessageUpdate",
151        "MessageDelete",
152        "VoiceStateUpdate",
153        "PresenceUpdate",
154        "GuildUpdate",
155    ];
156
157    if !KNOWN.contains(&pascal.as_str()) {
158        return Err(syn::Error::new(
159            ident.span(),
160            format!(
161                "unknown event kind `{}` (known: {})",
162                ident,
163                KNOWN.join(", ")
164            ),
165        ));
166    }
167
168    let variant = format_ident!("{}", pascal);
169    Ok(quote! { ::santity_pdk::EventKind::#variant })
170}
171
172fn parse_options(meta: &syn::meta::ParseNestedMeta) -> syn::Result<Vec<OptionDef>> {
173    let mut options = Vec::new();
174    meta.parse_nested_meta(|opt_meta| {
175        let opt_name = opt_meta
176            .path
177            .get_ident()
178            .map(|id| id.to_string())
179            .unwrap_or_else(|| {
180                opt_meta.path.segments.last().unwrap().ident.to_string()
181            });
182        let type_str = opt_meta.value()?.parse::<LitStr>()?.value();
183        let opt_type_token = match type_str.to_lowercase().as_str() {
184            "string" | "str" | "text" => quote! { ::santity_pdk::SlashOptionType::StringType },
185            "integer" | "int" | "i64" | "number" => quote! { ::santity_pdk::SlashOptionType::IntegerType },
186            "boolean" | "bool" => quote! { ::santity_pdk::SlashOptionType::BooleanType },
187            "user" => quote! { ::santity_pdk::SlashOptionType::UserType },
188            "channel" => quote! { ::santity_pdk::SlashOptionType::ChannelType },
189            "role" => quote! { ::santity_pdk::SlashOptionType::RoleType },
190            _ => {
191                return Err(syn::Error::new(
192                    opt_meta.path.span(),
193                    format!(
194                        "unsupported option type `{}` (expected String, Integer, Boolean, User, Channel, or Role)",
195                        type_str
196                    ),
197                ));
198            }
199        };
200
201        options.push(OptionDef {
202            name: opt_name.clone(),
203            description: format!("{} parameter", opt_name),
204            option_type: opt_type_token,
205            required: true,
206            autocomplete: false,
207        });
208        Ok(())
209    })?;
210    Ok(options)
211}
212
213/// Attribute macro for Wasm plugins.
214#[proc_macro_attribute]
215pub fn plugin(attr: TokenStream, item: TokenStream) -> TokenStream {
216    let args = parse_macro_input!(attr as PluginArgs);
217
218    let mut input = parse_macro_input!(item as ItemImpl);
219    let self_ty = &input.self_ty;
220
221    let name_str = args.name.unwrap_or_else(|| {
222        quote!(#self_ty)
223            .to_string()
224            .to_lowercase()
225            .replace("plugin", "")
226    });
227    let version_str = args.version.unwrap_or_else(|| "0.1.0".to_string());
228    let author_str = args.author.unwrap_or_else(|| "SEGv".to_string());
229    let description_str = args
230        .description
231        .unwrap_or_else(|| "Santity Wasm Plugin".to_string());
232
233    let mut commands: Vec<CommandDef> = Vec::new();
234    let mut subcommands: Vec<SubcommandDef> = Vec::new();
235    let mut components: Vec<ComponentDef> = Vec::new();
236    let mut autocompletes: Vec<AutocompleteDef> = Vec::new();
237    let mut timers: Vec<TimerDef> = Vec::new();
238    let mut lifecycle_events: Vec<EventDef> = Vec::new();
239    let mut message_fn: Option<(Ident, bool)> = None;
240
241    for item in &mut input.items {
242        if let ImplItem::Fn(ref mut method) = item {
243            let fn_ident = method.sig.ident.clone();
244            let takes_arg = !method.sig.inputs.is_empty();
245
246            let mut is_cmd = false;
247            let mut cmd_name_opt: Option<String> = None;
248            let mut cmd_desc_opt: Option<String> = None;
249            let mut cmd_options: Vec<OptionDef> = Vec::new();
250            let mut cmd_opens_modal = false;
251
252            let mut is_subcmd = false;
253            let mut sub_cmd_parent = String::new();
254            let mut sub_name_opt: Option<String> = None;
255            let mut sub_group_opt: Option<String> = None;
256            let mut sub_desc_opt: Option<String> = None;
257            let mut sub_options: Vec<OptionDef> = Vec::new();
258            let mut sub_opens_modal = false;
259
260            let mut is_msg = false;
261            let mut retained_attrs: Vec<Attribute> = Vec::new();
262
263            for attr in &method.attrs {
264                if attr.path().is_ident("command") {
265                    is_cmd = true;
266                    let parse_res = attr.parse_nested_meta(|meta| {
267                        if meta.path.is_ident("name") {
268                            cmd_name_opt = Some(meta.value()?.parse::<LitStr>()?.value());
269                        } else if meta.path.is_ident("description") {
270                            cmd_desc_opt = Some(meta.value()?.parse::<LitStr>()?.value());
271                        } else if meta.path.is_ident("opens_modal") {
272                            if let Ok(val) = meta.value() {
273                                cmd_opens_modal = val.parse::<syn::LitBool>()?.value;
274                            } else {
275                                cmd_opens_modal = true;
276                            }
277                        } else if meta.path.is_ident("options") {
278                            cmd_options = parse_options(&meta)?;
279                        }
280                        Ok(())
281                    });
282                    if let Err(err) = parse_res {
283                        return TokenStream::from(err.to_compile_error());
284                    }
285                } else if attr.path().is_ident("subcommand") {
286                    is_subcmd = true;
287                    let parse_res = attr.parse_nested_meta(|meta| {
288                        if meta.path.is_ident("command") {
289                            sub_cmd_parent = meta.value()?.parse::<LitStr>()?.value();
290                        } else if meta.path.is_ident("name") {
291                            sub_name_opt = Some(meta.value()?.parse::<LitStr>()?.value());
292                        } else if meta.path.is_ident("group") {
293                            sub_group_opt = Some(meta.value()?.parse::<LitStr>()?.value());
294                        } else if meta.path.is_ident("description") {
295                            sub_desc_opt = Some(meta.value()?.parse::<LitStr>()?.value());
296                        } else if meta.path.is_ident("opens_modal") {
297                            if let Ok(val) = meta.value() {
298                                sub_opens_modal = val.parse::<syn::LitBool>()?.value;
299                            } else {
300                                sub_opens_modal = true;
301                            }
302                        } else if meta.path.is_ident("options") {
303                            sub_options = parse_options(&meta)?;
304                        }
305                        Ok(())
306                    });
307                    if let Err(err) = parse_res {
308                        return TokenStream::from(err.to_compile_error());
309                    }
310                } else if attr.path().is_ident("button") || attr.path().is_ident("select_menu") || attr.path().is_ident("modal_submit") {
311                    let mut custom_id_opt: Option<String> = None;
312                    if let Ok(lit) = attr.parse_args::<LitStr>() {
313                        custom_id_opt = Some(lit.value());
314                    } else {
315                        let _ = attr.parse_nested_meta(|meta| {
316                            if meta.path.is_ident("id") || meta.path.is_ident("custom_id") {
317                                custom_id_opt = Some(meta.value()?.parse::<LitStr>()?.value());
318                            }
319                            Ok(())
320                        });
321                    }
322                    let cid = custom_id_opt.unwrap_or_else(|| fn_ident.to_string());
323                    components.push(ComponentDef {
324                        fn_ident: fn_ident.clone(),
325                        custom_id: cid,
326                        takes_arg,
327                    });
328                } else if attr.path().is_ident("autocomplete") {
329                    let mut cmd_parent = String::new();
330                    let mut sub_parent: Option<String> = None;
331                    let mut opt_name = String::new();
332                    let parse_res = attr.parse_nested_meta(|meta| {
333                        if meta.path.is_ident("command") {
334                            cmd_parent = meta.value()?.parse::<LitStr>()?.value();
335                        } else if meta.path.is_ident("subcommand") {
336                            sub_parent = Some(meta.value()?.parse::<LitStr>()?.value());
337                        } else if meta.path.is_ident("option") {
338                            opt_name = meta.value()?.parse::<LitStr>()?.value();
339                        }
340                        Ok(())
341                    });
342                    if let Err(err) = parse_res {
343                        return TokenStream::from(err.to_compile_error());
344                    }
345                    autocompletes.push(AutocompleteDef {
346                        fn_ident: fn_ident.clone(),
347                        command: cmd_parent,
348                        subcommand: sub_parent,
349                        option: opt_name,
350                        takes_arg,
351                    });
352                } else if attr.path().is_ident("timer") {
353                    let mut tag_opt: Option<String> = None;
354                    if let Ok(lit) = attr.parse_args::<LitStr>() {
355                        tag_opt = Some(lit.value());
356                    } else {
357                        let _ = attr.parse_nested_meta(|meta| {
358                            if meta.path.is_ident("tag") {
359                                tag_opt = Some(meta.value()?.parse::<LitStr>()?.value());
360                            }
361                            Ok(())
362                        });
363                    }
364                    timers.push(TimerDef {
365                        fn_ident: fn_ident.clone(),
366                        tag: tag_opt,
367                        takes_arg,
368                    });
369                } else if attr.path().is_ident("event") {
370                    let mut event_kind_ident: Option<Ident> = None;
371                    if let Ok(ident) = attr.parse_args::<Ident>() {
372                        event_kind_ident = Some(ident);
373                    }
374                    if let Some(kind) = event_kind_ident {
375                        lifecycle_events.push(EventDef {
376                            fn_ident: fn_ident.clone(),
377                            kind,
378                            takes_arg,
379                        });
380                    }
381                } else if attr.path().is_ident("message") {
382                    is_msg = true;
383                } else {
384                    retained_attrs.push(attr.clone());
385                }
386            }
387
388            method.attrs = retained_attrs;
389
390            if is_cmd {
391                let cmd_name = cmd_name_opt.unwrap_or_else(|| fn_ident.to_string());
392                let cmd_description =
393                    cmd_desc_opt.unwrap_or_else(|| format!("{} command", cmd_name));
394                commands.push(CommandDef {
395                    fn_ident: fn_ident.clone(),
396                    cmd_name,
397                    cmd_description,
398                    takes_arg,
399                    options: cmd_options,
400                    opens_modal: cmd_opens_modal,
401                });
402            }
403
404            if is_subcmd {
405                let sub_name = sub_name_opt.unwrap_or_else(|| fn_ident.to_string());
406                let sub_desc = sub_desc_opt.unwrap_or_else(|| format!("{} subcommand", sub_name));
407                subcommands.push(SubcommandDef {
408                    fn_ident: fn_ident.clone(),
409                    command: sub_cmd_parent,
410                    subcommand: sub_name,
411                    group: sub_group_opt,
412                    description: sub_desc,
413                    takes_arg,
414                    options: sub_options,
415                    opens_modal: sub_opens_modal,
416                });
417            }
418
419            if is_msg {
420                message_fn = Some((fn_ident, takes_arg));
421            }
422        }
423    }
424
425    // Build slash command definitions with subcommands merged
426    let mut command_map: std::collections::BTreeMap<String, CommandEntry<'_>> =
427        std::collections::BTreeMap::new();
428
429    for cmd in &commands {
430        command_map.insert(
431            cmd.cmd_name.clone(),
432            (cmd.cmd_description.clone(), cmd.options.clone(), Vec::new(), cmd.opens_modal),
433        );
434    }
435
436    for sub in &subcommands {
437        let entry = command_map
438            .entry(sub.command.clone())
439            .or_insert_with(|| (format!("{} command", sub.command), Vec::new(), Vec::new(), false));
440        entry.2.push(sub);
441        if sub.opens_modal {
442            entry.3 = true;
443        }
444    }
445
446    let cmd_defs = command_map.into_iter().map(|(cmd_name, (cmd_desc, opts, subs, opens_modal))| {
447        let opt_defs = opts.iter().map(|opt| {
448            let opt_name = &opt.name;
449            let opt_desc = &opt.description;
450            let opt_type = &opt.option_type;
451            let opt_req = opt.required;
452            let opt_auto = opt.autocomplete;
453            quote! {
454                ::santity_pdk::SlashOptionDef {
455                    name: #opt_name.to_string(),
456                    description: #opt_desc.to_string(),
457                    option_type: #opt_type,
458                    required: #opt_req,
459                    autocomplete: #opt_auto,
460                }
461            }
462        });
463
464        let sub_defs = subs.iter().map(|sub| {
465            let sub_name = &sub.subcommand;
466            let sub_desc = &sub.description;
467            let sub_group = match &sub.group {
468                Some(g) => quote! { Some(#g.to_string()) },
469                None => quote! { None },
470            };
471            let sub_opt_defs = sub.options.iter().map(|opt| {
472                let opt_name = &opt.name;
473                let opt_desc = &opt.description;
474                let opt_type = &opt.option_type;
475                let opt_req = opt.required;
476                let opt_auto = opt.autocomplete;
477                quote! {
478                    ::santity_pdk::SlashOptionDef {
479                        name: #opt_name.to_string(),
480                        description: #opt_desc.to_string(),
481                        option_type: #opt_type,
482                        required: #opt_req,
483                        autocomplete: #opt_auto,
484                    }
485                }
486            });
487
488            let sub_opens_modal = sub.opens_modal;
489            quote! {
490                ::santity_pdk::SlashSubcommandDef {
491                    name: #sub_name.to_string(),
492                    description: #sub_desc.to_string(),
493                    group: #sub_group,
494                    options: vec![#(#sub_opt_defs),*],
495                    opens_modal: #sub_opens_modal,
496                }
497            }
498        });
499
500        let cmd_opens_modal = opens_modal;
501        quote! {
502            ::santity_pdk::SlashCommandDef {
503                name: #cmd_name.to_string(),
504                description: #cmd_desc.to_string(),
505                options: vec![#(#opt_defs),*],
506                subcommands: vec![#(#sub_defs),*],
507                opens_modal: #cmd_opens_modal,
508            }
509        }
510    });
511
512    // Zero-cost compile-time match jump table for on_interaction
513    let command_arms = commands.iter().map(|c| {
514        let name = &c.cmd_name;
515        let ident = &c.fn_ident;
516        if c.takes_arg {
517            quote! { #name => Self::#ident(event), }
518        } else {
519            quote! { #name => Self::#ident(), }
520        }
521    });
522
523    let subcommand_arms = subcommands.iter().map(|s| {
524        let cmd = &s.command;
525        let sub = &s.subcommand;
526        let ident = &s.fn_ident;
527        if s.takes_arg {
528            quote! { (#cmd, #sub) => return Self::#ident(event), }
529        } else {
530            quote! { (#cmd, #sub) => return Self::#ident(), }
531        }
532    });
533
534    let (prefix_components, exact_components): (Vec<&ComponentDef>, Vec<&ComponentDef>) = components
535        .iter()
536        .partition(|c| c.custom_id.ends_with('_') || c.custom_id.ends_with('*'));
537
538    let exact_component_arms = exact_components.iter().map(|c| {
539        let cid = &c.custom_id;
540        let namespaced = format!("{}:{}", name_str, cid);
541        let ident = &c.fn_ident;
542        if c.takes_arg {
543            quote! { #cid | #namespaced => return Self::#ident(event), }
544        } else {
545            quote! { #cid | #namespaced => return Self::#ident(), }
546        }
547    });
548
549    let prefix_component_arms = prefix_components.iter().map(|c| {
550        let cid = &c.custom_id;
551        let namespaced = format!("{}:{}", name_str, cid);
552        let ident = &c.fn_ident;
553        let clean_cid = cid.trim_end_matches('*');
554        let clean_namespaced = namespaced.trim_end_matches('*');
555        if c.takes_arg {
556            quote! { s if s.starts_with(#clean_cid) || s.starts_with(#clean_namespaced) => return Self::#ident(event), }
557        } else {
558            quote! { s if s.starts_with(#clean_cid) || s.starts_with(#clean_namespaced) => return Self::#ident(), }
559        }
560    });
561
562    let (sub_autocompletes, generic_autocompletes): (Vec<&AutocompleteDef>, Vec<&AutocompleteDef>) = autocompletes
563        .iter()
564        .partition(|a| a.subcommand.is_some());
565
566    let sub_autocomplete_arms = sub_autocompletes.iter().map(|a| {
567        let cmd = &a.command;
568        let sub = a.subcommand.as_ref().unwrap();
569        let opt = &a.option;
570        let ident = &a.fn_ident;
571        if a.takes_arg {
572            quote! { (#cmd, Some(#sub), #opt) => return Self::#ident(event), }
573        } else {
574            quote! { (#cmd, Some(#sub), #opt) => return Self::#ident(), }
575        }
576    });
577
578    let generic_autocomplete_arms = generic_autocompletes.iter().map(|a| {
579        let cmd = &a.command;
580        let opt = &a.option;
581        let ident = &a.fn_ident;
582        if a.takes_arg {
583            quote! { (#cmd, _, #opt) => return Self::#ident(event), }
584        } else {
585            quote! { (#cmd, _, #opt) => return Self::#ident(), }
586        }
587    });
588
589    let timer_arms = timers.iter().filter_map(|t| {
590        t.tag.as_ref().map(|tag| {
591            let ident = &t.fn_ident;
592            if t.takes_arg {
593                quote! { #tag => Self::#ident(callback_tag), }
594            } else {
595                quote! { #tag => Self::#ident(), }
596            }
597        })
598    });
599
600    let fallback_timer = timers.iter().find(|t| t.tag.is_none());
601    let default_timer_body = if let Some(t) = fallback_timer {
602        let ident = &t.fn_ident;
603        if t.takes_arg {
604            quote! { Self::#ident(callback_tag); }
605        } else {
606            quote! { Self::#ident(); }
607        }
608    } else {
609        quote! {}
610    };
611
612    let on_message_body = if let Some((msg_ident, takes_arg)) = message_fn {
613        if takes_arg {
614            quote! {
615                let _ = ::santity_pdk::init();
616                Self::#msg_ident(event)
617            }
618        } else {
619            quote! {
620                let _ = ::santity_pdk::init();
621                Self::#msg_ident()
622            }
623        }
624    } else {
625        quote! {
626            let _ = ::santity_pdk::init();
627            ::santity_pdk::ResponseAction::none()
628        }
629    };
630
631    let mut all_events = args.events.clone();
632    for le in &lifecycle_events {
633        if !all_events.iter().any(|id| id == &le.kind) {
634            all_events.push(le.kind.clone());
635        }
636    }
637
638    let event_kind_exprs = match all_events
639        .iter()
640        .map(event_kind_expr)
641        .collect::<Result<Vec<_>, _>>()
642    {
643        Ok(exprs) => exprs,
644        Err(err) => return TokenStream::from(err.to_compile_error()),
645    };
646
647    let event_arms = lifecycle_events.iter().map(|e| {
648        let expr = event_kind_expr(&e.kind).unwrap();
649        let ident = &e.fn_ident;
650        if e.takes_arg {
651            quote! { #expr => return Self::#ident(payload_json), }
652        } else {
653            quote! { #expr => return Self::#ident(), }
654        }
655    });
656
657    let cap_strs = &args.capabilities;
658
659    let expanded = quote! {
660        #input
661
662        impl ::santity_pdk::Guest for #self_ty {
663            fn get_info() -> ::santity_pdk::PluginMetadata {
664                ::santity_pdk::PluginMetadata {
665                    name: #name_str.to_string(),
666                    version: #version_str.to_string(),
667                    author: #author_str.to_string(),
668                    description: #description_str.to_string(),
669                    required_events: vec![#(#event_kind_exprs),*],
670                    capabilities: vec![#(#cap_strs.to_string()),*],
671                }
672            }
673
674            fn get_slash_commands() -> Vec<::santity_pdk::SlashCommandDef> {
675                vec![
676                    #(#cmd_defs),*
677                ]
678            }
679
680            fn on_interaction(event: ::santity_pdk::InteractionEvent) -> ::santity_pdk::ResponseAction {
681                let _ = ::santity_pdk::init();
682
683                if let Some(ref cid) = event.custom_id {
684                    match cid.as_str() {
685                        #(#exact_component_arms)*
686                        #(#prefix_component_arms)*
687                        _ => {}
688                    }
689                }
690
691                if event.kind == ::santity_pdk::InteractionKind::Autocomplete {
692                    let focused = event.focused_option_name.as_deref().unwrap_or("");
693                    let sub_name = event.get_subcommand_name();
694                    let sub_str = sub_name.as_deref();
695                    match (event.command_name.as_str(), sub_str, focused) {
696                        #(#sub_autocomplete_arms)*
697                        #(#generic_autocomplete_arms)*
698                        _ => return ::santity_pdk::ResponseAction::none(),
699                    }
700                }
701
702                // Subcommand dispatch
703                let parsed_sub: Option<String> = ::santity_pdk::serde_json::from_str::<::santity_pdk::serde_json::Value>(&event.options_json)
704                    .ok()
705                    .and_then(|v| match v {
706                        ::santity_pdk::serde_json::Value::Array(arr) => {
707                            arr.into_iter().find_map(|opt| {
708                                if opt.get("type").and_then(|t| t.as_u64()) == Some(1) {
709                                    opt.get("name").and_then(|n| n.as_str()).map(|s| s.to_string())
710                                } else if opt.get("type").and_then(|t| t.as_u64()) == Some(2) {
711                                    opt.get("options")
712                                        .and_then(|opts| opts.as_array())
713                                        .and_then(|sub_arr| {
714                                            sub_arr.iter().find_map(|sub_opt| {
715                                                if sub_opt.get("type").and_then(|t| t.as_u64()) == Some(1) {
716                                                    sub_opt.get("name").and_then(|n| n.as_str()).map(|s| s.to_string())
717                                                } else {
718                                                    None
719                                                }
720                                            })
721                                        })
722                                } else {
723                                    None
724                                }
725                            })
726                        }
727                        _ => None,
728                    });
729
730                if let Some(sub_name) = parsed_sub {
731                    match (event.command_name.as_str(), sub_name.as_str()) {
732                        #(#subcommand_arms)*
733                        _ => {}
734                    }
735                }
736
737                match event.command_name.as_str() {
738                    #(#command_arms)*
739                    _ => ::santity_pdk::ResponseAction::none(),
740                }
741            }
742
743            fn on_timer(callback_tag: String) {
744                let _ = ::santity_pdk::init();
745                match callback_tag.as_str() {
746                    #(#timer_arms)*
747                    _ => {
748                        #default_timer_body
749                    }
750                }
751            }
752
753            fn on_message(event: ::santity_pdk::MessageEvent) -> ::santity_pdk::ResponseAction {
754                #on_message_body
755            }
756
757            fn on_gateway_event(kind: ::santity_pdk::EventKind, payload_json: String) -> ::santity_pdk::ResponseAction {
758                let _ = ::santity_pdk::init();
759                match kind {
760                    #(#event_arms)*
761                    _ => ::santity_pdk::ResponseAction::none(),
762                }
763            }
764        }
765
766        pub use ::santity_pdk::exports;
767        pub use ::santity_pdk::export;
768
769        #[cfg(target_arch = "wasm32")]
770        export!(#self_ty);
771    };
772
773    TokenStream::from(expanded)
774}