wasmrun 0.19.0

A WebAssembly Runtime
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
use crate::error::{Result, WasmrunError};
use crate::utils::PathResolver;
use clap::{Parser, Subcommand};

/// Wasmrun - WebAssembly project compiler and runtime 🌟
#[derive(Parser, Debug)]
#[command(
    name = "wasmrun",
    author,
    version = get_version_string(),
    about = "A lightweight WebAssembly runner",
    long_about = "Wasmrun is a CLI tool for compiling, running, and debugging WebAssembly modules with full WASI support.",
    after_help = "If you find Wasmrun useful, please consider starring the repository on GitHub! ✨\nhttps://github.com/anistark/wasmrun"
)]
pub struct Args {
    /// Subcommands to control Wasmrun server
    #[command(subcommand)]
    pub command: Option<Commands>,

    /// Path to project directory or WASM file (default: current directory)
    #[arg(
        short = 'p',
        long,
        default_value = "./",
        value_hint = clap::ValueHint::AnyPath,
        help = "Project directory or WASM file path"
    )]
    pub path: String,

    /// Project directory or WASM file path (positional argument)
    #[arg(index = 1, value_hint = clap::ValueHint::AnyPath)]
    pub positional_path: Option<String>,

    /// Port to serve (default: 8420)
    // TODO: Apply to web server as well if provided.
    #[arg(
        short = 'P',
        long,
        default_value_t = 8420,
        value_parser = clap::value_parser!(u16).range(1..=65535),
        help = "Server port number"
    )]
    pub port: u16,

    /// Interpret path as a WebAssembly file (instead of a project directory)
    #[arg(short = 'w', long, help = "Run WASM file directly")]
    pub wasm: bool,

    /// Enable watch mode for live-reloading on file changes
    #[arg(short = 'W', long, help = "Watch for file changes and reload")]
    pub watch: bool,

    /// Enable debug output with detailed information
    #[arg(long, global = true, help = "Show detailed debug information")]
    pub debug: bool,

    /// Serve the UI in browser (default: false)
    #[arg(short = 's', long, help = "Open UI in browser when server starts")]
    pub serve: bool,

    /// Language to use for compilation (auto-detect if not specified)
    #[arg(
        short = 'l',
        long,
        value_parser = ["rust", "go", "c", "asc", "python"],
        help = "Force specific language for compilation"
    )]
    pub language: Option<String>,
}

#[derive(Subcommand, Debug)]
pub enum Commands {
    /// Stop any running Wasmrun server instance
    #[command(alias = "kill")]
    Stop,

