kayto 0.1.10

Fast OpenAPI parser that turns imperfect specs into a stable output schema with actionable diagnostics.
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
use crate::parser::Request;
use std::collections::{BTreeMap, HashSet};

use super::{convert, names, prepare_model_data, utils};

/// Renders the final `schema.dart` content from parsed request IR.
pub fn render_schema_file(requests: &[Request]) -> String {
    let model_data = prepare_model_data::prepare_model_data(requests);
    let identifiers = names::build_model_identifiers(&model_data.names);
    let methods = group_requests_by_method(requests);

    let mut out = String::new();
    out.push_str("// This file is generated by kayto. Do not edit manually.\n\n");
    render_model_types(&mut out, &model_data, &identifiers);
    render_schemas_namespace(&mut out, &model_data, &identifiers);
    render_endpoint_meta_class(&mut out);
    render_endpoints_namespace(&mut out, &methods, &identifiers);
    out
}

/// Renders top-level model type aliases used by schema registry and endpoints.
fn render_model_types(
    out: &mut String,
    model_data: &prepare_model_data::ModelData,
    identifiers: &BTreeMap<String, String>,
) {
    for model_name in &model_data.names {
        let ident = identifiers
            .get(model_name)
            .expect("type identifier must exist for each model name");

        let dart_type = match model_data.definitions.get(model_name) {
            Some(schema_type) => convert::schema_to_dart(schema_type, identifiers),
            None => "Object?".to_string(),
        };

        out.push_str(&format!("typedef {ident} = {dart_type};\n\n"));
    }
}

/// Renders schema registry with original schema keys and generated Dart alias names.
fn render_schemas_namespace(
    out: &mut String,
    model_data: &prepare_model_data::ModelData,
    identifiers: &BTreeMap<String, String>,
) {
    out.push_str("abstract final class Schemas {\n");
    out.push_str("  static const Map<String, String> types = {\n");

    for model_name in &model_data.names {
        let ident = identifiers
            .get(model_name)
            .expect("type identifier must exist for each model name");
        out.push_str(&format!(
            "    {}: {},\n",
            utils::dart_quote(model_name),
            utils::dart_quote(ident)
        ));
    }

    out.push_str("  };\n");
    out.push_str("}\n\n");
}

/// Renders endpoint metadata class used in `Endpoints.byMethod`.
fn render_endpoint_meta_class(out: &mut String) {
    out.push_str("class EndpointMeta {\n");
    out.push_str("  final String path;\n");
    out.push_str("  final String method;\n");
    out.push_str("  final String? operationId;\n");
    out.push_str("  final Map<String, Map<String, String>>? params;\n");
    out.push_str("  final String? bodyType;\n");
    out.push_str("  final Map<int, String>? responses;\n\n");
    out.push_str("  const EndpointMeta({\n");
    out.push_str("    required this.path,\n");
    out.push_str("    required this.method,\n");
    out.push_str("    this.operationId,\n");
    out.push_str("    this.params,\n");
    out.push_str("    this.bodyType,\n");
    out.push_str("    this.responses,\n");
    out.push_str("  });\n");
    out.push_str("}\n\n");
}

/// Renders endpoint metadata namespace grouped by HTTP method.
fn render_endpoints_namespace(
    out: &mut String,
    methods: &BTreeMap<String, BTreeMap<String, &Request>>,
    identifiers: &BTreeMap<String, String>,
) {
    render_method_endpoint_classes(out, methods, identifiers);

    out.push_str("abstract final class Endpoints {\n");
    for method in methods.keys() {
        let class_name = method_class_name(method);
        out.push_str(&format!("  static const {method} = {class_name}();\n"));
    }

    out.push('\n');
    out.push_str("  static const Map<String, Map<String, EndpointMeta>> byMethod = {\n");
    for method in methods.keys() {
        let class_name = method_class_name(method);
        out.push_str(&format!(
            "    {}: {class_name}.byPath,\n",
            utils::dart_quote(method)
        ));
    }

    out.push_str("  };\n");
    out.push_str("}\n");
}

