romm-cli 0.36.0

Rust-based CLI and TUI for the ROMM 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
//! Parse a subset of OpenAPI 3.x JSON into a flat endpoint list.
//!
//! Inline `parameters` only; `$ref` on parameters is not resolved.

use anyhow::{anyhow, Result};
use percent_encoding::{utf8_percent_encode, AsciiSet, CONTROLS};
use serde_json::Value;

/// Percent-encode set for OpenAPI path parameter values (conservative).
const PATH_PARAM_ENCODE: &AsciiSet = &CONTROLS
    .add(b' ')
    .add(b'"')
    .add(b'#')
    .add(b'<')
    .add(b'>')
    .add(b'`')
    .add(b'?')
    .add(b'{')
    .add(b'}')
    .add(b'/')
    .add(b'%');

/// Replace `{name}` segments in an OpenAPI path template using percent-encoded values.
/// Returns an error if any `{...}` placeholder remains after substitution.
pub fn resolve_path_template(template: &str, values: &[(String, String)]) -> Result<String> {
    let mut out = template.to_string();
    for (name, raw) in values {
        let token = format!("{{{}}}", name);
        if out.contains(&token) {
            let encoded = utf8_percent_encode(raw, PATH_PARAM_ENCODE).to_string();
            out = out.replace(&token, &encoded);
        }
    }
    if out.contains('{') {
        return Err(anyhow!(
            "unresolved path placeholders in {:?} (fill all path parameters)",
            template
        ));
    }
    Ok(out)
}

/// Lowercase OpenAPI path-item operation keys we treat as HTTP methods.
const OPENAPI_OPERATION_METHODS: &[&str] = &[
    "get", "post", "put", "delete", "patch", "options", "head", "trace",
];

/// Returns true if `key` is an OpenAPI operation method (e.g. `get`, `post`), not `parameters` or `summary`.
pub fn is_openapi_operation_method(key: &str) -> bool {
    OPENAPI_OPERATION_METHODS
        .iter()
        .any(|m| m.eq_ignore_ascii_case(key))
}

#[derive(Debug, Clone)]
pub struct ApiParameter {
    pub name: String,
    pub param_type: String,
    pub required: bool,
    pub default: Option<String>,
    #[allow(dead_code)]
    pub description: Option<String>,
}

#[derive(Debug, Clone)]
pub struct ApiEndpoint {
    pub method: String,
    pub path: String,
    pub summary: Option<String>,
    #[allow(dead_code)]
    pub description: Option<String>,
    pub query_params: Vec<ApiParameter>,
    pub path_params: Vec<ApiParameter>,
    pub has_body: bool,
    pub tags: Vec<String>,
}

#[derive(Debug, Clone, Default)]
pub struct EndpointRegistry {
    pub endpoints: Vec<ApiEndpoint>,
}

/// Split OpenAPI `parameters` array into query vs path params. Skips `header`, `cookie`, etc.
fn parse_parameters_array(params: &[Value]) -> (Vec<ApiParameter>, Vec<ApiParameter>) {
    let mut query_params = Vec::new();
    let mut path_params = Vec::new();

    for param in params {
        let Some(param_obj) = param.as_object() else {
            continue;
        };
        // $ref not resolved — skip
        if param_obj.contains_key("$ref") {
            continue;
        }

        let name = param_obj
            .get("name")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string())
            .unwrap_or_default();

        let param_in = param_obj
            .get("in")
            .and_then(|v| v.as_str())
            .unwrap_or("query");

        let required = param_obj
            .get("required")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);

        let schema = param_obj.get("schema");
        let param_type = schema
            .and_then(|s| s.get("type"))
            .and_then(|v| v.as_str())
            .map(|s| s.to_string())
            .unwrap_or_else(|| "string".to_string());

        let default = schema.and_then(|s| s.get("default")).and_then(|v| {
            if v.is_string() {
                v.as_str().map(|s| s.to_string())
            } else {
                Some(v.to_string())
            }
        });

        let description = param_obj
            .get("description")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());

        let api_param = ApiParameter {
            name,
            param_type,
            required,
            default,
            description,
        };

        match param_in {
            "query" => query_params.push(api_param),
            "path" => path_params.push(api_param),
            _ => {}
        }
    }

    (query_params, path_params)
}

