a4-cli 0.1.3

CLI tool for generating TypeScript SDKs from Arete stream specifications
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
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
use anyhow::{Context, Result};
use colored::Colorize;
use dialoguer::{theme::ColorfulTheme, Select};
use std::fs;
use std::path::{Path, PathBuf};

use crate::api_client::{ApiClient, RegistryAstResponse};
use crate::config::{discover_ast_files, find_ast_file, to_kebab_case, AreteConfig, DiscoveredAst};
use crate::telemetry;

struct RemoteStackAst {
    name: String,
    stack: String,
    websocket_url: String,
    ast_payload: serde_json::Value,
    sdk_name: String,
}

enum ResolvedStackSource {
    Local(DiscoveredAst),
    Remote(RemoteStackAst),
}

#[derive(Clone, Copy)]
enum SdkTarget {
    TypeScript,
    Rust,
}

impl ResolvedStackSource {
    fn stack_id(&self) -> &str {
        match self {
            Self::Local(ast) => ast.stack_id.as_str(),
            Self::Remote(stack) => stack.stack.as_str(),
        }
    }

    fn sdk_name(&self) -> &str {
        match self {
            Self::Local(ast) => ast.stack_name.as_str(),
            Self::Remote(stack) => stack.sdk_name.as_str(),
        }
    }

    fn default_url(&self) -> Option<String> {
        match self {
            Self::Local(_) => None,
            Self::Remote(stack) => Some(stack.websocket_url.clone()),
        }
    }

    fn print_source_details(&self) {
        match self {
            Self::Local(ast) => {
                println!("  Path: {}", ast.path.display());
                if !ast.program_ids.is_empty() {
                    println!("  Program IDs: {}", ast.program_ids.join(", "));
                }
            }
            Self::Remote(stack) => {
                println!("  Hosted Stack: {}", stack.stack.cyan());
                println!("  Stack Name: {}", stack.name);
            }
        }
    }

    fn load_stack_spec(&self) -> Result<arete_interpreter::ast::SerializableStackSpec> {
        match self {
            Self::Local(ast) => load_stack_spec_from_file(ast),
            Self::Remote(stack) => load_stack_spec_from_value(
                &stack.ast_payload,
                &format!("hosted stack '{}'", stack.stack),
            ),
        }
    }
}

pub fn list(config_path: &str) -> Result<()> {
    let config = AreteConfig::load_optional(config_path)?;

    let discovered = discover_ast_files(None)?;

    let has_config_stacks = config
        .as_ref()
        .map(|c| !c.stacks.is_empty())
        .unwrap_or(false);

    if !has_config_stacks && discovered.is_empty() {
        println!("{}", "No stacks found.".yellow());
        println!();
        println!("To add stacks:");
        println!("  1. Build your stack crate to generate .arete/*.stack.json files");
        println!("  2. Run {} to create a configuration", "a4 init".cyan());
        return Ok(());
    }

    println!("{} Available stacks:\n", "".blue().bold());

    if let Some(ref cfg) = config {
        for stack in &cfg.stacks {
            let name = stack.name.as_deref().unwrap_or(&stack.stack);
            println!("  {}", name.green().bold());
            println!("    Stack: {}", stack.stack);

            if let Some(desc) = &stack.description {
                println!("    Description: {}", desc);
            }

            if let Some(url) = &stack.url {
                println!("    URL: {}", url.cyan());
            }

            let ts_output = cfg.get_typescript_output_path(name, Some(stack), None);
            let rust_output = cfg.get_rust_output_path(name, Some(stack), None);
            println!("    TypeScript: {}", ts_output.display());
            println!("    Rust: {}", rust_output.display());
            println!();
        }
    }

    let config_asts: std::collections::HashSet<_> = config
        .as_ref()
        .map(|c| c.stacks.iter().map(|s| s.stack.clone()).collect())
        .unwrap_or_default();

    for ast in discovered {
        if !config_asts.contains(&ast.stack_id) {
            println!("  {} {}", "".dimmed(), ast.stack_name.green().bold());
            println!("    Stack: {}", ast.stack_id);
            println!("    Path: {}", ast.path.display());
            if !ast.program_ids.is_empty() {
                println!("    Program IDs: {}", ast.program_ids.join(", "));
            }
            println!("    {}", "(auto-discovered, not in config)".dimmed());
            println!();
        }
    }

    println!(
        "Use {} to generate SDK",
        "a4 sdk create <stack-name> --ts".cyan()
    );

    Ok(())
}