/// Renders typed method classes with endpoint getters and by-path maps.
fn render_method_endpoint_classes(
    out: &mut String,
    methods: &BTreeMap<String, BTreeMap<String, &Request>>,
    identifiers: &BTreeMap<String, String>,
) {
    for (method, path_map) in methods {
        let class_name = method_class_name(method);
        let getter_names = build_endpoint_getter_names(path_map);

        out.push_str(&format!("class {class_name} {{\n"));
        out.push_str(&format!("  const {class_name}();\n\n"));
        out.push_str("  static const Map<String, EndpointMeta> byPath = {\n");
        for (path, req) in path_map {
            render_endpoint_entry(out, "    ", method, path, req, identifiers);
        }
        out.push_str("  };\n\n");

        for (path, getter_name) in getter_names {
            out.push_str(&format!(
                "  EndpointMeta get {getter_name} => byPath[{}]!;\n",
                utils::dart_quote(&path)
            ));
        }
        out.push('\n');
        out.push_str("  EndpointMeta operator [](String path) => byPath[path]!;\n");

        out.push_str("}\n\n");
    }
}

/// Renders a single endpoint metadata record under a method-specific map.
fn render_endpoint_entry(
    out: &mut String,
    entry_indent: &str,
    method: &str,
    path: &str,
    req: &Request,
    identifiers: &BTreeMap<String, String>,
) {
    let field_indent = format!("{entry_indent}  ");

    out.push_str(&format!(
        "{entry_indent}{}: EndpointMeta(\n",
        utils::dart_quote(path)
    ));
    out.push_str(&format!(
        "{field_indent}path: {},\n",
        utils::dart_quote(&req.path)
    ));
    out.push_str(&format!(
        "{field_indent}method: {},\n",
        utils::dart_quote(method)
    ));

    if let Some(operation_id) = &req.operation_id {
        out.push_str(&format!(
            "{field_indent}operationId: {},\n",
            utils::dart_quote(operation_id)
        ));
    }

    if let Some(params_meta) = convert::params_to_dart_meta(req, identifiers) {
        out.push_str(&format!(
            "{field_indent}params: {},\n",
            utils::indent_inline(&params_meta, &field_indent)
        ));
    }

    if let Some(body) = req.body.as_ref() {
        let body_type = convert::parsed_response_to_dart_type(body, identifiers);
        out.push_str(&format!(
            "{field_indent}bodyType: {},\n",
            utils::dart_quote(&body_type)
        ));
    }

    if let Some(responses_meta) = convert::responses_to_dart_meta(req, identifiers) {
        out.push_str(&format!(
            "{field_indent}responses: {},\n",
            utils::indent_inline(&responses_meta, &field_indent)
        ));
    }

    out.push_str(&format!("{entry_indent}),\n"));
}

/// Groups parsed requests by HTTP method and then by path for deterministic output.
fn group_requests_by_method(requests: &[Request]) -> BTreeMap<String, BTreeMap<String, &Request>> {
    let mut methods: BTreeMap<String, BTreeMap<String, &Request>> = BTreeMap::new();
    for req in requests {
        methods
            .entry(req.method.to_lowercase())
            .or_default()
            .insert(req.path.clone(), req);
    }
    methods
}

/// Builds a stable method class name from an HTTP method token.
fn method_class_name(method: &str) -> String {
    format!("Endpoints{}", upper_camel(method))
}

/// Converts an arbitrary token to UpperCamelCase.
fn upper_camel(value: &str) -> String {
    let mut out = String::new();
    let mut next_upper = true;

    for ch in value.chars() {
        if !ch.is_ascii_alphanumeric() {
            next_upper = true;
            continue;
        }

        if next_upper {
            out.push(ch.to_ascii_uppercase());
            next_upper = false;
            continue;
        }

        out.push(ch);
    }

    if out.is_empty() {
        "Value".to_string()
    } else {
        out
    }
}

/// Builds stable getter names for each endpoint path in a method group.
fn build_endpoint_getter_names(path_map: &BTreeMap<String, &Request>) -> BTreeMap<String, String> {
    let mut used = HashSet::new();
    let mut result = BTreeMap::new();

    for path in path_map.keys() {
        let base = sanitize_endpoint_getter_name(path);
        let mut candidate = base.clone();
        let mut n = 2usize;

        while used.contains(&candidate) {
            candidate = format!("{base}{n}");
            n += 1;
        }

        used.insert(candidate.clone());
        result.insert(path.clone(), candidate);
    }

    result
}

