fraiseql-cli 2.3.2

CLI tools for FraiseQL v2 - Schema compilation and development utilities
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
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
//! Schema dependency graph command
//!
//! Analyzes and exports schema type dependencies in multiple formats.
//!
//! Usage: fraiseql dependency-graph <schema.compiled.json> [--format=json|dot|mermaid|d2|console]

use std::{fmt::Display, fs, str::FromStr};

use anyhow::Result;
use fraiseql_core::schema::{CompiledSchema, CyclePath, SchemaDependencyGraph};
use serde::Serialize;
use serde_json::Value;

use crate::output::CommandResult;

/// Export format for dependency graph
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum GraphFormat {
    /// JSON format (machine-readable, default)
    #[default]
    Json,
    /// DOT format (Graphviz)
    Dot,
    /// Mermaid format (documentation/markdown)
    Mermaid,
    /// D2 format (modern diagram language)
    D2,
    /// Console format (human-readable text)
    Console,
}

impl FromStr for GraphFormat {
    type Err = String;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "json" => Ok(GraphFormat::Json),
            "dot" | "graphviz" => Ok(GraphFormat::Dot),
            "mermaid" | "md" => Ok(GraphFormat::Mermaid),
            "d2" => Ok(GraphFormat::D2),
            "console" | "text" | "txt" => Ok(GraphFormat::Console),
            other => Err(format!(
                "Unknown format: '{other}'. Valid formats: json, dot, mermaid, d2, console"
            )),
        }
    }
}

impl Display for GraphFormat {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            GraphFormat::Json => write!(f, "json"),
            GraphFormat::Dot => write!(f, "dot"),
            GraphFormat::Mermaid => write!(f, "mermaid"),
            GraphFormat::D2 => write!(f, "d2"),
            GraphFormat::Console => write!(f, "console"),
        }
    }
}

/// Serializable representation of the dependency graph
#[derive(Debug, Serialize)]
pub struct DependencyGraphOutput {
    /// Total number of types in the schema
    pub type_count: usize,

    /// All nodes (types) in the graph
    pub nodes: Vec<GraphNode>,

    /// All edges (dependencies) in the graph
    pub edges: Vec<GraphEdge>,

    /// Circular dependencies detected (empty if none)
    pub cycles: Vec<CycleInfo>,

    /// Types with no incoming references (orphaned)
    pub unused_types: Vec<String>,

    /// Summary statistics
    pub stats: GraphStats,
}

/// A node in the dependency graph
#[derive(Debug, Serialize)]
pub struct GraphNode {
    /// Type name
    pub name: String,

    /// Number of types this type depends on
    pub dependency_count: usize,

    /// Number of types that depend on this type
    pub dependent_count: usize,

    /// Whether this is a root type (Query, Mutation, Subscription)
    pub is_root: bool,
}

/// An edge in the dependency graph
#[derive(Debug, Serialize)]
pub struct GraphEdge {
    /// Source type (the type that has the dependency)
    pub from: String,

    /// Target type (the type being depended on)
    pub to: String,
}

/// Information about a detected cycle
#[derive(Debug, Serialize)]
pub struct CycleInfo {
    /// Types involved in the cycle
    pub types: Vec<String>,

    /// Human-readable path string
    pub path: String,

    /// Whether this is a self-reference
    pub is_self_reference: bool,
}

impl From<&CyclePath> for CycleInfo {
    fn from(cycle: &CyclePath) -> Self {
        Self {
            types:             cycle.nodes.clone(),
            path:              cycle.path_string(),
            is_self_reference: cycle.is_self_reference(),
        }
    }
}

/// Statistics about the dependency graph
#[derive(Debug, Serialize)]
pub struct GraphStats {
    /// Total number of types
    pub total_types: usize,

    /// Total number of edges (dependencies)
    pub total_edges: usize,

    /// Number of circular dependencies
    pub cycle_count: usize,

    /// Number of unused types
    pub unused_count: usize,