    /// Compile a project to WebAssembly with optimization options
    #[command(aliases = ["build", "c"])]
    Compile {
        /// Path to the project directory
        #[arg(
            short = 'p',
            long,
            value_hint = clap::ValueHint::DirPath,
            help = "Project directory to compile"
        )]
        path: Option<String>,

        /// Project directory path (positional argument)
        #[arg(index = 1, value_hint = clap::ValueHint::DirPath)]
        positional_path: Option<String>,

        /// Output directory for the WASM file (default: current directory)
        #[arg(
            short = 'o',
            long,
            value_hint = clap::ValueHint::DirPath,
            help = "Output directory for compiled files"
        )]
        output: Option<String>,

        /// Enable verbose output
        #[arg(short = 'v', long, help = "Show detailed compilation output")]
        verbose: bool,

        /// Optimization level: debug, release, size
        #[arg(
            long,
            default_value = "release",
            value_parser = ["debug", "release", "size"],
            help = "Compilation optimization level"
        )]
        optimization: String,
    },

    /// Verify WebAssembly file format and structure
    Verify {
        /// Path to the WASM file
        #[arg(
            short = 'p',
            long,
            value_hint = clap::ValueHint::FilePath,
            help = "WASM file to verify"
        )]
        path: Option<String>,

        /// WASM file path (positional argument)
        #[arg(index = 1, value_hint = clap::ValueHint::FilePath)]
        positional_path: Option<String>,

        /// Show detailed information about the WASM module
        #[arg(short = 'd', long, help = "Show detailed verification results")]
        detailed: bool,
    },

    /// Perform detailed inspection on a WebAssembly file
    Inspect {
        /// Path to the WASM file
        #[arg(
            short = 'p',
            long,
            value_hint = clap::ValueHint::FilePath,
            help = "WASM file to inspect"
        )]
        path: Option<String>,

        /// WASM file path (positional argument)
        #[arg(index = 1, value_hint = clap::ValueHint::FilePath)]
        positional_path: Option<String>,
    },

    /// Compile and run a project with live development server
    #[command(aliases = ["dev", "serve"])]
    Run {
        /// Path to the project
        #[arg(
            short = 'p',
            long,
            value_hint = clap::ValueHint::DirPath,
            help = "Project directory to run"
        )]
        path: Option<String>,

        /// Project path (positional argument)
        #[arg(index = 1, value_hint = clap::ValueHint::DirPath)]
        positional_path: Option<String>,

        /// Port to serve (default: 8420)
        #[arg(
            short = 'P',
            long,
            default_value_t = 8420,
            value_parser = clap::value_parser!(u16).range(1..=65535),
            help = "Development server port"
        )]
        port: u16,

        /// Language to use for compilation (auto-detect if not specified)
        #[arg(
            short = 'l',
            long,
            value_parser = ["rust", "go", "c", "asc", "python"],
            help = "Force specific language for compilation"
        )]
        language: Option<String>,

        /// Enable watch mode for live-reloading on file changes
        #[arg(long, help = "Watch for changes and auto-reload")]
        watch: bool,

        /// Enable verbose output
        #[arg(short = 'v', long, help = "Show detailed build output")]
        verbose: bool,

        /// Serve the UI in browser (default: false)
        #[arg(short = 's', long, help = "Open UI in browser when server starts")]
        serve: bool,
    },

    /// Execute a WASM file directly with arguments
    Exec {
        /// Path to the WASM file
        #[arg(
            value_hint = clap::ValueHint::FilePath,
            help = "Path to the WASM file to execute"
        )]
        wasm_file: Option<String>,

        /// Exported function name to call (if not specified, uses entry point)
        #[arg(
            short = 'c',
            long,
            value_hint = clap::ValueHint::Other,
            help = "Exported function to call (defaults to entry point: main, _start, or start)"
        )]
        call: Option<String>,

        /// Arguments to pass to the WASM program (after the WASM file)
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },

    /// Run projects in browser-based multi-language OS mode
    Os {
        /// Path to the project
        #[arg(
            short = 'p',
            long,
            value_hint = clap::ValueHint::DirPath,
            help = "Project directory to run in OS mode"
        )]
        path: Option<String>,

        /// Project path (positional argument)
        #[arg(index = 1, value_hint = clap::ValueHint::DirPath)]
        positional_path: Option<String>,

        /// Port to serve (default: 8420)
        #[arg(
            short = 'P',
            long,
            default_value_t = 8420,
            value_parser = clap::value_parser!(u16).range(1..=65535),
            help = "OS mode server port"
        )]
        port: u16,

        /// Language to use for OS mode execution (auto-detect if not specified)
        #[arg(
            short = 'l',
            long,
            value_parser = ["nodejs", "python"],
            help = "Force specific language for OS mode execution"
        )]
        language: Option<String>,

        /// Enable watch mode for live-reloading on file changes
        #[arg(long, help = "Watch for changes and auto-reload")]
        watch: bool,

        /// Enable verbose output
        #[arg(short = 'v', long, help = "Show detailed build output")]
        verbose: bool,

        /// Allow wildcard CORS (Access-Control-Allow-Origin: *)
        #[arg(
            long,
            help = "Allow cross-origin requests from any domain (default: localhost only)"
        )]
        allow_cors: bool,
    },

    /// Start the agent sandbox API server for AI agents
    Agent {
        /// Server port (default: 8430)
        #[arg(
            short = 'P',
            long,
            default_value_t = 8430,
            value_parser = clap::value_parser!(u16).range(1..=65535),
            help = "Agent API server port"
        )]
        port: u16,

        /// Default session timeout in seconds (default: 300)
        #[arg(
            short = 't',
            long,
            default_value_t = 300,
            help = "Default idle timeout per session (seconds)"
        )]
        timeout: u64,

        /// Maximum concurrent sessions (default: 100)
        #[arg(
            short = 'm',
            long,
            default_value_t = 100,
            help = "Maximum number of concurrent sandbox sessions"
        )]
        max_sessions: usize,

        /// Memory limit per session in MB (default: 256)
        #[arg(
            long,
            default_value_t = 256,
            help = "Maximum linear memory per session (MB)"
        )]
        max_memory: u32,

        /// Allow wildcard CORS (Access-Control-Allow-Origin: *)
        #[arg(long, help = "Allow cross-origin requests from any domain")]
        allow_cors: bool,

        /// Enable verbose request logging
        #[arg(short = 'v', long, help = "Log all incoming requests")]
        verbose: bool,
    },

    /// Plugin management commands
    #[command(subcommand)]
    Plugin(PluginSubcommands),

    // TODO: Implement project initialization command
    // This will create new WebAssembly projects from templates (rust, go, c, asc, python)
    // /// Initialize a new Wasmrun project from template
    // #[command(alias = "new")]
    // Init {
    //     /// Project name
    //     #[arg(index = 1, help = "Name of the new project")]
    //     name: Option<String>,

    //     /// Template to use (rust, go, c, asc)
    //     #[arg(
    //         short = 't',
    //         long,
    //         default_value = "rust",
    //         value_parser = ["rust", "go", "c", "asc", "python"],
    //         help = "Project template to use"
    //     )]
    //     template: String,

    //     /// Target directory (default: project name)
    //     #[arg(
    //         short = 'd',
    //         long,
    //         value_hint = clap::ValueHint::DirPath,
    //         help = "Directory to create project in"
    //     )]
    //     directory: Option<String>,
    // },
    /// Clean build artifacts and temporary files
    #[command(aliases = ["clear", "reset"])]
    Clean {
        /// Path to the project directory
        #[arg(
            short = 'p',
            long,
            value_hint = clap::ValueHint::DirPath,
            help = "Project directory to clean"
        )]
        path: Option<String>,

        /// Project directory path (positional argument)
        #[arg(index = 1, value_hint = clap::ValueHint::DirPath)]
        positional_path: Option<String>,

        /// Clean everything (project artifacts and temp directories)
        #[arg(
            short = 'a',
            long,
            help = "Clean both project artifacts and temp directories"
        )]
        all: bool,
    },
}

