rusty-lcu 0.1.0

Generated Rust client helpers for the League Client Update API
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
use std::{
    collections::{HashMap, HashSet},
    env, fs,
    path::Path,
};

use heck::{ToPascalCase, ToShoutySnakeCase, ToSnakeCase};
use serde_json::Value;

fn main() {
    println!("cargo:rerun-if-env-changed=LCU_SWAGGER_PATH");
    println!("cargo:rerun-if-changed=schema/swagger.json");

    let swagger_path =
        env::var("LCU_SWAGGER_PATH").unwrap_or_else(|_| "schema/swagger.json".to_string());

    let swagger = fs::read_to_string(&swagger_path).unwrap_or_else(|error| {
        panic!(
            "failed to read {swagger_path}: {error}. Download it from https://raw.githubusercontent.com/dysolix/hasagi-types/main/swagger.json"
        )
    });

    let document: Value = serde_json::from_str(&swagger).expect("valid OpenAPI JSON");
    let paths = document
        .get("paths")
        .and_then(Value::as_object)
        .expect("OpenAPI document with paths");
    let schemas = document
        .get("components")
        .and_then(|components| components.get("schemas"))
        .and_then(Value::as_object)
        .cloned()
        .unwrap_or_default();
    let schema_info = SchemaInfo::from_document(&document);

    let mut endpoints = Vec::new();
    let methods = ["delete", "get", "patch", "post", "put"];

    for (path, item) in paths {
        let Some(item) = item.as_object() else {
            continue;
        };

        for method in methods {
            let Some(operation) = item.get(method).and_then(Value::as_object) else {
                continue;
            };

            let operation_id = operation
                .get("operationId")
                .and_then(Value::as_str)
                .map(str::to_string)
                .unwrap_or_else(|| fallback_operation_id(method, path));

            endpoints.push(Operation {
                method: method.to_ascii_uppercase(),
                path: path.clone(),
                operation_id,
                path_params: parameter_names(operation, "path"),
                query_params: parameter_names(operation, "query"),
                required_query_params: required_parameter_names(operation, "query"),
                has_body: operation.get("requestBody").is_some(),
                request_type: request_type(operation),
                response_type: response_type(operation),
                tags: operation
                    .get("tags")
                    .and_then(Value::as_array)
                    .map(|tags| {
                        tags.iter()
                            .filter_map(Value::as_str)
                            .map(str::to_string)
                            .collect::<Vec<_>>()
                    })
                    .unwrap_or_default(),
            });
        }
    }

    endpoints.sort_by(|left, right| {
        left.path
            .cmp(&right.path)
            .then(left.method.cmp(&right.method))
            .then(left.operation_id.cmp(&right.operation_id))
    });

    let generated = generate(&endpoints, &schemas, &schema_info);
    let out_dir = env::var("OUT_DIR").expect("OUT_DIR set");
    fs::write(Path::new(&out_dir).join("lcu_endpoints.rs"), generated)
        .expect("write generated endpoints");
}

#[derive(Debug)]
struct Operation {
    method: String,
    path: String,
    operation_id: String,
    path_params: Vec<String>,
    query_params: Vec<String>,
    required_query_params: Vec<String>,
    has_body: bool,
    request_type: Option<String>,
    response_type: Option<String>,
    tags: Vec<String>,
}

#[derive(Debug)]
struct SchemaInfo {
    title: String,
    version: String,
    upstream_url: String,
}

impl SchemaInfo {
    fn from_document(document: &Value) -> Self {
        Self {
            title: document
                .get("info")
                .and_then(|info| info.get("title"))
                .and_then(Value::as_str)
                .unwrap_or("LCU SCHEMA")
                .to_string(),
            version: document
                .get("info")
                .and_then(|info| info.get("version"))
                .and_then(Value::as_str)
                .unwrap_or("unknown")
                .to_string(),
            upstream_url:
                "https://raw.githubusercontent.com/dysolix/hasagi-types/main/swagger.json"
                    .to_string(),
        }
    }
}

fn parameter_names(operation: &serde_json::Map<String, Value>, location: &str) -> Vec<String> {
    operation
        .get("parameters")
        .and_then(Value::as_array)
        .into_iter()
        .flatten()
        .filter(|parameter| parameter.get("in").and_then(Value::as_str) == Some(location))
        .filter_map(|parameter| parameter.get("name").and_then(Value::as_str))
        .map(str::to_string)
        .collect()
}

fn required_parameter_names(
    operation: &serde_json::Map<String, Value>,
    location: &str,
) -> Vec<String> {
    operation
        .get("parameters")
        .and_then(Value::as_array)
        .into_iter()
        .flatten()
        .filter(|parameter| parameter.get("in").and_then(Value::as_str) == Some(location))
        .filter(|parameter| parameter.get("required").and_then(Value::as_bool) == Some(true))
        .filter_map(|parameter| parameter.get("name").and_then(Value::as_str))
        .map(str::to_string)
        .collect()
}

