vimanam 0.6.0

OpenAPI/Swagger to Markdown documentation generator with grouping, filtering, and detail levels for docs and LLM context
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
use anyhow::{Context, Result};
use indexmap::{IndexMap, IndexSet};
use log::{debug, warn};
use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::io::{BufReader, Read, Seek, SeekFrom};
use std::path::Path;

use crate::models::{
    ApiDocumentation, Endpoint, Example, OpenApiSpec, Parameter, Response, Schema, Service,
};
use crate::utils::{
    extract_security_schemes, extract_servers, resolve_parameter_ref, resolve_path_item_ref,
    resolve_request_body_ref, resolve_response_ref,
};

/// Parses an OpenAPI 2.0/3.0 JSON file into the spec-version-agnostic
/// [`ApiDocumentation`] intermediate representation. On deserialization
/// failure, re-parses as generic JSON to produce a targeted error message.
pub fn parse_openapi<P: AsRef<Path>>(path: P) -> Result<ApiDocumentation> {
    let path_ref = path.as_ref();
    let file = File::open(path_ref).context("Failed to open OpenAPI file")?;
    let mut reader = BufReader::new(file);

    // First, try to parse as OpenAPI spec
    match serde_json::from_reader(&mut reader) as Result<OpenApiSpec, _> {
        Ok(spec) => {
            // Validate the parsed spec
            validate_openapi(&spec, path_ref)?;

            // Serialize the spec to JSON once so `$ref` resolution can navigate
            // it without re-serializing the (potentially multi-MB) spec per ref.
            let spec_json = serde_json::to_value(&spec)
                .context("Failed to serialize OpenAPI spec for reference resolution")?;

            // Extract services (ref-aware: tags inside `$ref` path items count too)
            let services = extract_services(&spec, &spec_json);
            debug!("Extracted {} services", services.len());

            // Extract servers information
            let servers = extract_servers(&spec);
            debug!("Extracted {} server URLs", servers.len());

            // Extract security schemes
            let security_schemes = extract_security_schemes(&spec);
            debug!("Extracted {} security schemes", security_schemes.len());

            let endpoints = extract_endpoints(&spec, &spec_json, &services);
            debug!("Extracted {} endpoints", endpoints.len());
            let schemas = extract_schemas(&spec);
            debug!("Extracted {} reusable schemas", schemas.len());
            let examples = extract_examples(&spec);
            debug!("Extracted {} reusable examples", examples.len());

            Ok(ApiDocumentation {
                title: spec.info.title,
                version: spec.info.version,
                description: spec.info.description,
                services,
                endpoints,
                servers,
                security_schemes,
                schemas,
                examples,
            })
        }
        Err(err) => {
            // Rewind the file to try other parsing methods
            reader.seek(SeekFrom::Start(0))?;

            // Read the file content for better error analysis
            let mut content = String::new();
            reader.read_to_string(&mut content)?;

            // Try to parse as generic JSON to provide better error messages
            match serde_json::from_str::<serde_json::Value>(&content) {
                Ok(json) => {
                    // Check for common issues
                    if !json.is_object() {
                        return Err(anyhow::anyhow!("Root element is not a JSON object"));
                    }

                    let obj = json.as_object().unwrap();

                    if !obj.contains_key("swagger") && !obj.contains_key("openapi") {
                        return Err(anyhow::anyhow!(
                            "Missing 'swagger' or 'openapi' field - not a valid OpenAPI specification"
                        ));
                    }

                    if !obj.contains_key("paths") {
                        return Err(anyhow::anyhow!(
                            "Missing 'paths' field - not a valid OpenAPI specification"
                        ));
                    }

                    if !obj.contains_key("info") {
                        return Err(anyhow::anyhow!(
                            "Missing 'info' field - not a valid OpenAPI specification"
                        ));
                    }

                    // If we got here, there's a structural issue with the spec
                    Err(anyhow::anyhow!(
                        "Invalid OpenAPI specification structure: {}",
                        err
                    ))
                }
                Err(_) => {
                    // Not even valid JSON
                    Err(anyhow::anyhow!("File is not valid JSON: {}", err))
                }
            }
        }
    }
}