#[allow(clippy::too_many_arguments)]
pub fn create(
    config_path: &str,
    stack_name: &str,
    ts: bool,
    rust: bool,
    output_override: Option<String>,
    package_name_override: Option<String>,
    crate_name_override: Option<String>,
    module_flag: bool,
    url_override: Option<String>,
) -> Result<()> {
    match select_sdk_target(ts, rust, "Generate which SDK?")? {
        SdkTarget::TypeScript => create_typescript(
            config_path,
            stack_name,
            output_override,
            package_name_override,
            url_override,
        ),
        SdkTarget::Rust => create_rust(
            config_path,
            stack_name,
            output_override,
            crate_name_override,
            module_flag,
            url_override,
        ),
    }
}

pub fn create_typescript(
    config_path: &str,
    stack_name: &str,
    output_override: Option<String>,
    package_name_override: Option<String>,
    url_override: Option<String>,
) -> Result<()> {
    println!(
        "{} Looking for stack '{}'...",
        "".blue().bold(),
        stack_name
    );

    let config = AreteConfig::load_optional(config_path)?;
    let client = ApiClient::new()?;

    // Get the config file's directory for resolving relative paths
    let config_dir = Path::new(config_path)
        .parent()
        .unwrap_or(Path::new("."))
        .to_path_buf();

    let (source, output_path, package_name, stack_url) = if let Some(ref cfg) = config {
        if let Some(stack_config) = cfg.find_stack(stack_name) {
            let source = resolve_stack_source(&client, &stack_config.stack)?;

            let name = stack_config.name.as_deref().unwrap_or(&stack_config.stack);
            let raw_output =
                cfg.get_typescript_output_path(name, Some(stack_config), output_override.clone());

            // Resolve relative paths relative to the config file's directory
            let output = if raw_output.is_relative() {
                config_dir.join(&raw_output)
            } else {
                raw_output
            };

            let pkg = package_name_override
                .or_else(|| cfg.sdk.as_ref().and_then(|s| s.typescript_package.clone()))
                .unwrap_or_else(|| "@usearete/react".to_string());

            let url = url_override
                .or_else(|| stack_config.url.clone())
                .or_else(|| source.default_url());

            (source, output, pkg, url)
        } else {
            let (source, output, pkg) =
                find_stack_by_name(&client, stack_name, output_override, package_name_override)?;
            let url = url_override.or_else(|| source.default_url());
            (source, output, pkg, url)
        }
    } else {
        let (source, output, pkg) =
            find_stack_by_name(&client, stack_name, output_override, package_name_override)?;
        let url = url_override.or_else(|| source.default_url());
        (source, output, pkg, url)
    };

    println!(
        "{} Found stack: {}",
        "".green().bold(),
        source.stack_id().bold()
    );
    source.print_source_details();
    println!("  Output: {}", output_path.display());
    if let Some(url) = &stack_url {
        println!("  URL: {}", url.cyan());
    } else {
        println!(
            "  URL: {}",
            "(not configured - placeholder will be generated)".dimmed()
        );
    }

    if let Some(parent) = output_path.parent() {
        fs::create_dir_all(parent)
            .with_context(|| format!("Failed to create output directory: {}", parent.display()))?;
    }

    println!("\n{} Generating TypeScript SDK...", "".blue().bold());

    generate_typescript_sdk_from_source(&source, &output_path, &package_name, stack_url)?;

    println!(
        "{} Successfully generated TypeScript SDK!",
        "".green().bold()
    );
    println!("  File: {}", output_path.display().to_string().bold());

    telemetry::record_sdk_generated("typescript");

    Ok(())
}