fn fallback_operation_id(method: &str, path: &str) -> String {
    let path_name = path
        .trim_matches('/')
        .replace(['/', '{', '}'], "_")
        .replace('-', "_");
    format!("{method}_{path_name}")
}

fn request_type(operation: &serde_json::Map<String, Value>) -> Option<String> {
    operation
        .get("requestBody")
        .and_then(|body| body.get("content"))
        .and_then(json_schema_from_content)
        .and_then(ref_type_name)
}

fn response_type(operation: &serde_json::Map<String, Value>) -> Option<String> {
    let responses = operation.get("responses")?.as_object()?;
    ["2XX", "200", "201", "202", "204"]
        .iter()
        .filter_map(|status| responses.get(*status))
        .filter_map(|response| response.get("content"))
        .filter_map(json_schema_from_content)
        .find_map(ref_type_name)
}

fn json_schema_from_content(content: &Value) -> Option<&Value> {
    let content = content.as_object()?;
    content
        .get("application/json")
        .or_else(|| content.values().next())
        .and_then(|media_type| media_type.get("schema"))
}

fn ref_type_name(schema: &Value) -> Option<String> {
    schema
        .get("$ref")
        .and_then(Value::as_str)
        .and_then(|reference| reference.rsplit('/').next())
        .map(type_name)
}

fn generate(
    endpoints: &[Operation],
    schemas: &serde_json::Map<String, Value>,
    schema_info: &SchemaInfo,
) -> String {
    let mut used_functions = HashMap::<String, usize>::new();
    let mut output = generate_models(schemas);
    let tags = unique_tags(endpoints);
    output.push_str(&format!(
        "pub const SCHEMA_TITLE: &str = {};\npub const SCHEMA_VERSION: &str = {};\npub const SCHEMA_UPSTREAM_URL: &str = {};\n\n",
        rust_string(&schema_info.title),
        rust_string(&schema_info.version),
        rust_string(&schema_info.upstream_url),
    ));
    output.push_str(
        r#"#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Endpoint {
    pub operation_id: &'static str,
    pub method: &'static str,
    pub path: &'static str,
    pub path_params: &'static [&'static str],
    pub query_params: &'static [&'static str],
    pub required_query_params: &'static [&'static str],
    pub has_body: bool,
    pub request_type: Option<&'static str>,
    pub response_type: Option<&'static str>,
    pub tags: &'static [&'static str],
}

"#,
    );

    for endpoint in endpoints {
        let constant = constant_name(&endpoint.operation_id);
        let path_params = string_slice(&endpoint.path_params);
        let query_params = string_slice(&endpoint.query_params);
        let required_query_params = string_slice(&endpoint.required_query_params);
        let tags = string_slice(&endpoint.tags);

        output.push_str(&format!(
            "pub const {constant}: Endpoint = Endpoint {{ operation_id: {}, method: {}, path: {}, path_params: {path_params}, query_params: {query_params}, required_query_params: {required_query_params}, has_body: {}, request_type: {}, response_type: {}, tags: {tags} }};\n",
            rust_string(&endpoint.operation_id),
            rust_string(&endpoint.method),
            rust_string(&endpoint.path),
            endpoint.has_body,
            option_string(endpoint.request_type.as_deref()),
            option_string(endpoint.response_type.as_deref()),
        ));
    }

    output.push_str("\npub const ENDPOINTS: &[Endpoint] = &[\n");
    for endpoint in endpoints {
        output.push_str(&format!("    {},\n", constant_name(&endpoint.operation_id)));
    }
    output.push_str("];\n\n");

    output.push_str("pub const TAGS: &[&str] = &[\n");
    for tag in tags {
        output.push_str(&format!("    {},\n", rust_string(&tag)));
    }
    output.push_str("];\n\n");

    output.push_str(
        r#"pub fn find_endpoint(method: &str, path: &str) -> Option<&'static Endpoint> {
    ENDPOINTS
        .iter()
        .find(|endpoint| endpoint.method.eq_ignore_ascii_case(method) && path_matches_template(endpoint.path, path))
}

pub fn find_endpoint_by_operation_id(operation_id: &str) -> Option<&'static Endpoint> {
    ENDPOINTS
        .iter()
        .find(|endpoint| endpoint.operation_id == operation_id)
}

pub fn endpoints_for_tag(tag: &str) -> impl Iterator<Item = &'static Endpoint> + '_ {
    ENDPOINTS
        .iter()
        .filter(move |endpoint| endpoint.tags.iter().any(|endpoint_tag| *endpoint_tag == tag))
}