    /// Average dependencies per type
    pub avg_dependencies: f64,

    /// Maximum dependency depth from any root
    pub max_depth: usize,

    /// Types with the most dependents (most "important")
    pub most_depended_on: Vec<String>,
}

/// Run the dependency graph command
///
/// # Errors
///
/// Returns an error if the schema file cannot be read or cannot be deserialized
/// as a `CompiledSchema`. Also propagates JSON serialization errors for the
/// selected output format.
pub fn run(schema_path: &str, format: GraphFormat) -> Result<CommandResult> {
    // Load and parse schema
    let schema_content = fs::read_to_string(schema_path)?;
    let schema: CompiledSchema = serde_json::from_str(&schema_content)?;

    // Build dependency graph
    let graph = SchemaDependencyGraph::build(&schema);

    // Analyze the graph
    let cycles = graph.find_cycles();
    let unused = graph.find_unused();

    // Build output structure
    let output = build_output(&graph, &cycles, &unused);

    // Check for cycles (these are errors)
    let warnings: Vec<String> = unused
        .iter()
        .map(|t| format!("Unused type: '{t}' has no incoming references"))
        .collect();

    // Format output based on requested format
    let data = match format {
        GraphFormat::Json => serde_json::to_value(&output)?,
        GraphFormat::Dot => Value::String(to_dot(&output)),
        GraphFormat::Mermaid => Value::String(to_mermaid(&output)),
        GraphFormat::D2 => Value::String(to_d2(&output)),
        GraphFormat::Console => Value::String(to_console(&output)),
    };

    // If cycles exist, return validation failure
    if !cycles.is_empty() {
        let errors: Vec<String> = cycles
            .iter()
            .map(|c| format!("Circular dependency: {}", c.path_string()))
            .collect();

        // Include the graph data in the error response
        return Ok(CommandResult {
            status: "validation-failed".to_string(),
            command: "dependency-graph".to_string(),
            data: Some(data),
            message: Some(format!("Schema has {} circular dependencies", cycles.len())),
            code: Some("CIRCULAR_DEPENDENCY".to_string()),
            errors,
            warnings,
        });
    }

    // Success - return graph with any warnings
    if warnings.is_empty() {
        Ok(CommandResult::success("dependency-graph", data))
    } else {
        Ok(CommandResult::success_with_warnings("dependency-graph", data, warnings))
    }
}

/// Build the output structure from the dependency graph
fn build_output(
    graph: &SchemaDependencyGraph,
    cycles: &[CyclePath],
    unused: &[String],
) -> DependencyGraphOutput {
    let all_types = graph.all_types();
    let root_types = ["Query", "Mutation", "Subscription"];

    // Build nodes
    let mut nodes: Vec<GraphNode> = all_types
        .iter()
        .map(|name| GraphNode {
            name:             name.clone(),
            dependency_count: graph.dependencies_of(name).len(),
            dependent_count:  graph.dependents_of(name).len(),
            is_root:          root_types.contains(&name.as_str()),
        })
        .collect();

    // Sort by dependent count (most depended on first)
    nodes.sort_by_key(|n| std::cmp::Reverse(n.dependent_count));

    // Build edges
    let mut edges: Vec<GraphEdge> = Vec::new();
    for type_name in &all_types {
        for dep in graph.dependencies_of(type_name) {
            edges.push(GraphEdge {
                from: type_name.clone(),
                to:   dep,
            });
        }
    }

    // Sort edges for consistent output
    edges.sort_by(|a, b| (&a.from, &a.to).cmp(&(&b.from, &b.to)));

    // Build cycle info
    let cycle_info: Vec<CycleInfo> = cycles.iter().map(CycleInfo::from).collect();

    // Calculate stats
    let total_deps: usize = nodes.iter().map(|n| n.dependency_count).sum();
    #[allow(clippy::cast_precision_loss)]
    // Reason: precision loss acceptable for metric/ratio calculations
    let avg_deps = if nodes.is_empty() {
        0.0
    } else {
        total_deps as f64 / nodes.len() as f64
    };

    // Find most depended on types (top 5)
    let most_depended: Vec<String> = nodes
        .iter()
        .filter(|n| n.dependent_count > 0 && !n.is_root)
        .take(5)
        .map(|n| n.name.clone())
        .collect();

    // Calculate max depth (BFS from roots)
    let max_depth = calculate_max_depth(graph, &root_types);

    let stats = GraphStats {
        total_types: nodes.len(),
        total_edges: edges.len(),
        cycle_count: cycles.len(),
        unused_count: unused.len(),
        avg_dependencies: (avg_deps * 100.0).round() / 100.0,
        max_depth,
        most_depended_on: most_depended,
    };

    DependencyGraphOutput {
        type_count: nodes.len(),
        nodes,
        edges,
        cycles: cycle_info,
        unused_types: unused.to_vec(),
        stats,
    }
}