/// Path-item parameters first; operation parameters with the same name replace query/path entries respectively.
fn merge_parameter_lists(
    path_query: Vec<ApiParameter>,
    path_path: Vec<ApiParameter>,
    op_query: Vec<ApiParameter>,
    op_path: Vec<ApiParameter>,
) -> (Vec<ApiParameter>, Vec<ApiParameter>) {
    let mut query = path_query;
    let mut path = path_path;

    for p in op_query {
        query.retain(|x| x.name != p.name);
        query.push(p);
    }
    for p in op_path {
        path.retain(|x| x.name != p.name);
        path.push(p);
    }

    (query, path)
}

impl EndpointRegistry {
    pub fn from_openapi_json(json_str: &str) -> Result<Self> {
        let value: Value = serde_json::from_str(json_str)
            .map_err(|e| anyhow!("Failed to parse OpenAPI JSON: {}", e))?;

        let paths = value
            .get("paths")
            .and_then(|v| v.as_object())
            .ok_or_else(|| anyhow!("OpenAPI JSON missing 'paths' object"))?;

        let mut endpoints = Vec::new();

        for (path, path_item) in paths {
            let path_item = path_item
                .as_object()
                .ok_or_else(|| anyhow!("Invalid path definition for {}", path))?;

            let path_level = path_item
                .get("parameters")
                .and_then(|v| v.as_array())
                .map(|a| a.as_slice())
                .unwrap_or(&[]);
            let (path_q, path_p) = parse_parameters_array(path_level);

            for (method_key, operation) in path_item {
                if !is_openapi_operation_method(method_key) {
                    continue;
                }

                let operation = operation
                    .as_object()
                    .ok_or_else(|| anyhow!("Invalid operation for {} {}", method_key, path))?;

                let summary = operation
                    .get("summary")
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_string());
                let description = operation
                    .get("description")
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_string());

                let tags = operation
                    .get("tags")
                    .and_then(|v| v.as_array())
                    .map(|arr| {
                        arr.iter()
                            .filter_map(|v| v.as_str())
                            .map(|s| s.to_string())
                            .collect()
                    })
                    .unwrap_or_default();

                let op_level = operation
                    .get("parameters")
                    .and_then(|v| v.as_array())
                    .map(|a| a.as_slice())
                    .unwrap_or(&[]);
                let (op_q, op_p) = parse_parameters_array(op_level);
                let (query_params, path_params) =
                    merge_parameter_lists(path_q.clone(), path_p.clone(), op_q, op_p);

                let has_body = operation.get("requestBody").is_some();

                endpoints.push(ApiEndpoint {
                    method: method_key.to_uppercase(),
                    path: path.clone(),
                    summary,
                    description,
                    query_params,
                    path_params,
                    has_body,
                    tags,
                });
            }
        }

        endpoints.sort_by(|a, b| a.path.cmp(&b.path).then_with(|| a.method.cmp(&b.method)));

        Ok(EndpointRegistry { endpoints })
    }

    pub fn from_file(path: &str) -> Result<Self> {
        let content = std::fs::read_to_string(path)
            .map_err(|e| anyhow!("Failed to read OpenAPI file {}: {}", path, e))?;
        Self::from_openapi_json(&content)
    }

    pub fn has_endpoint(&self, method: &str, path: &str) -> bool {
        self.endpoints
            .iter()
            .any(|ep| ep.method.eq_ignore_ascii_case(method) && ep.path == path)
    }

    #[allow(dead_code)]
    pub fn get_by_tag(&self, tag: &str) -> Vec<&ApiEndpoint> {
        self.endpoints
            .iter()
            .filter(|ep| ep.tags.contains(&tag.to_string()))
            .collect()
    }

    #[allow(dead_code)]
    pub fn get_by_path_prefix(&self, prefix: &str) -> Vec<&ApiEndpoint> {
        self.endpoints
            .iter()
            .filter(|ep| ep.path.starts_with(prefix))
            .collect()
    }

    #[allow(dead_code)]
    pub fn search(&self, query: &str) -> Vec<&ApiEndpoint> {
        let query_lower = query.to_lowercase();
        self.endpoints
            .iter()
            .filter(|ep| {
                ep.path.to_lowercase().contains(&query_lower)
                    || ep.method.to_lowercase().contains(&query_lower)
                    || ep
                        .summary
                        .as_ref()
                        .map(|s| s.to_lowercase().contains(&query_lower))
                        .unwrap_or(false)
                    || ep
                        .description
                        .as_ref()
                        .map(|s| s.to_lowercase().contains(&query_lower))
                        .unwrap_or(false)
            })
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn skips_path_item_parameters_key_as_operation() {
        let json = r#"{
            "openapi": "3.0.0",
            "paths": {
                "/api/foo/{id}": {
                    "parameters": [
                        {
                            "name": "id",
                            "in": "path",
                            "required": true,
                            "schema": { "type": "string" }
                        }
                    ],
                    "summary": "path summary",
                    "get": {
                        "summary": "get foo",
                        "responses": { "200": { "description": "ok" } }
                    }
                }
            }
        }"#;

        let reg = EndpointRegistry::from_openapi_json(json).expect("parse");
        assert_eq!(reg.endpoints.len(), 1);
        let ep = &reg.endpoints[0];
        assert_eq!(ep.method, "GET");
        assert_eq!(ep.path, "/api/foo/{id}");
        assert_eq!(ep.path_params.len(), 1);
        assert_eq!(ep.path_params[0].name, "id");
    }

    #[test]
    fn operation_parameters_override_path_level_same_name() {
        let json = r#"{
            "openapi": "3.0.0",
            "paths": {
                "/x": {
                    "parameters": [
                        {
                            "name": "q",
                            "in": "query",
                            "required": false,
                            "schema": { "type": "string", "default": "base" }
                        }
                    ],
                    "get": {
                        "parameters": [
                            {
                                "name": "q",
                                "in": "query",
                                "required": true,
                                "schema": { "type": "string", "default": "op" }
                            }
                        ],
                        "responses": { "200": { "description": "ok" } }
                    }
                }
            }
        }"#;

        let reg = EndpointRegistry::from_openapi_json(json).expect("parse");
        assert_eq!(reg.endpoints[0].query_params.len(), 1);
        assert_eq!(
            reg.endpoints[0].query_params[0].default.as_deref(),
            Some("op")
        );
        assert!(reg.endpoints[0].query_params[0].required);
    }

    #[test]
    fn has_endpoint_matches_exact_path_and_case_insensitive_method() {
        let json = r#"{
            "openapi": "3.0.0",
            "paths": {
                "/api/devices": {
                    "get": { "responses": { "200": { "description": "ok" } } }
                },
                "/api/sync/devices/{device_id}/push-pull": {
                    "post": { "responses": { "200": { "description": "ok" } } }
                }
            }
        }"#;

        let reg = EndpointRegistry::from_openapi_json(json).expect("parse");
        assert!(reg.has_endpoint("GET", "/api/devices"));
        assert!(reg.has_endpoint("post", "/api/sync/devices/{device_id}/push-pull"));
        assert!(!reg.has_endpoint("POST", "/api/devices"));
        assert!(!reg.has_endpoint("POST", "/api/sync/devices/1/push-pull"));
    }

    #[test]
    fn is_openapi_operation_method_cases() {
        assert!(is_openapi_operation_method("get"));
        assert!(is_openapi_operation_method("GET"));
        assert!(!is_openapi_operation_method("parameters"));
        assert!(!is_openapi_operation_method("summary"));
    }

    #[test]
    fn resolve_path_template_substitutes_and_encodes() {
        let p = resolve_path_template("/api/roms/{id}/files", &[("id".into(), "42".into())])
            .expect("ok");
        assert_eq!(p, "/api/roms/42/files");
    }

    #[test]
    fn resolve_path_template_errors_on_missing_placeholder() {
        let e = resolve_path_template("/api/{x}", &[]).unwrap_err();
        assert!(e.to_string().contains("unresolved"));
    }
}