#[allow(clippy::too_many_arguments)]
pub fn install(
    stack_name: &str,
    ts: bool,
    rust: bool,
    output_override: Option<String>,
    package_name_override: Option<String>,
    crate_name_override: Option<String>,
    module_flag: bool,
    url_override: Option<String>,
) -> Result<()> {
    match select_sdk_target(ts, rust, "Install which SDK?")? {
        SdkTarget::TypeScript => install_typescript(
            stack_name,
            output_override,
            package_name_override,
            url_override,
        ),
        SdkTarget::Rust => install_rust(
            stack_name,
            output_override,
            crate_name_override,
            module_flag,
            url_override,
        ),
    }
}

fn install_typescript(
    stack_name: &str,
    output_override: Option<String>,
    package_name_override: Option<String>,
    url_override: Option<String>,
) -> Result<()> {
    println!(
        "{} Looking up hosted stack '{}'...",
        "".blue().bold(),
        stack_name
    );

    let client = ApiClient::new()?;
    let source = resolve_remote_stack_source(&client, stack_name)?;
    let output_path = output_override
        .map(PathBuf::from)
        .unwrap_or_else(|| PathBuf::from(format!("./generated/{}-stack.ts", source.sdk_name())));
    let package_name = package_name_override.unwrap_or_else(|| "@usearete/react".to_string());
    let stack_url = url_override.or_else(|| source.default_url());

    println!(
        "{} Found hosted stack: {}",
        "".green().bold(),
        source.stack_id().bold()
    );
    source.print_source_details();
    println!("  Output: {}", output_path.display());
    if let Some(url) = &stack_url {
        println!("  URL: {}", url.cyan());
    } else {
        println!(
            "  URL: {}",
            "(not provided by hosted stack - placeholder will be generated)".dimmed()
        );
    }

    if let Some(parent) = output_path.parent() {
        fs::create_dir_all(parent)
            .with_context(|| format!("Failed to create output directory: {}", parent.display()))?;
    }

    println!("\n{} Generating TypeScript SDK...", "".blue().bold());

    generate_typescript_sdk_from_source(&source, &output_path, &package_name, stack_url)?;

    println!(
        "{} Successfully generated TypeScript SDK!",
        "".green().bold()
    );
    println!("  File: {}", output_path.display().to_string().bold());

    telemetry::record_sdk_generated("typescript");

    Ok(())
}

