Skip to main content

odk_cli/generate/
mod.rs

1//! Code generation targets for client artifacts.
2//!
3//! Generates typed SDK clients, framework-specific hooks, and mock
4//! handlers directly from the CompiledSchema IR.
5
6pub mod mcp;
7pub mod msw;
8pub mod python;
9pub mod react_query;
10pub mod rust;
11pub mod sdk;
12pub mod typescript;
13pub mod util;
14
15use crate::config::McpGenerateConfig;
16use odk_schema::CompiledSchema;
17use std::collections::BTreeMap;
18use std::fmt;
19
20/// Available generation targets.
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub enum Target {
23    Sdk,
24    ReactQuery,
25    Msw,
26    Mcp,
27    Python,
28    Typescript,
29    Rust,
30}
31
32impl Target {
33    /// Parse a target name string.
34    pub fn parse(s: &str) -> Option<Self> {
35        match s.to_lowercase().as_str() {
36            "sdk" => Some(Target::Sdk),
37            "react-query" | "reactquery" => Some(Target::ReactQuery),
38            "msw" => Some(Target::Msw),
39            "mcp" => Some(Target::Mcp),
40            "python" | "py" => Some(Target::Python),
41            "typescript" | "ts" => Some(Target::Typescript),
42            "rust" | "rs" => Some(Target::Rust),
43            _ => None,
44        }
45    }
46
47    /// Parse a comma-separated list of target names.
48    pub fn parse_list(s: &str) -> Result<Vec<Self>, String> {
49        let mut targets = Vec::new();
50        for part in s.split(',') {
51            let trimmed = part.trim();
52            if trimmed.is_empty() {
53                continue;
54            }
55            match Self::parse(trimmed) {
56                Some(t) => {
57                    if !targets.contains(&t) {
58                        targets.push(t);
59                    }
60                }
61                None => {
62                    return Err(format!(
63                        "Unknown target: '{}'. Available: sdk, react-query, msw, mcp, python, typescript, rust",
64                        trimmed
65                    ));
66                }
67            }
68        }
69        Ok(targets)
70    }
71}
72
73impl fmt::Display for Target {
74    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75        match self {
76            Target::Sdk => write!(f, "sdk"),
77            Target::ReactQuery => write!(f, "react-query"),
78            Target::Msw => write!(f, "msw"),
79            Target::Mcp => write!(f, "mcp"),
80            Target::Python => write!(f, "python"),
81            Target::Typescript => write!(f, "typescript"),
82            Target::Rust => write!(f, "rust"),
83        }
84    }
85}
86
87/// Generate client artifacts for the requested targets.
88///
89/// Returns a map of relative file paths to their contents.
90/// The `sdk` target is always included if `react-query` or `msw` is requested.
91pub fn generate(
92    schema: &CompiledSchema,
93    targets: &[Target],
94    mcp_config: Option<&McpGenerateConfig>,
95) -> BTreeMap<String, String> {
96    let mut output = BTreeMap::new();
97
98    // SDK is always generated if any target needs it
99    let needs_sdk = targets.contains(&Target::Sdk)
100        || targets.contains(&Target::ReactQuery)
101        || targets.contains(&Target::Msw);
102
103    if needs_sdk {
104        output.extend(sdk::generate(schema));
105    }
106
107    if targets.contains(&Target::ReactQuery) {
108        output.extend(react_query::generate(schema));
109    }
110
111    if targets.contains(&Target::Msw) {
112        output.extend(msw::generate(schema));
113    }
114
115    if targets.contains(&Target::Python) {
116        output.extend(python::generate(schema));
117    }
118
119    if targets.contains(&Target::Typescript) {
120        output.extend(typescript::generate(schema));
121    }
122
123    if targets.contains(&Target::Rust) {
124        output.extend(rust::generate(schema));
125    }
126
127    if targets.contains(&Target::Mcp) {
128        if let Some(cfg) = mcp_config {
129            output.extend(mcp::generate_with_config(schema, cfg));
130        } else {
131            output.extend(mcp::generate(schema));
132        }
133    }
134
135    output
136}
137
138/// Reject a schema a requested target cannot yet emit correctly, before any
139/// code is generated.
140///
141/// Only the `rust` and `typescript` targets emit data-carrying (tagged) unions;
142/// the `python` target emits string enums only and would silently drop the
143/// payloads. The `rust` target also cannot emit a reference cycle its boxing
144/// does not break (mutual recursion), which would produce infinitely-sized Rust.
145/// Returning a clear error here turns both silent failures into an actionable
146/// message. Targets that handle the schema impose no restriction.
147pub fn check_support(schema: &CompiledSchema, targets: &[Target]) -> Result<(), String> {
148    if targets.contains(&Target::Python)
149        && let Some(union) = schema.unions.iter().find(|u| u.is_data_carrying())
150    {
151        return Err(format!(
152            "the python target does not yet support the data-carrying (tagged) union `{}`; it \
153             emits string enums only, so it would drop the variant payloads. Use \
154             -t rust,typescript for tagged unions.",
155            union.name
156        ));
157    }
158
159    if targets.contains(&Target::Rust)
160        && let Some(message) = rust::unsupported_recursion(schema)
161    {
162        return Err(message);
163    }
164
165    Ok(())
166}
167
168#[cfg(test)]
169mod tests {
170    use super::*;
171    use odk_schema::{CompiledType, CompiledUnion, CompiledUnionVariant};
172
173    fn string_enum() -> CompiledUnion {
174        CompiledUnion {
175            name: "Status".to_string(),
176            variants: vec![CompiledUnionVariant::literal_string("draft")],
177            ..Default::default()
178        }
179    }
180
181    fn tagged_union() -> CompiledUnion {
182        CompiledUnion {
183            name: "OpNode".to_string(),
184            tag: Some("op".to_string()),
185            variants: vec![CompiledUnionVariant {
186                name: "cube".to_string(),
187                variant_type: Some(CompiledType::Object { fields: vec![] }),
188            }],
189            ..Default::default()
190        }
191    }
192
193    fn schema_with_union(union: CompiledUnion) -> CompiledSchema {
194        let mut schema = CompiledSchema::new("S");
195        schema.add_union(union);
196        schema
197    }
198
199    #[test]
200    fn python_rejects_a_data_carrying_union() {
201        let schema = schema_with_union(tagged_union());
202        let err = check_support(&schema, &[Target::Python]).unwrap_err();
203        assert!(err.contains("python") && err.contains("OpNode"), "{err}");
204    }
205
206    #[test]
207    fn python_allows_a_string_enum() {
208        let schema = schema_with_union(string_enum());
209        assert!(check_support(&schema, &[Target::Python]).is_ok());
210    }
211
212    #[test]
213    fn typescript_allows_a_data_carrying_union() {
214        let schema = schema_with_union(tagged_union());
215        assert!(check_support(&schema, &[Target::Typescript]).is_ok());
216    }
217
218    #[test]
219    fn rust_allows_a_data_carrying_union_without_mutual_recursion() {
220        let schema = schema_with_union(tagged_union());
221        assert!(check_support(&schema, &[Target::Rust]).is_ok());
222    }
223}