/// Logs warnings for missing-but-tolerated spec fields (version, title, paths).
fn validate_openapi(spec: &OpenApiSpec, path: &Path) -> Result<()> {
    // Log the OpenAPI version
    if let Some(version) = &spec.spec_version {
        debug!("OpenAPI specification version: {}", version);
    } else {
        warn!(
            "OpenAPI specification version not found in {}, continuing anyway",
            path.display()
        );
    }

    // Check for required fields
    if spec.info.title.is_empty() {
        warn!("OpenAPI specification is missing a title");
    }

    if spec.info.version.is_empty() {
        warn!("OpenAPI specification is missing a version");
    }

    if spec.paths.is_empty() {
        warn!("OpenAPI specification has no paths defined");
    }

    Ok(())
}

/// Derives "services" from spec-level tags, falling back to per-operation
/// tags, then to a single default `"API"` service.
fn extract_services(spec: &OpenApiSpec, spec_json: &serde_json::Value) -> Vec<Service> {
    let mut services = Vec::new();
    // Names already added, so declared tags and operation tags don't duplicate;
    // first-appearance order keeps output deterministic.
    let mut seen: IndexSet<String> = IndexSet::new();

    // Declared tags first, preserving their descriptions and order.
    if let Some(tags) = &spec.tags {
        for tag in tags {
            if seen.insert(tag.name.clone()) {
                services.push(Service {
                    name: tag.name.clone(),
                    description: tag.description.clone(),
                });
            }
        }
    }

    // Union with every tag actually used by an operation — including operations
    // inside `$ref` path items — so an operation tagged with an undeclared tag
    // gets its own service instead of being silently reassigned to the first one.
    for (_, path_item) in &spec.paths {
        let resolved_path_item;
        let path_item = if path_item.reference.is_some() {
            match resolve_path_item_ref(spec_json, path_item) {
                Some(item) => {
                    resolved_path_item = item;
                    &resolved_path_item
                }
                None => continue,
            }
        } else {
            path_item
        };

        for op in path_item
            .operations()
            .into_iter()
            .filter_map(|(_, op)| op.as_ref())
        {
            if let Some(tags) = &op.tags {
                for tag in tags {
                    if seen.insert(tag.clone()) {
                        services.push(Service {
                            name: tag.clone(),
                            description: None,
                        });
                    }
                }
            }
        }
    }

    // Fall back to a single default service if the spec declares no tags at all.
    if services.is_empty() {
        services.push(Service {
            name: "API".to_string(),
            description: None,
        });
    }

    services
}

/// The service an endpoint is attributed to when its operation declares no tags
/// at all: the first declared service, or `"API"` if there are none.
fn default_service(services: &[Service]) -> String {
    services
        .first()
        .map(|s| s.name.clone())
        .unwrap_or_else(|| "API".to_string())
}

/// De-duplicates parameters on `(name, in)`, keeping the last occurrence so an
/// operation-level parameter overrides a path-level one of the same name and
/// location (OpenAPI's override rule). First-seen position is preserved.
fn dedup_parameters(parameters: Vec<Parameter>) -> Vec<Parameter> {
    let mut by_key: IndexMap<(String, String), Parameter> = IndexMap::new();
    for parameter in parameters {
        let key = (parameter.name.clone(), parameter.parameter_in.clone());
        by_key.insert(key, parameter);
    }
    by_key.into_values().collect()
}