fn install_rust(
    stack_name: &str,
    output_override: Option<String>,
    crate_name_override: Option<String>,
    module_flag: bool,
    url_override: Option<String>,
) -> Result<()> {
    println!(
        "{} Looking up hosted stack '{}'...",
        "".blue().bold(),
        stack_name
    );

    let client = ApiClient::new()?;
    let source = resolve_remote_stack_source(&client, stack_name)?;
    let crate_name = crate_name_override.unwrap_or_else(|| format!("{}-stack", source.sdk_name()));
    let output_dir = output_override
        .map(PathBuf::from)
        .unwrap_or_else(|| PathBuf::from(format!("./generated/{}-stack", source.sdk_name())));
    let stack_url = url_override.or_else(|| source.default_url());

    println!(
        "{} Found hosted stack: {}",
        "".green().bold(),
        source.stack_id().bold()
    );
    source.print_source_details();
    println!("  Output: {}", output_dir.display());
    if module_flag {
        println!("  Mode: module (mod.rs)");
    }
    if let Some(url) = &stack_url {
        println!("  URL: {}", url.cyan());
    } else {
        println!(
            "  URL: {}",
            "(not provided by hosted stack - placeholder will be generated)".dimmed()
        );
    }

    println!("\n{} Generating Rust SDK...", "".blue().bold());

    let stack_spec = source.load_stack_spec()?;

    println!(
        "{} {} entities in stack",
        "".blue().bold(),
        stack_spec.entities.len()
    );

    let rust_config = arete_interpreter::rust::RustStackConfig {
        crate_name: crate_name.clone(),
        sdk_version: "0.2".to_string(),
        module_mode: module_flag,
        url: stack_url,
    };

    let output = arete_interpreter::rust::compile_stack_spec(stack_spec, Some(rust_config))
        .map_err(|e| anyhow::anyhow!("Failed to compile Rust: {}", e))?;

    if module_flag {
        arete_interpreter::rust::write_rust_module(&output, &output_dir)
            .with_context(|| format!("Failed to write Rust module to {}", output_dir.display()))?;

        println!("{} Successfully generated Rust module!", "".green().bold());
        println!("  Module: {}", output_dir.display().to_string().bold());
        println!("\n  Add to your lib.rs:");
        let module_name = output_dir
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("module");
        println!("    pub mod {};", module_name.cyan());
    } else {
        arete_interpreter::rust::write_rust_crate(&output, &output_dir)
            .with_context(|| format!("Failed to write Rust crate to {}", output_dir.display()))?;

        println!("{} Successfully generated Rust SDK!", "".green().bold());
        println!("  Crate: {}", output_dir.display().to_string().bold());
        println!("\n  Add to your Cargo.toml:");
        println!(
            "    {} = {{ path = \"{}\" }}",
            crate_name.cyan(),
            output_dir.display()
        );
    }

    telemetry::record_sdk_generated("rust");

    Ok(())
}

fn select_sdk_target(ts: bool, rust: bool, prompt: &str) -> Result<SdkTarget> {
    match (ts, rust) {
        (true, false) => Ok(SdkTarget::TypeScript),
        (false, true) => Ok(SdkTarget::Rust),
        (false, false) => {
            let theme = ColorfulTheme::default();
            let items = ["TypeScript", "Rust"];
            let selection = Select::with_theme(&theme)
                .with_prompt(prompt)
                .items(&items)
                .default(0)
                .interact()
                .context("Failed to select SDK language")?;

            Ok(match selection {
                0 => SdkTarget::TypeScript,
                1 => SdkTarget::Rust,
                _ => unreachable!(),
            })
        }
        (true, true) => Err(anyhow::anyhow!(
            "Cannot specify both --ts and --rust. Choose one."
        )),
    }
}

fn find_stack_by_name(
    client: &ApiClient,
    stack_name: &str,
    output_override: Option<String>,
    package_name_override: Option<String>,
) -> Result<(ResolvedStackSource, PathBuf, String)> {
    let source = resolve_stack_source(client, stack_name)?;

    let output = output_override
        .map(|p| p.into())
        .unwrap_or_else(|| PathBuf::from(format!("./generated/{}-stack.ts", source.sdk_name())));

    let pkg = package_name_override.unwrap_or_else(|| "@usearete/react".to_string());

    Ok((source, output, pkg))
}

fn generate_typescript_sdk_from_source(
    source: &ResolvedStackSource,
    output_path: &Path,
    package_name: &str,
    url: Option<String>,
) -> Result<()> {
    let stack_spec = source.load_stack_spec()?;

    let entity_count = stack_spec.entities.len();
    let total_views: usize = stack_spec.entities.iter().map(|e| e.views.len()).sum();

    println!(
        "{} {} entities, {} views total",
        "".blue().bold(),
        entity_count,
        total_views,
    );
    for entity in &stack_spec.entities {
        let view_ids: Vec<&str> = entity.views.iter().map(|v| v.id.as_str()).collect();
        println!(
            "   Entity: {} (views: {})",
            entity.state_name,
            view_ids.join(", ")
        );
    }

    println!("{} Compiling TypeScript from stack...", "".blue().bold());

    let config = arete_interpreter::typescript::TypeScriptStackConfig {
        package_name: package_name.to_string(),
        generate_helpers: true,
        export_const_name: "STACK".to_string(),
        url,
    };

    let output = arete_interpreter::typescript::compile_stack_spec(stack_spec, Some(config))
        .map_err(|e| anyhow::anyhow!("Failed to compile TypeScript: {}", e))?;

    arete_interpreter::typescript::write_stack_typescript_to_file(&output, output_path)
        .with_context(|| format!("Failed to write TypeScript to {}", output_path.display()))?;

    Ok(())
}