/// Plugin management subcommands
#[derive(Subcommand, Debug)]
pub enum PluginSubcommands {
    /// List all available plugins
    List {
        /// Show detailed information
        #[arg(short, long)]
        all: bool,
    },

    /// Install a plugin
    Install {
        /// Plugin name, URL, or path
        plugin: String,

        /// Specific version to install (for crates.io plugins)
        #[arg(short, long)]
        version: Option<String>,
    },

    /// Uninstall a plugin
    Uninstall {
        /// Plugin name to uninstall
        plugin: String,
    },

    /// Update a plugin
    Update {
        /// Plugin name to update, or 'all' for all plugins
        plugin: String,
    },

    /// Enable or disable a plugin
    Enable {
        /// Plugin name
        plugin: String,

        /// Disable instead of enable
        #[arg(long)]
        disable: bool,
    },

    /// Show detailed information about a plugin
    Info {
        /// Plugin name
        plugin: String,
    },
    // TODO: Implement plugin search with proper plugin registry system
    // /// Search for available plugins
    // Search {
    //     /// Search query
    //     query: String,
    // },
}

/// Argument resolution with validation
#[derive(Debug)]
pub struct ResolvedArgs {
    pub path: String,
    pub port: u16,
    pub wasm: bool,
    pub watch: bool,
    #[allow(dead_code)] // TODO: Used for debug output control
    pub debug: bool,
    #[allow(dead_code)] // TODO: Used for command validation and processing
    pub command: Option<Commands>,
    pub serve: bool,
    pub language: Option<String>,
}