/// Flattens every operation under `paths` into an [`Endpoint`], merging
/// path-level and operation-level parameters, resolving `$ref`s, and
/// representing an OpenAPI 3.0 `requestBody` as a synthetic `body` parameter.
fn extract_endpoints(
    spec: &OpenApiSpec,
    spec_json: &serde_json::Value,
    services: &[Service],
) -> Vec<Endpoint> {
    let mut endpoints = Vec::new();

    // A map of service names to ensure all endpoints are associated with valid services
    let service_map: HashSet<String> = services.iter().map(|s| s.name.clone()).collect();

    for (path, path_item) in &spec.paths {
        // A path item may itself be a `$ref`; resolve it (warn + skip when it
        // can't be resolved) so its operations aren't silently dropped.
        let resolved_path_item;
        let path_item = if path_item.reference.is_some() {
            match resolve_path_item_ref(spec_json, path_item) {
                Some(item) => {
                    resolved_path_item = item;
                    &resolved_path_item
                }
                None => {
                    warn!("Unresolved $ref for path '{}'; skipping", path);
                    continue;
                }
            }
        } else {
            path_item
        };

        // Get parameters defined at the path level and resolve any references
        let path_parameters = path_item
            .parameters
            .as_ref()
            .map(|params| {
                params
                    .iter()
                    .filter_map(|p| resolve_parameter_ref(spec_json, p))
                    .collect::<Vec<_>>()
            })
            .unwrap_or_default();

        for (method, operation_opt) in path_item.operations() {
            if let Some(operation) = operation_opt {
                // Service tags filtered to known services, falling back to the
                // default service when an operation has none (or only unknown ones).
                let service_tags = operation
                    .tags
                    .as_ref()
                    .map(|tags| {
                        tags.iter()
                            .filter(|tag| service_map.contains(*tag))
                            .cloned()
                            .collect::<Vec<_>>()
                    })
                    .filter(|filtered| !filtered.is_empty())
                    .unwrap_or_else(|| vec![default_service(services)]);

                // Combine path-level and operation-level parameters with reference resolution
                let mut parameters = path_parameters.clone();

                if let Some(op_params) = &operation.parameters {
                    for param in op_params {
                        if let Some(resolved_param) = resolve_parameter_ref(spec_json, param) {
                            parameters.push(resolved_param);
                        }
                    }
                }

                // De-duplicate on (name, in): an operation-level parameter
                // overrides a path-level one with the same name and location.
                let mut parameters = dedup_parameters(parameters);

                // Handle request body as a parameter (for OpenAPI 3.0).
                // Bodies are optional unless the spec says required: true.
                if let Some(req_body) = &operation.request_body {
                    // A `requestBody` may be a `$ref`; resolve it before reading
                    // its content, otherwise the synthetic body is dropped.
                    let req_body = resolve_request_body_ref(spec_json, req_body)
                        .unwrap_or_else(|| req_body.clone());
                    if let Some((_, media_type)) = req_body.content.first() {
                        parameters.push(Parameter {
                            reference: None,
                            name: "requestBody".to_string(),
                            description: req_body.description.clone(),
                            parameter_in: "body".to_string(),
                            required: Some(req_body.required.unwrap_or(false)),
                            schema: media_type.schema.clone(),
                            // Ferry the request body's examples through so the
                            // generator can render them at `--detail full`.
                            example: media_type.example.clone(),
                            examples: media_type.examples.clone(),
                            extensions: HashMap::new(),
                        });
                    }
                }

                // Resolve references in responses
                let resolved_responses: IndexMap<String, Response> = operation
                    .responses
                    .iter()
                    .map(|(status_code, response)| {
                        let resolved = resolve_response_ref(spec_json, response)
                            .unwrap_or_else(|| response.clone());
                        (status_code.clone(), resolved)
                    })
                    .collect();

                endpoints.push(Endpoint {
                    path: path.clone(),
                    method: method.to_uppercase(),
                    services: service_tags,
                    summary: operation.summary.clone(),
                    description: operation.description.clone(),
                    operation_id: operation.operation_id.clone(),
                    parameters,
                    responses: resolved_responses,
                    deprecated: operation.deprecated.unwrap_or(false),
                });
            }
        }
    }

    endpoints
}

/// Collects reusable schemas from OpenAPI 3 `components.schemas` and
/// OpenAPI 2 `definitions` into a deterministic registry.
fn extract_schemas(spec: &OpenApiSpec) -> IndexMap<String, Schema> {
    let mut schemas = IndexMap::new();

    if let Some(components) = &spec.components {
        if let Some(component_schemas) = &components.schemas {
            for (name, schema) in component_schemas {
                schemas.insert(name.clone(), schema.clone());
            }
        }
    }

    if let Some(definitions) = spec
        .extensions
        .get("definitions")
        .and_then(|v| v.as_object())
    {
        for (name, raw_schema) in definitions {
            if schemas.contains_key(name) {
                continue;
            }

            match serde_json::from_value::<Schema>(raw_schema.clone()) {
                Ok(schema) => {
                    schemas.insert(name.clone(), schema);
                }
                Err(err) => {
                    warn!(
                        "Skipping definition '{}': failed to parse schema: {}",
                        name, err
                    );
                }
            }
        }
    }

    schemas
}

/// Collects reusable examples from OpenAPI 3 `components.examples` into a
/// deterministic registry, so media-type `examples` entries that are `$ref`s
/// (`#/components/examples/...`) can be resolved during rendering.
fn extract_examples(spec: &OpenApiSpec) -> IndexMap<String, Example> {
    let mut examples = IndexMap::new();

    if let Some(components) = &spec.components {
        if let Some(component_examples) = &components.examples {
            for (name, example) in component_examples {
                examples.insert(name.clone(), example.clone());
            }
        }
    }

    examples
}