/// Calculate maximum depth from root types using BFS
fn calculate_max_depth(graph: &SchemaDependencyGraph, root_types: &[&str]) -> usize {
    use std::collections::{HashSet, VecDeque};

    let mut max_depth = 0;
    let mut visited = HashSet::new();
    let mut queue = VecDeque::new();

    // Start from each root that exists
    for &root in root_types {
        if graph.has_type(root) {
            queue.push_back((root.to_string(), 0));
            visited.insert(root.to_string());
        }
    }

    while let Some((type_name, depth)) = queue.pop_front() {
        max_depth = max_depth.max(depth);

        for dep in graph.dependencies_of(&type_name) {
            if !visited.contains(&dep) {
                visited.insert(dep.clone());
                queue.push_back((dep, depth + 1));
            }
        }
    }

    max_depth
}

/// Convert dependency graph to DOT format (Graphviz)
pub(crate) fn to_dot(output: &DependencyGraphOutput) -> String {
    use std::fmt::Write;

    let mut dot = String::from("digraph schema_dependencies {\n");
    dot.push_str("    rankdir=LR;\n");
    dot.push_str("    node [shape=box, style=rounded];\n\n");

    // Add legend comment
    dot.push_str("    // Root types (Query, Mutation, Subscription)\n");

    // Add nodes with styling
    for node in &output.nodes {
        let style = if node.is_root {
            "style=\"rounded,bold\", color=blue"
        } else if output.unused_types.contains(&node.name) {
            "style=\"rounded,dashed\", color=gray"
        } else {
            "style=rounded"
        };

        let name = &node.name;
        let deps = node.dependency_count;
        let refs = node.dependent_count;
        let _ = writeln!(
            dot,
            "    \"{name}\" [label=\"{name}\\n(deps: {deps}, refs: {refs})\", {style}];"
        );
    }

    dot.push_str("\n    // Dependencies\n");

    // Add edges
    for edge in &output.edges {
        let from = &edge.from;
        let to = &edge.to;
        let _ = writeln!(dot, "    \"{from}\" -> \"{to}\";");
    }

    // Highlight cycles
    if !output.cycles.is_empty() {
        dot.push_str("\n    // Cycles (highlighted in red)\n");
        for cycle in &output.cycles {
            for i in 0..cycle.types.len() {
                let from = &cycle.types[i];
                let to = &cycle.types[(i + 1) % cycle.types.len()];
                let _ = writeln!(dot, "    \"{from}\" -> \"{to}\" [color=red, penwidth=2];");
            }
        }
    }

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

/// Convert dependency graph to Mermaid format
pub(crate) fn to_mermaid(output: &DependencyGraphOutput) -> String {
    use std::fmt::Write;

    let mut mermaid = String::from("```mermaid\ngraph LR\n");

    // Add subgraph for root types
    mermaid.push_str("    subgraph Roots\n");
    for node in &output.nodes {
        if node.is_root {
            let name = &node.name;
            let _ = writeln!(mermaid, "        {name}[\"{name}\"]");
        }
    }
    mermaid.push_str("    end\n\n");

    // Add other nodes
    for node in &output.nodes {
        if !node.is_root {
            let style = if output.unused_types.contains(&node.name) {
                ":::unused"
            } else {
                ""
            };
            let name = &node.name;
            let _ = writeln!(mermaid, "    {name}[\"{name}\"]{style}");
        }
    }

    mermaid.push('\n');

    // Add edges
    for edge in &output.edges {
        // Check if this edge is part of a cycle
        let is_cycle_edge = output.cycles.iter().any(|c| {
            let types = &c.types;
            for i in 0..types.len() {
                let from = &types[i];
                let to = &types[(i + 1) % types.len()];
                if from == &edge.from && to == &edge.to {
                    return true;
                }
            }
            false
        });

        let from = &edge.from;
        let to = &edge.to;
        if is_cycle_edge {
            let _ = writeln!(mermaid, "    {from} -->|CYCLE| {to}");
        } else {
            let _ = writeln!(mermaid, "    {from} --> {to}");
        }
    }

    // Add styling
    mermaid.push_str("\n    classDef unused fill:#f9f,stroke:#333,stroke-dasharray: 5 5\n");

    mermaid.push_str("```\n");
    mermaid
}

/// Convert dependency graph to D2 format (modern diagram language)
///
/// D2 is a modern diagram scripting language that compiles to SVG.
/// See: https://d2lang.com/
pub(crate) fn to_d2(output: &DependencyGraphOutput) -> String {
    use std::fmt::Write;

    let mut d2 = String::new();

    // Header comment
    d2.push_str("# Schema Dependency Graph\n");
    d2.push_str("# Generated by FraiseQL CLI\n");
    d2.push_str("# Render with: d2 schema.d2 schema.svg\n\n");

    // Global styling
    d2.push_str("direction: right\n\n");

    // Root types container
    let has_roots = output.nodes.iter().any(|n| n.is_root);
    if has_roots {
        d2.push_str("roots: {\n");
        d2.push_str("  label: \"Root Types\"\n");
        d2.push_str("  style.fill: \"#e3f2fd\"\n");
        d2.push_str("  style.stroke: \"#1976d2\"\n\n");
        for node in &output.nodes {
            if node.is_root {
                let name = &node.name;
                let deps = node.dependency_count;
                let refs = node.dependent_count;
                let _ = writeln!(d2, "  {name}: \"{name}\\n(deps: {deps}, refs: {refs})\" {{");
                d2.push_str("    style.bold: true\n");
                d2.push_str("    style.fill: \"#bbdefb\"\n");
                d2.push_str("  }\n");
            }
        }
        d2.push_str("}\n\n");
    }

    // Unused types container (if any)
    if !output.unused_types.is_empty() {
        d2.push_str("unused: {\n");
        d2.push_str("  label: \"Unused Types\"\n");
        d2.push_str("  style.fill: \"#fff3e0\"\n");
        d2.push_str("  style.stroke: \"#ff9800\"\n");
        d2.push_str("  style.stroke-dash: 3\n\n");
        for node in &output.nodes {
            if output.unused_types.contains(&node.name) {
                let name = &node.name;
                let _ = writeln!(d2, "  {name}: \"{name}\" {{");
                d2.push_str("    style.fill: \"#ffe0b2\"\n");
                d2.push_str("    style.stroke-dash: 3\n");
                d2.push_str("  }\n");
            }
        }
        d2.push_str("}\n\n");
    }

    // Regular types (not root, not unused)
    for node in &output.nodes {
        if !node.is_root && !output.unused_types.contains(&node.name) {
            let name = &node.name;
            let deps = node.dependency_count;
            let refs = node.dependent_count;
            let _ = writeln!(d2, "{name}: \"{name}\\n(deps: {deps}, refs: {refs})\"");
        }
    }

    d2.push('\n');

    // Edges
    d2.push_str("# Dependencies\n");
    for edge in &output.edges {
        // Check if this edge is part of a cycle
        let is_cycle_edge = output.cycles.iter().any(|c| {
            let types = &c.types;
            for i in 0..types.len() {
                let from = &types[i];
                let to = &types[(i + 1) % types.len()];
                if from == &edge.from && to == &edge.to {
                    return true;
                }
            }
            false
        });

        let from = &edge.from;
        let to = &edge.to;

        // Handle edges from root types (need to reference inside container)
        let from_ref = if output.nodes.iter().any(|n| n.is_root && &n.name == from) {
            format!("roots.{from}")
        } else if output.unused_types.contains(from) {
            format!("unused.{from}")
        } else {
            from.clone()
        };

        let to_ref = if output.nodes.iter().any(|n| n.is_root && &n.name == to) {
            format!("roots.{to}")
        } else if output.unused_types.contains(to) {
            format!("unused.{to}")
        } else {
            to.clone()
        };

        if is_cycle_edge {
            let _ = writeln!(d2, "{from_ref} -> {to_ref}: \"CYCLE\" {{");
            d2.push_str("  style.stroke: \"#d32f2f\"\n");
            d2.push_str("  style.stroke-width: 2\n");
            d2.push_str("}\n");
        } else {
            let _ = writeln!(d2, "{from_ref} -> {to_ref}");
        }
    }

    // Cycle warning comment
    if !output.cycles.is_empty() {
        d2.push_str("\n# WARNING: Circular dependencies detected!\n");
        for cycle in &output.cycles {
            let _ = writeln!(d2, "# Cycle: {}", cycle.path);
        }
    }

    d2
}

/// Convert dependency graph to console (human-readable) format
pub(crate) fn to_console(output: &DependencyGraphOutput) -> String {
    use std::fmt::Write;

    let mut console = String::new();

    // Header
    console.push_str("Schema Dependency Graph Analysis\n");
    console.push_str("================================\n\n");

    // Summary stats
    let _ = writeln!(console, "Total types: {}", output.stats.total_types);
    let _ = writeln!(console, "Total dependencies: {}", output.stats.total_edges);
    let _ =
        writeln!(console, "Average dependencies per type: {:.2}", output.stats.avg_dependencies);
    let _ = writeln!(console, "Maximum depth from roots: {}", output.stats.max_depth);
    console.push('\n');

    // Cycles (errors)
    if !output.cycles.is_empty() {
        let _ = writeln!(console, "CIRCULAR DEPENDENCIES ({}):", output.cycles.len());
        for cycle in &output.cycles {
            let _ = writeln!(console, "  - {}", cycle.path);
        }
        console.push('\n');
    }

    // Unused types (warnings)
    if !output.unused_types.is_empty() {
        let _ = writeln!(console, "UNUSED TYPES ({}):", output.unused_types.len());
        for unused in &output.unused_types {
            let _ = writeln!(console, "  - {unused}");
        }
        console.push('\n');
    }

    // Most depended on types
    if !output.stats.most_depended_on.is_empty() {
        console.push_str("Most referenced types:\n");
        for (i, type_name) in output.stats.most_depended_on.iter().enumerate() {
            let node = output.nodes.iter().find(|n| &n.name == type_name);
            if let Some(node) = node {
                let _ = writeln!(
                    console,
                    "  {}. {type_name} ({} references)",
                    i + 1,
                    node.dependent_count
                );
            }
        }
        console.push('\n');
    }

    // Type details
    console.push_str("Type Details:\n");
    console.push_str("-------------\n");

    for node in &output.nodes {
        let prefix = if node.is_root {
            "[ROOT] "
        } else if output.unused_types.contains(&node.name) {
            "[UNUSED] "
        } else {
            ""
        };

        let _ = writeln!(
            console,
            "{prefix}{}: {} deps, {} refs",
            node.name, node.dependency_count, node.dependent_count
        );
    }

    console
}