impl ResolvedArgs {
    /// Create from CLI args with path resolution and validation
    pub fn from_args(args: Args) -> Result<Self> {
        let resolved_path = PathResolver::resolve_input_path(args.positional_path, Some(args.path));

        Ok(Self {
            path: resolved_path,
            port: args.port,
            wasm: args.wasm,
            watch: args.watch,
            debug: args.debug,
            command: args.command,
            serve: args.serve,
            language: args.language,
        })
    }

    /// Validate the resolved arguments
    #[allow(dead_code)] // TODO: Future argument validation system
    pub fn validate(&self) -> Result<()> {
        // Validate port range
        if self.port == 0 {
            return Err(WasmrunError::from(format!(
                "Invalid port number: {}. Must be between 1-65535",
                self.port
            )));
        }

        // Validate path based on context
        match &self.command {
            Some(Commands::Verify { .. }) | Some(Commands::Inspect { .. }) => {
                // These commands expect WASM files
                PathResolver::validate_wasm_file(&self.path)?;
            }
            Some(Commands::Compile { .. })
            | Some(Commands::Run { .. })
            | Some(Commands::Os { .. })
            | Some(Commands::Clean { .. }) => {
                // These commands expect project directories
                PathResolver::validate_directory_exists(&self.path)?;
            }
            _ => {
                // For default run command, validate based on wasm flag
                if self.wasm {
                    PathResolver::validate_wasm_file(&self.path)?;
                } else {
                    // Could be either file or directory
                    if !std::path::Path::new(&self.path).exists() {
                        return Err(WasmrunError::path(format!("Path not found: {}", self.path)));
                    }
                }
            }
        }

        Ok(())
    }
}

/// Command-specific argument resolution
pub trait CommandArgs {
    #[allow(dead_code)] // TODO: Future path resolution trait implementation
    fn resolve_path(&self) -> String;
}

impl CommandArgs for Commands {
    fn resolve_path(&self) -> String {
        match self {
            Commands::Compile {
                path,
                positional_path,
                ..
            } => PathResolver::resolve_input_path(positional_path.clone(), path.clone()),
            Commands::Verify {
                path,
                positional_path,
                ..
            } => PathResolver::resolve_input_path(positional_path.clone(), path.clone()),
            Commands::Inspect {
                path,
                positional_path,
                ..
            } => PathResolver::resolve_input_path(positional_path.clone(), path.clone()),
            Commands::Run {
                path,
                positional_path,
                ..
            } => PathResolver::resolve_input_path(positional_path.clone(), path.clone()),
            Commands::Exec { wasm_file, .. } => {
                PathResolver::resolve_input_path(wasm_file.clone(), None)
            }
            Commands::Os {
                path,
                positional_path,
                ..
            } => PathResolver::resolve_input_path(positional_path.clone(), path.clone()),
            Commands::Clean {
                path,
                positional_path,
                ..
            } => PathResolver::resolve_input_path(positional_path.clone(), path.clone()),
            // TODO: Implement Init command
            // Commands::Init {
            //     name, directory, ..
            // } => directory.clone().unwrap_or_else(|| {
            //     name.clone()
            //         .unwrap_or_else(|| "my-wasmrun-project".to_string())
            // }),
            Commands::Agent { .. } => "./".to_string(),
            Commands::Plugin(_) => "./".to_string(),
            Commands::Stop => "./".to_string(),
        }
    }
}