/// Sanitizes an endpoint path into a lowerCamelCase getter name.
fn sanitize_endpoint_getter_name(path: &str) -> String {
    let mut parts: Vec<String> = Vec::new();
    let mut current = String::new();

    for ch in path.chars() {
        if ch.is_ascii_alphanumeric() {
            current.push(ch);
            continue;
        }

        if !current.is_empty() {
            parts.push(current);
            current = String::new();
        }
    }

    if !current.is_empty() {
        parts.push(current);
    }

    if parts.is_empty() {
        return "root".to_string();
    }

    let mut out = String::new();
    for (idx, part) in parts.into_iter().enumerate() {
        let mut chars = part.chars();
        let Some(first) = chars.next() else {
            continue;
        };

        if idx == 0 {
            out.push(first.to_ascii_lowercase());
        } else {
            out.push(first.to_ascii_uppercase());
        }

        out.extend(chars);
    }

    if out
        .chars()
        .next()
        .map(|ch| ch.is_ascii_digit())
        .unwrap_or(false)
    {
        out = format!("endpoint{out}");
    }

    match out.as_str() {
        "class" | "enum" | "switch" | "case" | "default" | "get" | "set" | "static"
        | "void" | "final" | "const" => format!("{out}Endpoint"),
        _ => out,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parser::{ParsedResponse, Request, SchemaType};
    use crate::{parser, spec, test_fixtures};
    use std::collections::BTreeMap;

    /// Creates a deterministic single-endpoint fixture for snapshot rendering checks.
    fn fixture_requests() -> Vec<Request> {
        let mut responses = BTreeMap::new();
        responses.insert(
            200,
            ParsedResponse {
                schema_type: Some(SchemaType::Ref("Item".to_string())),
                schema_name: None,
            },
        );

        vec![Request {
            path: "/items".to_string(),
            method: "get".to_string(),
            operation_id: Some("listItems".to_string()),
            params: None,
            body: None,
            responses: Some(responses),
        }]
    }

    /// Verifies rendered Dart output for a small fixture remains stable.
    #[test]
    fn renders_expected_schema_snapshot() {
        let output = render_schema_file(&fixture_requests());
        let expected = r#"// This file is generated by kayto. Do not edit manually.

typedef Item = Object?;

abstract final class Schemas {
  static const Map<String, String> types = {
    'Item': 'Item',
  };
}

class EndpointMeta {
  final String path;
  final String method;
  final String? operationId;
  final Map<String, Map<String, String>>? params;
  final String? bodyType;
  final Map<int, String>? responses;

  const EndpointMeta({
    required this.path,
    required this.method,
    this.operationId,
    this.params,
    this.bodyType,
    this.responses,
  });
}

class EndpointsGet {
  const EndpointsGet();

  static const Map<String, EndpointMeta> byPath = {
    '/items': EndpointMeta(
      path: '/items',
      method: 'get',
      operationId: 'listItems',
      responses: {
        200: 'Item',
      },
    ),
  };

  EndpointMeta get items => byPath['/items']!;

  EndpointMeta operator [](String path) => byPath[path]!;
}

abstract final class Endpoints {
  static const get = EndpointsGet();

  static const Map<String, Map<String, EndpointMeta>> byMethod = {
    'get': EndpointsGet.byPath,
  };
}
"#;
        assert_eq!(output, expected);
    }

    /// Parses OpenAPI JSON and returns parser IR requests for end-to-end rendering tests.
    fn parse_requests_from_json(input: &str) -> Vec<Request> {
        let openapi: spec::OpenAPI = serde_json::from_str(input).expect("valid OpenAPI json");
        let parsed = parser::parse(&openapi).expect("parser should return output");
        assert!(
            parsed.issues.is_empty(),
            "expected no parser issues, got: {:#?}",
            parsed.issues
        );
        parsed.requests
    }

    /// Verifies Dart rendering includes schemas and endpoint metadata for combinator-heavy specs.
    #[test]
    fn renders_combinators_end_to_end() {
        let requests = parse_requests_from_json(test_fixtures::COMBINATORS_OPENAPI_JSON);

        let output = render_schema_file(&requests);
        assert!(output.contains("typedef BasePet = Map<String, Object?>;"));
        assert!(output.contains("typedef CatKind = Object?;"));
        assert!(output.contains("typedef PetFilter = Object?;"));
        assert!(output.contains("abstract final class Endpoints"));
        assert!(output.contains("class EndpointsPost"));
        assert!(output.contains("static const post = EndpointsPost();"));
        assert!(output.contains("bodyType: 'CreatePetRequest'"));
        assert!(output.contains("201: 'PetDetails'"));
    }
}