fn load_stack_spec_from_file(
    ast: &DiscoveredAst,
) -> Result<arete_interpreter::ast::SerializableStackSpec> {
    let ast_json = fs::read_to_string(&ast.path)
        .with_context(|| format!("Failed to read stack file: {}", ast.path.display()))?;

    load_stack_spec_from_json(&ast_json, &ast.path.display().to_string())
}

fn load_stack_spec_from_value(
    ast: &serde_json::Value,
    source_name: &str,
) -> Result<arete_interpreter::ast::SerializableStackSpec> {
    let ast_json = serde_json::to_string(ast)
        .with_context(|| format!("Failed to serialize stack AST from {}", source_name))?;

    load_stack_spec_from_json(&ast_json, source_name)
}

fn load_stack_spec_from_json(
    ast_json: &str,
    source_name: &str,
) -> Result<arete_interpreter::ast::SerializableStackSpec> {
    // Use versioned loader for automatic version detection and migration
    let stack_spec = arete_interpreter::versioned::load_stack_spec(ast_json)
        .with_context(|| format!("Failed to load stack AST from {}", source_name))?;

    if stack_spec.entities.is_empty() {
        return Err(anyhow::anyhow!(
            "Stack AST contains no entities: {}",
            source_name
        ));
    }

    Ok(stack_spec)
}

pub fn create_rust(
    config_path: &str,
    stack_name: &str,
    output_override: Option<String>,
    crate_name_override: Option<String>,
    module_flag: bool,
    url_override: Option<String>,
) -> Result<()> {
    println!(
        "{} Looking for stack '{}'...",
        "".blue().bold(),
        stack_name
    );

    let config = AreteConfig::load_optional(config_path)?;
    let client = ApiClient::new()?;

    let config_dir = Path::new(config_path)
        .parent()
        .unwrap_or(Path::new("."))
        .to_path_buf();

    let stack_config = config.as_ref().and_then(|c| c.find_stack(stack_name));

    let as_module = module_flag
        || stack_config.and_then(|s| s.rust_module).unwrap_or_else(|| {
            config
                .as_ref()
                .and_then(|c| c.sdk.as_ref())
                .map(|s| s.rust_module_mode)
                .unwrap_or(false)
        });

    let (source, raw_output_dir, crate_name) = find_stack_for_rust(
        &client,
        stack_name,
        config.as_ref(),
        output_override,
        crate_name_override,
    )?;

    let stack_url = url_override
        .or_else(|| stack_config.and_then(|s| s.url.clone()))
        .or_else(|| source.default_url());

    let output_dir = if raw_output_dir.is_relative() {
        config_dir.join(&raw_output_dir)
    } else {
        raw_output_dir
    };

    println!(
        "{} Found stack: {}",
        "".green().bold(),
        source.stack_id().bold()
    );
    source.print_source_details();
    println!("  Output: {}", output_dir.display());
    if as_module {
        println!("  Mode: module (mod.rs)");
    }
    if let Some(url) = &stack_url {
        println!("  URL: {}", url.cyan());
    } else {
        println!(
            "  URL: {}",
            "(not configured - placeholder will be generated)".dimmed()
        );
    }

    println!("\n{} Generating Rust SDK...", "".blue().bold());

    let stack_spec = source.load_stack_spec()?;

    println!(
        "{} {} entities in stack",
        "".blue().bold(),
        stack_spec.entities.len()
    );

    let rust_config = arete_interpreter::rust::RustStackConfig {
        crate_name: crate_name.clone(),
        sdk_version: "0.2".to_string(),
        module_mode: as_module,
        url: stack_url,
    };

    let output = arete_interpreter::rust::compile_stack_spec(stack_spec, Some(rust_config))
        .map_err(|e| anyhow::anyhow!("Failed to compile Rust: {}", e))?;

    if as_module {
        arete_interpreter::rust::write_rust_module(&output, &output_dir)
            .with_context(|| format!("Failed to write Rust module to {}", output_dir.display()))?;

        println!("{} Successfully generated Rust module!", "".green().bold());
        println!("  Module: {}", output_dir.display().to_string().bold());
        println!("\n  Add to your lib.rs:");
        let module_name = output_dir
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("module");
        println!("    pub mod {};", module_name.cyan());
    } else {
        arete_interpreter::rust::write_rust_crate(&output, &output_dir)
            .with_context(|| format!("Failed to write Rust crate to {}", output_dir.display()))?;

        println!("{} Successfully generated Rust SDK!", "".green().bold());
        println!("  Crate: {}", output_dir.display().to_string().bold());
        println!("\n  Add to your Cargo.toml:");
        println!(
            "    {} = {{ path = \"{}\" }}",
            crate_name.cyan(),
            output_dir.display()
        );
    }

    telemetry::record_sdk_generated("rust");

    Ok(())
}