pub fn endpoints_for_path_prefix(prefix: &str) -> impl Iterator<Item = &'static Endpoint> + '_ {
    ENDPOINTS
        .iter()
        .filter(move |endpoint| endpoint.path.starts_with(prefix))
}

pub fn path_matches_template(template: &str, path: &str) -> bool {
    let template_segments = template.trim_matches('/').split('/').collect::<Vec<_>>();
    let path_segments = path.trim_matches('/').split('/').collect::<Vec<_>>();

    if template_segments.len() != path_segments.len() {
        return false;
    }

    template_segments
        .iter()
        .zip(path_segments.iter())
        .all(|(template_segment, path_segment)| {
            (template_segment.starts_with('{') && template_segment.ends_with('}'))
                || template_segment == path_segment
        })
}

"#,
    );

    for endpoint in endpoints {
        let function = unique_function_name(&endpoint.operation_id, &mut used_functions);
        let constant = constant_name(&endpoint.operation_id);
        output.push_str(&format!(
            "pub async fn {function}(client: &crate::LcuClient, params: crate::EndpointParams) -> crate::Result<serde_json::Value> {{\n    client.request_endpoint(&{constant}, params).await\n}}\n\n"
        ));

        if let Some(response_type) = &endpoint.response_type {
            output.push_str(&format!(
                "pub async fn {function}_typed(client: &crate::LcuClient, params: crate::EndpointParams) -> crate::Result<models::{response_type}> {{\n    client.request_endpoint_as(&{constant}, params).await\n}}\n\n"
            ));
        }

        if let Some(request_type) = &endpoint.request_type {
            output.push_str(&format!(
                "pub async fn {function}_with_body(client: &crate::LcuClient, params: crate::EndpointParams, body: &models::{request_type}) -> crate::Result<serde_json::Value> {{\n    client.request_endpoint(&{constant}, params.body(body)?).await\n}}\n\n"
            ));

            if let Some(response_type) = &endpoint.response_type {
                output.push_str(&format!(
                    "pub async fn {function}_with_body_typed(client: &crate::LcuClient, params: crate::EndpointParams, body: &models::{request_type}) -> crate::Result<models::{response_type}> {{\n    client.request_endpoint_as(&{constant}, params.body(body)?).await\n}}\n\n"
                ));
            }
        }
    }

    output
}

fn unique_tags(endpoints: &[Operation]) -> Vec<String> {
    let mut tags = endpoints
        .iter()
        .flat_map(|endpoint| endpoint.tags.iter().cloned())
        .collect::<Vec<_>>();
    tags.sort();
    tags.dedup();
    tags
}