/// Validation helper for specific command arguments
pub struct CommandValidator;

impl CommandValidator {
    #[allow(dead_code)] // TODO: Future compile command validation
    pub fn validate_compile_args(
        path: &Option<String>,
        positional_path: &Option<String>,
        output: &Option<String>,
    ) -> Result<(String, String)> {
        let project_path = PathResolver::resolve_input_path(positional_path.clone(), path.clone());
        let output_dir = output.clone().unwrap_or_else(|| ".".to_string());

        PathResolver::validate_directory_exists(&project_path)?;
        PathResolver::ensure_output_directory(&output_dir)?;

        Ok((project_path, output_dir))
    }

    pub fn validate_verify_args(
        path: &Option<String>,
        positional_path: &Option<String>,
    ) -> Result<String> {
        let wasm_path = PathResolver::resolve_input_path(positional_path.clone(), path.clone());
        PathResolver::validate_wasm_file(&wasm_path)?;
        Ok(wasm_path)
    }

    #[allow(dead_code)] // TODO: Future run command validation
    pub fn validate_run_args(
        path: &Option<String>,
        positional_path: &Option<String>,
        port: u16,
    ) -> Result<(String, u16)> {
        let project_path = PathResolver::resolve_input_path(positional_path.clone(), path.clone());

        if !std::path::Path::new(&project_path).exists() {
            return Err(WasmrunError::path(format!(
                "Path not found: {project_path}"
            )));
        }

        Ok((project_path, port))
    }

    #[allow(dead_code)] // TODO: Future init command validation
    pub fn validate_init_args(
        name: &Option<String>,
        template: &str,
        directory: &Option<String>,
    ) -> Result<(String, String, String)> {
        let project_name = name
            .clone()
            .unwrap_or_else(|| "my-wasmrun-project".to_string());
        let target_dir = directory.clone().unwrap_or_else(|| project_name.clone());

        let valid_templates = ["rust", "go", "c", "asc", "python"];
        if !valid_templates.contains(&template) {
            return Err(WasmrunError::from(format!(
                "Invalid template '{}'. Valid templates: {}",
                template,
                valid_templates.join(", ")
            )));
        }

        if std::path::Path::new(&target_dir).exists() {
            return Err(WasmrunError::path(format!(
                "Directory '{target_dir}' already exists"
            )));
        }

        Ok((project_name, template.to_string(), target_dir))
    }
}

/// Get version string
fn get_version_string() -> &'static str {
    env!("CARGO_PKG_VERSION")
}

pub fn get_args() -> Args {
    if std::env::args().any(|arg| arg == "-V" || arg == "--version") {
        print_styled_version();
        std::process::exit(0);
    }

    let mut args = Args::parse();

    if let Some(pos_path) = args.positional_path.take() {
        args.path = pos_path;
    }

    args
}

/// Print styled version output
fn print_styled_version() {
    let version = env!("CARGO_PKG_VERSION");
    let name = env!("CARGO_PKG_NAME");

    println!(
        "\n\x1b[1;34mâ•­\x1b[0m\n\
         \x1b[1;34m│\x1b[0m  🅦 \x1b[1;36m{name} v{version}\x1b[0m\n\
         \x1b[1;34m│\x1b[0m  \x1b[0;90mA lightweight WebAssembly runner\x1b[0m\n\
         \x1b[1;34mâ•°\x1b[0m\n"
    );
}

/// Argument parsing with validation
#[allow(dead_code)] // TODO: Future validated argument parsing system
pub fn get_validated_args() -> Result<ResolvedArgs> {
    let args = get_args();
    let resolved = ResolvedArgs::from_args(args)?;
    resolved.validate()?;
    Ok(resolved)
}

// Helper function for error conversion
impl From<String> for WasmrunError {
    fn from(message: String) -> Self {
        Self::Command(crate::error::CommandError::invalid_arguments(message))
    }
}