fn find_stack_for_rust(
    client: &ApiClient,
    stack_name: &str,
    config: Option<&AreteConfig>,
    output_override: Option<String>,
    crate_name_override: Option<String>,
) -> Result<(ResolvedStackSource, PathBuf, String)> {
    let (source, stack_config) = if let Some(cfg) = config {
        if let Some(stack_config) = cfg.find_stack(stack_name) {
            let source = resolve_stack_source(client, &stack_config.stack)?;
            (source, Some(stack_config))
        } else {
            let source = resolve_stack_source(client, stack_name)?;
            (source, None)
        }
    } else {
        let source = resolve_stack_source(client, stack_name)?;
        (source, None)
    };

    let crate_name = crate_name_override.unwrap_or_else(|| format!("{}-stack", source.sdk_name()));

    let crate_dir = if let Some(cfg) = config {
        cfg.get_rust_output_path(source.sdk_name(), stack_config, output_override)
    } else {
        output_override
            .map(PathBuf::from)
            .unwrap_or_else(|| PathBuf::from(format!("./generated/{}-stack", source.sdk_name())))
    };

    Ok((source, crate_dir, crate_name))
}

fn resolve_stack_source(client: &ApiClient, stack: &str) -> Result<ResolvedStackSource> {
    if let Some(ast) = find_ast_file(stack, None)? {
        return Ok(ResolvedStackSource::Local(ast));
    }

    let remote = client.get_registry_ast_by_stack(stack).with_context(|| {
        format!(
            "Stack '{}' was not found locally and no accessible hosted stack with that identifier was found.",
            stack
        )
    })?;

    Ok(ResolvedStackSource::Remote(remote_stack_ast(remote)))
}

fn resolve_remote_stack_source(client: &ApiClient, stack: &str) -> Result<ResolvedStackSource> {
    let remote = client.get_registry_ast_by_stack(stack).with_context(|| {
        format!(
            "No accessible hosted stack with identifier '{}' was found.",
            stack
        )
    })?;

    Ok(ResolvedStackSource::Remote(remote_stack_ast(remote)))
}

fn remote_stack_ast(remote: RegistryAstResponse) -> RemoteStackAst {
    RemoteStackAst {
        sdk_name: to_kebab_case(&remote.name),
        name: remote.name,
        stack: remote.stack,
        websocket_url: remote.websocket_url,
        ast_payload: remote.ast_payload,
    }
}