fn generate_models(schemas: &serde_json::Map<String, Value>) -> String {
    let mut output = String::from(
        r#"pub mod models {
    use serde::{Deserialize, Serialize};
    use serde_json::Value;
    use std::collections::HashMap;

"#,
    );

    let mut names = schemas.keys().collect::<Vec<_>>();
    names.sort();

    for name in names {
        let Some(schema) = schemas.get(name).and_then(Value::as_object) else {
            continue;
        };
        let type_name = type_name(name);

        if schema.get("type").and_then(Value::as_str) == Some("object")
            && schema
                .get("properties")
                .and_then(Value::as_object)
                .is_some()
        {
            output.push_str(&generate_struct(&type_name, schema));
        } else {
            let alias_type = schema_type(&Value::Object(schema.clone()));
            output.push_str(&format!("    pub type {type_name} = {alias_type};\n\n"));
        }
    }

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

fn generate_struct(name: &str, schema: &serde_json::Map<String, Value>) -> String {
    let required = schema
        .get("required")
        .and_then(Value::as_array)
        .map(|values| {
            values
                .iter()
                .filter_map(Value::as_str)
                .collect::<HashSet<_>>()
        })
        .unwrap_or_default();

    let mut output = format!(
        "    #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]\n    pub struct {name} {{\n"
    );

    let mut fields = schema
        .get("properties")
        .and_then(Value::as_object)
        .expect("properties checked")
        .iter()
        .collect::<Vec<_>>();
    fields.sort_by(|left, right| left.0.cmp(right.0));

    for (json_name, field_schema) in fields {
        let field_name = field_name(json_name);
        let mut field_type = schema_type(field_schema);
        let is_required = required.contains(json_name.as_str());

        if !is_required {
            field_type = format!("Option<{field_type}>");
        }

        let serde_options = if is_required {
            format!("rename = {}", rust_string(json_name))
        } else {
            format!(
                "rename = {}, default, skip_serializing_if = \"Option::is_none\"",
                rust_string(json_name)
            )
        };
        output.push_str(&format!("        #[serde({serde_options})]\n"));
        output.push_str(&format!("        pub {field_name}: {field_type},\n"));
    }

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

fn schema_type(schema: &Value) -> String {
    if let Some(type_name) = ref_type_name(schema) {
        return type_name;
    }

    if schema.get("nullable").and_then(Value::as_bool) == Some(true) {
        let mut cloned = schema.clone();
        if let Some(object) = cloned.as_object_mut() {
            object.remove("nullable");
        }
        return format!("Option<{}>", schema_type(&cloned));
    }

    if schema.get("oneOf").is_some()
        || schema.get("anyOf").is_some()
        || schema.get("allOf").is_some()
    {
        return "Value".to_string();
    }

    match schema.get("type").and_then(Value::as_str) {
        Some("array") => {
            let item_type = schema
                .get("items")
                .map(schema_type)
                .unwrap_or_else(|| "Value".to_string());
            format!("Vec<{item_type}>")
        }
        Some("boolean") => "bool".to_string(),
        Some("integer") => integer_type(schema),
        Some("number") => "f64".to_string(),
        Some("string") => "String".to_string(),
        Some("object") => {
            if let Some(additional) = schema.get("additionalProperties") {
                if additional == &Value::Bool(true) {
                    return "HashMap<String, Value>".to_string();
                }
                if additional.is_object() {
                    return format!("HashMap<String, {}>", schema_type(additional));
                }
            }
            "Value".to_string()
        }
        _ => "Value".to_string(),
    }
}

fn integer_type(schema: &Value) -> String {
    match schema.get("format").and_then(Value::as_str) {
        Some("uint8") | Some("uint16") | Some("uint32") => "u32".to_string(),
        Some("uint64") => "u64".to_string(),
        Some("int8") | Some("int16") | Some("int32") => "i32".to_string(),
        Some("int64") => "i64".to_string(),
        _ if schema
            .get("minimum")
            .and_then(Value::as_i64)
            .is_some_and(|minimum| minimum >= 0) =>
        {
            "u64".to_string()
        }
        _ => "i64".to_string(),
    }
}

fn rust_string(value: &str) -> String {
    serde_json::to_string(value).expect("string serializes")
}

fn option_string(value: Option<&str>) -> String {
    value
        .map(|value| format!("Some({})", rust_string(value)))
        .unwrap_or_else(|| "None".to_string())
}

fn type_name(value: &str) -> String {
    let mut name = value.to_pascal_case();
    name.retain(|character| character == '_' || character.is_ascii_alphanumeric());
    if name.is_empty() {
        name = "GeneratedModel".to_string();
    }
    if name
        .chars()
        .next()
        .is_some_and(|character| character.is_ascii_digit())
    {
        name.insert_str(0, "Model");
    }
    name
}

fn field_name(value: &str) -> String {
    let keywords = rust_keywords();
    let mut name = value.to_snake_case();
    name.retain(|character| character == '_' || character.is_ascii_alphanumeric());
    if name.is_empty() {
        name = "field".to_string();
    }
    if name
        .chars()
        .next()
        .is_some_and(|character| character.is_ascii_digit())
    {
        name.insert_str(0, "field_");
    }
    if keywords.contains(name.as_str()) {
        name.push('_');
    }
    name
}

fn string_slice(values: &[String]) -> String {
    if values.is_empty() {
        return "&[]".to_string();
    }

    let values = values
        .iter()
        .map(|value| format!("    {},", rust_string(value)))
        .collect::<Vec<_>>()
        .join("\n");

    format!("&[\n{values}\n]")
}

fn constant_name(operation_id: &str) -> String {
    let mut name = operation_id.to_shouty_snake_case();
    name.retain(|character| character == '_' || character.is_ascii_alphanumeric());
    if name
        .chars()
        .next()
        .is_some_and(|character| character.is_ascii_digit())
    {
        name.insert_str(0, "ENDPOINT_");
    }
    name
}

fn unique_function_name(operation_id: &str, used: &mut HashMap<String, usize>) -> String {
    let keywords = rust_keywords();
    let mut name = operation_id.to_snake_case();
    name.retain(|character| character == '_' || character.is_ascii_alphanumeric());
    if name.is_empty() {
        name = "endpoint".to_string();
    }
    if name
        .chars()
        .next()
        .is_some_and(|character| character.is_ascii_digit())
    {
        name.insert_str(0, "endpoint_");
    }
    if keywords.contains(name.as_str()) {
        name.push('_');
    }

    let count = used.entry(name.clone()).or_insert(0);
    *count += 1;
    if *count == 1 {
        name
    } else {
        format!("{name}_{count}")
    }
}

fn rust_keywords() -> HashSet<&'static str> {
    [
        "as", "async", "await", "break", "const", "continue", "crate", "dyn", "else", "enum",
        "extern", "false", "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod", "move",
        "mut", "pub", "ref", "return", "self", "Self", "static", "struct", "super", "trait",
        "true", "type", "unsafe", "use", "where", "while",
    ]
    .into_iter()
    .collect()
}