kael-cli 0.4.1

Scaffold and build release-aligned Kael applications for desktop and the web
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
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
use serde_json::Value;
use std::ffi::OsStr;
use std::fs;
use std::io::{BufRead as _, BufReader, Read as _, Write as _};
use std::net::{TcpListener, TcpStream};
use std::path::{Component, Path, PathBuf};
use std::process::{Command, Stdio};

const WASM_TARGET: &str = "wasm32-unknown-unknown";
const WASM_BINDGEN_VERSION: &str = "0.2.122";
const WASM_OPT_VERSION: &str = "132";

const DEFAULT_INDEX: &str = r##"<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />
    <meta name="color-scheme" content="dark light" />
    <title>Kael application</title>
    <style>
      html, body, #blade { width: 100%; height: 100%; margin: 0; }
      body { overflow: hidden; background: #111827; }
      #blade { display: block; outline: none; touch-action: none; }
      #kael-error { position: fixed; inset: 1rem; color: #fecaca;
        font: 14px/1.5 ui-monospace, monospace; white-space: pre-wrap;
        pointer-events: none; }
    </style>
  </head>
  <body>
    <canvas id="blade" aria-label="Kael application"></canvas>
    <pre id="kael-error" role="alert"></pre>
    <script type="module">
      import init from "./app.js";
      try {
        await init({ module_or_path: "./app_bg.wasm" });
        document.documentElement.dataset.kaelReady = "true";
      } catch (error) {
        document.querySelector("#kael-error").textContent =
          `Kael browser startup failed:\n${error?.stack ?? error}`;
        throw error;
      }
    </script>
  </body>
</html>
"##;

#[derive(Debug, Clone, PartialEq, Eq)]
struct WebOptions {
    command: WebCommand,
    release: bool,
    out_dir: PathBuf,
    html: Option<PathBuf>,
    assets: Option<PathBuf>,
    package: Option<String>,
    bin: Option<String>,
    port: u16,
    open: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum WebCommand {
    Build,
    Serve,
}

struct BuildTarget {
    package: String,
    bin: String,
    target_directory: PathBuf,
}

pub(super) fn run(args: &[String]) -> Result<(), String> {
    if args.is_empty()
        || args
            .iter()
            .any(|argument| matches!(argument.as_str(), "-h" | "--help"))
    {
        print_help();
        return Ok(());
    }
    let options = parse_options(args)?;
    let current_dir = std::env::current_dir()
        .map_err(|error| format!("cannot resolve the current directory: {error}"))?;
    let output = build(&current_dir, &options)?;
    println!("Built Kael web app in {}", output.display());
    if options.command == WebCommand::Serve {
        serve(&output, options.port, options.open)?;
    } else {
        println!("Run it locally with: kael web serve");
    }
    Ok(())
}

fn print_help() {
    println!(
        "Build the same Kael app for a WebGL2 browser canvas.

USAGE:
    kael web build [OPTIONS]
    kael web serve [OPTIONS]

OPTIONS:
    --debug              Build without release optimizations
    --out-dir <path>     Output directory (default: dist/web)
    --html <file>        Use a source-owned HTML shell
    --assets <directory> Copy product web assets into the output
    --package <name>     Select a package in a Cargo workspace
    --bin <name>         Select a binary target
    --port <number>      Local serve port (default: 8000)
    --no-open            Do not open the browser after serving
    -h, --help           Print this help"
    );
}

fn parse_options(args: &[String]) -> Result<WebOptions, String> {
    let command = match args.first().map(String::as_str) {
        Some("build") => WebCommand::Build,
        Some("serve") => WebCommand::Serve,
        Some(other) => return Err(format!("unknown `kael web` command {other:?}")),
        None => return Err("`kael web` requires `build` or `serve`".into()),
    };
    let mut options = WebOptions {
        command,
        release: true,
        out_dir: PathBuf::from("dist/web"),
        html: None,
        assets: None,
        package: None,
        bin: None,
        port: 8_000,
        open: true,
    };
    let mut index = 1;
    while index < args.len() {
        match args[index].as_str() {
            "--debug" => options.release = false,
            "--no-open" => options.open = false,
            "--out-dir" => {
                index += 1;
                options.out_dir = required_value(args, index, "--out-dir")?.into();
            }
            "--html" => {
                index += 1;
                options.html = Some(required_value(args, index, "--html")?.into());
            }
            "--assets" => {
                index += 1;
                options.assets = Some(required_value(args, index, "--assets")?.into());
            }
            "--package" => {
                index += 1;
                options.package = Some(required_value(args, index, "--package")?.into());
            }
            "--bin" => {
                index += 1;
                options.bin = Some(required_value(args, index, "--bin")?.into());
            }
            "--port" => {
                index += 1;
                options.port = required_value(args, index, "--port")?
                    .parse()
                    .map_err(|_| "--port must be an integer from 1 to 65535".to_string())?;
                if options.port == 0 {
                    return Err("--port must be an integer from 1 to 65535".into());
                }
            }
            other => return Err(format!("unknown web option {other:?}")),
        }
        index += 1;
    }
    if command == WebCommand::Build && (!options.open || options.port != 8_000) {
        return Err("--port and --no-open are only valid with `kael web serve`".into());
    }
    Ok(options)
}

fn required_value<'a>(args: &'a [String], index: usize, option: &str) -> Result<&'a str, String> {
    args.get(index)
        .map(String::as_str)
        .filter(|value| !value.starts_with('-'))
        .ok_or_else(|| format!("{option} requires a value"))
}

fn build(current_dir: &Path, options: &WebOptions) -> Result<PathBuf, String> {
    let target = discover_target(
        current_dir,
        options.package.as_deref(),
        options.bin.as_deref(),
    )?;
    ensure_wasm_bindgen()?;
    if options.release {
        ensure_wasm_opt()?;
    }

    let mut cargo = Command::new("cargo");
    cargo.current_dir(current_dir).args([
        "build",
        "--target",
        WASM_TARGET,
        "--package",
        &target.package,
        "--bin",
        &target.bin,
    ]);
    if options.release {
        cargo.arg("--release");
    }
    let status = cargo
        .status()
        .map_err(|error| format!("failed to start Cargo: {error}"))?;
    if !status.success() {
        return Err(format!(
            "Cargo could not build {} for {WASM_TARGET}; ensure Kael dependencies select their `browser` features for wasm32",
            target.bin
        ));
    }

    let profile = if options.release { "release" } else { "debug" };
    let wasm_dir = target.target_directory.join(WASM_TARGET).join(profile);
    let wasm = find_wasm(&wasm_dir, &target.bin)?;
    let output = if options.out_dir.is_absolute() {
        options.out_dir.clone()
    } else {
        current_dir.join(&options.out_dir)
    };
    fs::create_dir_all(&output)
        .map_err(|error| format!("failed to create {}: {error}", output.display()))?;

    let status = Command::new("wasm-bindgen")
        .args([
            "--target",
            "web",
            "--no-typescript",
            "--out-name",
            "app",
            "--out-dir",
        ])
        .arg(&output)
        .arg(&wasm)
        .status()
        .map_err(|error| format!("failed to run wasm-bindgen: {error}"))?;
    if !status.success() {
        return Err("wasm-bindgen could not package the compiled module".into());
    }
    if options.release {
        optimize_wasm(&output.join("app_bg.wasm"))?;
    }

    if let Some(assets) = options.assets.as_deref() {
        let assets = resolve_input_path(current_dir, assets);
        copy_web_assets(&assets, &output)?;
    }

    let index = output.join("index.html");
    if let Some(html) = options.html.as_deref() {
        let html = resolve_input_path(current_dir, html);
        if !html.is_file() {
            return Err(format!("web HTML shell is not a file: {}", html.display()));
        }
        fs::copy(&html, &index).map_err(|error| {
            format!(
                "failed to copy web HTML shell {} to {}: {error}",
                html.display(),
                index.display()
            )
        })?;
    } else if !index.exists() {
        fs::write(&index, DEFAULT_INDEX)
            .map_err(|error| format!("failed to write {}: {error}", index.display()))?;
    }
    Ok(output)
}

fn resolve_input_path(current_dir: &Path, path: &Path) -> PathBuf {
    if path.is_absolute() {
        path.to_path_buf()
    } else {
        current_dir.join(path)
    }
}

fn copy_web_assets(source: &Path, output: &Path) -> Result<(), String> {
    if !source.is_dir() {
        return Err(format!(
            "web asset source is not a directory: {}",
            source.display()
        ));
    }
    let source = source
        .canonicalize()
        .map_err(|error| format!("failed to resolve {}: {error}", source.display()))?;
    let output = output
        .canonicalize()
        .map_err(|error| format!("failed to resolve {}: {error}", output.display()))?;
    if output.starts_with(&source) {
        return Err(format!(
            "web output {} cannot be inside asset source {}",
            output.display(),
            source.display()
        ));
    }
    copy_web_asset_directory(&source, &source, &output)
}

fn copy_web_asset_directory(root: &Path, directory: &Path, output: &Path) -> Result<(), String> {
    let entries = fs::read_dir(directory)
        .map_err(|error| format!("failed to read web assets {}: {error}", directory.display()))?;
    for entry in entries {
        let entry = entry.map_err(|error| {
            format!(
                "failed to inspect web assets {}: {error}",
                directory.display()
            )
        })?;
        let source = entry.path();
        let metadata = fs::symlink_metadata(&source)
            .map_err(|error| format!("failed to inspect {}: {error}", source.display()))?;
        if metadata.file_type().is_symlink() {
            return Err(format!(
                "web asset symlinks are not supported: {}",
                source.display()
            ));
        }
        let relative = source.strip_prefix(root).map_err(|error| {
            format!("failed to resolve web asset {}: {error}", source.display())
        })?;
        if matches!(
            relative.to_str(),
            Some("index.html" | "app.js" | "app_bg.wasm")
        ) {
            return Err(format!(
                "web asset source cannot replace reserved output {}",
                relative.display()
            ));
        }
        let destination = output.join(relative);
        if metadata.is_dir() {
            fs::create_dir_all(&destination).map_err(|error| {
                format!(
                    "failed to create web asset directory {}: {error}",
                    destination.display()
                )
            })?;
            copy_web_asset_directory(root, &source, output)?;
        } else if metadata.is_file() {
            if let Some(parent) = destination.parent() {
                fs::create_dir_all(parent).map_err(|error| {
                    format!(
                        "failed to create web asset directory {}: {error}",
                        parent.display()
                    )
                })?;
            }
            fs::copy(&source, &destination).map_err(|error| {
                format!(
                    "failed to copy web asset {} to {}: {error}",
                    source.display(),
                    destination.display()
                )
            })?;
        }
    }
    Ok(())
}

fn discover_target(
    current_dir: &Path,
    requested_package: Option<&str>,
    requested_bin: Option<&str>,
) -> Result<BuildTarget, String> {
    let output = Command::new("cargo")
        .current_dir(current_dir)
        .args(["metadata", "--format-version", "1", "--no-deps"])
        .output()
        .map_err(|error| format!("failed to run `cargo metadata`: {error}"))?;
    if !output.status.success() {
        return Err(format!(
            "`cargo metadata` failed:\n{}",
            String::from_utf8_lossy(&output.stderr).trim()
        ));
    }
    let metadata: Value = serde_json::from_slice(&output.stdout)
        .map_err(|error| format!("Cargo returned invalid metadata: {error}"))?;
    select_target(&metadata, current_dir, requested_package, requested_bin)
}

fn select_target(
    metadata: &Value,
    current_dir: &Path,
    requested_package: Option<&str>,
    requested_bin: Option<&str>,
) -> Result<BuildTarget, String> {
    let packages = metadata["packages"]
        .as_array()
        .ok_or_else(|| "Cargo metadata did not contain packages".to_string())?;
    let package = if let Some(name) = requested_package {
        packages
            .iter()
            .find(|package| package["name"].as_str() == Some(name))
            .ok_or_else(|| format!("Cargo workspace has no package named {name:?}"))?
    } else {
        let local_manifest = current_dir.join("Cargo.toml");
        let local = packages.iter().find(|package| {
            package["manifest_path"]
                .as_str()
                .is_some_and(|path| paths_equivalent(Path::new(path), &local_manifest))
        });
        if let Some(package) = local {
            package
        } else {
            let defaults = metadata["workspace_default_members"]
                .as_array()
                .into_iter()
                .flatten()
                .filter_map(Value::as_str)
                .collect::<Vec<_>>();
            if defaults.len() != 1 {
                return Err("select a Cargo package with `--package <name>`".into());
            }
            packages
                .iter()
                .find(|package| package["id"].as_str() == Some(defaults[0]))
                .ok_or_else(|| "Cargo default package was not present in metadata".to_string())?
        }
    };
    let package_name = package["name"]
        .as_str()
        .ok_or_else(|| "Cargo package had no name".to_string())?;
    let bins = package["targets"]
        .as_array()
        .into_iter()
        .flatten()
        .filter(|target| {
            target["kind"]
                .as_array()
                .is_some_and(|kinds| kinds.iter().any(|kind| kind.as_str() == Some("bin")))
        })
        .collect::<Vec<_>>();
    let bin = if let Some(name) = requested_bin {
        bins.iter()
            .copied()
            .find(|target| target["name"].as_str() == Some(name))
            .ok_or_else(|| format!("package {package_name:?} has no binary named {name:?}"))?
    } else if bins.len() == 1 {
        bins[0]
    } else if let Some(target) = bins
        .iter()
        .copied()
        .find(|target| target["name"].as_str() == Some(package_name))
    {
        target
    } else {
        return Err("select a binary target with `--bin <name>`".into());
    };
    let bin = bin["name"]
        .as_str()
        .ok_or_else(|| "Cargo binary target had no name".to_string())?;
    let target_directory = metadata["target_directory"]
        .as_str()
        .map(PathBuf::from)
        .ok_or_else(|| "Cargo metadata had no target directory".to_string())?;
    Ok(BuildTarget {
        package: package_name.into(),
        bin: bin.into(),
        target_directory,
    })
}

fn paths_equivalent(left: &Path, right: &Path) -> bool {
    match (left.canonicalize(), right.canonicalize()) {
        (Ok(left), Ok(right)) => left == right,
        _ => left == right,
    }
}

fn find_wasm(directory: &Path, bin: &str) -> Result<PathBuf, String> {
    for file_name in [
        format!("{bin}.wasm"),
        format!("{}.wasm", bin.replace('-', "_")),
    ] {
        let candidate = directory.join(file_name);
        if candidate.is_file() {
            return Ok(candidate);
        }
    }
    Err(format!(
        "Cargo succeeded but {} did not contain the {bin:?} WebAssembly binary",
        directory.display()
    ))
}

fn ensure_wasm_bindgen() -> Result<(), String> {
    let output = Command::new("wasm-bindgen")
        .arg("--version")
        .output()
        .map_err(|_| install_wasm_bindgen_message())?;
    let version = String::from_utf8_lossy(&output.stdout);
    if !output.status.success()
        || !version
            .split_whitespace()
            .any(|part| part == WASM_BINDGEN_VERSION)
    {
        return Err(format!(
            "Kael requires wasm-bindgen CLI {WASM_BINDGEN_VERSION}, but found {:?}. {}",
            version.trim(),
            install_wasm_bindgen_message()
        ));
    }
    Ok(())
}

fn install_wasm_bindgen_message() -> String {
    format!(
        "Install it with `cargo install wasm-bindgen-cli --version {WASM_BINDGEN_VERSION} --locked`."
    )
}

fn ensure_wasm_opt() -> Result<(), String> {
    let output = Command::new("wasm-opt")
        .arg("--version")
        .output()
        .map_err(|_| install_wasm_opt_message())?;
    let version = String::from_utf8_lossy(&output.stdout);
    if !output.status.success()
        || !version
            .split_whitespace()
            .any(|part| part == WASM_OPT_VERSION)
    {
        return Err(format!(
            "Kael requires wasm-opt {WASM_OPT_VERSION} for release builds, but found {:?}. {}",
            version.trim(),
            install_wasm_opt_message()
        ));
    }
    Ok(())
}

fn install_wasm_opt_message() -> String {
    "Install it with `npm install --global binaryen@132.0.0`. Use `--debug` only when an unoptimized development build is intentional.".into()
}

fn optimize_wasm(wasm: &Path) -> Result<(), String> {
    let optimized = wasm.with_extension("optimized.wasm");
    let before = fs::metadata(wasm)
        .map_err(|error| format!("cannot inspect {}: {error}", wasm.display()))?
        .len();
    let status = Command::new("wasm-opt")
        .arg("-O3")
        .arg(wasm)
        .arg("-o")
        .arg(&optimized)
        .status()
        .map_err(|error| format!("failed to start wasm-opt: {error}"))?;
    if !status.success() {
        let _ = fs::remove_file(&optimized);
        return Err("wasm-opt could not optimize the packaged module".into());
    }
    fs::copy(&optimized, wasm).map_err(|error| {
        format!(
            "failed to install optimized WebAssembly at {}: {error}",
            wasm.display()
        )
    })?;
    fs::remove_file(&optimized).map_err(|error| {
        format!(
            "failed to remove temporary optimized module {}: {error}",
            optimized.display()
        )
    })?;
    let after = fs::metadata(wasm)
        .map_err(|error| format!("cannot inspect {}: {error}", wasm.display()))?
        .len();
    println!("Optimized WebAssembly with Binaryen {WASM_OPT_VERSION}: {before} -> {after} bytes");
    Ok(())
}

fn serve(directory: &Path, port: u16, open: bool) -> Result<(), String> {
    let root = directory
        .canonicalize()
        .map_err(|error| format!("failed to resolve {}: {error}", directory.display()))?;
    let address = format!("127.0.0.1:{port}");
    let listener = TcpListener::bind(&address)
        .map_err(|error| format!("cannot serve http://{address}: {error}"))?;
    let url = format!("http://{address}");
    println!("Serving {} at {url} (press Ctrl-C to stop)", root.display());
    if open {
        open_browser(&url);
    }
    for connection in listener.incoming() {
        match connection {
            Ok(stream) => {
                if let Err(error) = serve_connection(stream, &root) {
                    eprintln!("web request failed: {error}");
                }
            }
            Err(error) => eprintln!("web connection failed: {error}"),
        }
    }
    Ok(())
}

fn serve_connection(mut stream: TcpStream, root: &Path) -> Result<(), String> {
    let mut reader = BufReader::new(
        stream
            .try_clone()
            .map_err(|error| format!("failed to read request: {error}"))?,
    );
    let mut request = String::new();
    reader
        .read_line(&mut request)
        .map_err(|error| format!("failed to read request: {error}"))?;
    let mut fields = request.split_whitespace();
    let method = fields.next().unwrap_or_default();
    let uri = fields.next().unwrap_or_default();
    let head = method == "HEAD";
    if method != "GET" && !head {
        return write_response(
            &mut stream,
            405,
            "text/plain; charset=utf-8",
            b"Method Not Allowed",
            head,
        );
    }
    let path = match safe_asset_path(root, uri) {
        Some(path) => path,
        None => {
            return write_response(
                &mut stream,
                404,
                "text/plain; charset=utf-8",
                b"Not Found",
                head,
            );
        }
    };
    let mut body = Vec::new();
    fs::File::open(&path)
        .and_then(|mut file| file.read_to_end(&mut body))
        .map_err(|error| format!("failed to read {}: {error}", path.display()))?;
    write_response(&mut stream, 200, mime_type(&path), &body, head)
}

fn safe_asset_path(root: &Path, uri: &str) -> Option<PathBuf> {
    let raw = uri.split(['?', '#']).next()?;
    if raw.contains('%') || raw.contains('\\') {
        return None;
    }
    let relative = raw.trim_start_matches('/');
    let relative = if relative.is_empty() {
        "index.html"
    } else {
        relative
    };
    let path = Path::new(relative);
    if !path
        .components()
        .all(|component| matches!(component, Component::Normal(_)))
    {
        return None;
    }
    let candidate = root.join(path).canonicalize().ok()?;
    (candidate.starts_with(root) && candidate.is_file()).then_some(candidate)
}

fn write_response(
    stream: &mut TcpStream,
    status: u16,
    content_type: &str,
    body: &[u8],
    head: bool,
) -> Result<(), String> {
    let reason = match status {
        200 => "OK",
        404 => "Not Found",
        405 => "Method Not Allowed",
        _ => "Error",
    };
    write!(
        stream,
        "HTTP/1.1 {status} {reason}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nCache-Control: no-cache\r\nConnection: close\r\n\r\n",
        body.len()
    )
    .and_then(|()| if head { Ok(()) } else { stream.write_all(body) })
    .map_err(|error| format!("failed to write response: {error}"))
}

fn mime_type(path: &Path) -> &'static str {
    match path.extension().and_then(OsStr::to_str) {
        Some("html") => "text/html; charset=utf-8",
        Some("js" | "mjs") => "text/javascript; charset=utf-8",
        Some("wasm") => "application/wasm",
        Some("css") => "text/css; charset=utf-8",
        Some("json") => "application/json; charset=utf-8",
        Some("map") => "application/json; charset=utf-8",
        Some("webmanifest") => "application/manifest+json; charset=utf-8",
        Some("txt") => "text/plain; charset=utf-8",
        Some("xml") => "application/xml; charset=utf-8",
        Some("svg") => "image/svg+xml",
        Some("png") => "image/png",
        Some("jpg" | "jpeg") => "image/jpeg",
        Some("webp") => "image/webp",
        Some("avif") => "image/avif",
        Some("gif") => "image/gif",
        Some("ico") => "image/x-icon",
        Some("mp3") => "audio/mpeg",
        Some("wav") => "audio/wav",
        Some("ogg") => "audio/ogg",
        Some("mp4") => "video/mp4",
        Some("webm") => "video/webm",
        Some("woff") => "font/woff",
        Some("woff2") => "font/woff2",
        _ => "application/octet-stream",
    }
}

fn open_browser(url: &str) {
    #[cfg(target_os = "macos")]
    let mut command = {
        let mut command = Command::new("open");
        command.arg(url);
        command
    };
    #[cfg(target_os = "windows")]
    let mut command = {
        let mut command = Command::new("cmd");
        command.args(["/C", "start", "", url]);
        command
    };
    #[cfg(all(unix, not(target_os = "macos")))]
    let mut command = {
        let mut command = Command::new("xdg-open");
        command.arg(url);
        command
    };
    #[cfg(not(any(unix, target_os = "windows")))]
    return;

    command.stdout(Stdio::null()).stderr(Stdio::null());
    if let Err(error) = command.spawn() {
        eprintln!("could not open the browser automatically ({error}); open {url}");
    }
}

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

    #[test]
    fn parses_build_and_serve_options() {
        let build = parse_options(&[
            "build".into(),
            "--debug".into(),
            "--bin".into(),
            "demo".into(),
        ])
        .unwrap();
        assert_eq!(build.command, WebCommand::Build);
        assert!(!build.release);
        assert_eq!(build.bin.as_deref(), Some("demo"));

        let custom = parse_options(&[
            "build".into(),
            "--html".into(),
            "web/index.html".into(),
            "--assets".into(),
            "web/assets".into(),
        ])
        .unwrap();
        assert_eq!(custom.html, Some(PathBuf::from("web/index.html")));
        assert_eq!(custom.assets, Some(PathBuf::from("web/assets")));

        let serve = parse_options(&[
            "serve".into(),
            "--port".into(),
            "9000".into(),
            "--no-open".into(),
        ])
        .unwrap();
        assert_eq!(serve.command, WebCommand::Serve);
        assert_eq!(serve.port, 9_000);
        assert!(!serve.open);
    }

    #[test]
    fn build_rejects_serve_only_options() {
        assert!(parse_options(&["build".into(), "--port".into(), "9000".into()]).is_err());
        assert!(parse_options(&["build".into(), "--no-open".into()]).is_err());
    }

    #[test]
    fn selects_local_package_and_default_binary() {
        let temp = std::env::temp_dir().join(format!("kael-web-metadata-{}", std::process::id()));
        fs::create_dir_all(&temp).unwrap();
        let manifest = temp.join("Cargo.toml");
        fs::write(&manifest, "[package]\nname='demo'\nversion='0.1.0'\n").unwrap();
        let metadata = serde_json::json!({
            "target_directory": temp.join("target"),
            "workspace_default_members": ["demo 0.1.0"],
            "packages": [{
                "id": "demo 0.1.0",
                "name": "demo",
                "manifest_path": manifest,
                "targets": [{"name": "demo", "kind": ["bin"]}]
            }]
        });
        let target = select_target(&metadata, &temp, None, None).unwrap();
        assert_eq!(target.package, "demo");
        assert_eq!(target.bin, "demo");
        fs::remove_dir_all(temp).ok();
    }

    #[test]
    fn static_asset_paths_cannot_escape_the_output_root() {
        let temp = std::env::temp_dir().join(format!("kael-web-assets-{}", std::process::id()));
        fs::create_dir_all(&temp).unwrap();
        fs::write(temp.join("index.html"), DEFAULT_INDEX).unwrap();
        let root = temp.canonicalize().unwrap();
        assert_eq!(safe_asset_path(&root, "/"), Some(root.join("index.html")));
        assert!(safe_asset_path(&root, "/../Cargo.toml").is_none());
        assert!(safe_asset_path(&root, "/%2e%2e/Cargo.toml").is_none());
        fs::remove_dir_all(temp).ok();
    }

    #[test]
    fn default_page_has_the_required_canvas_and_module() {
        assert!(DEFAULT_INDEX.contains("<canvas id=\"blade\""));
        assert!(DEFAULT_INDEX.contains("./app.js"));
        assert!(DEFAULT_INDEX.contains("./app_bg.wasm"));
        assert!(DEFAULT_INDEX.contains("module_or_path"));
    }

    #[test]
    fn serves_common_product_assets_with_browser_mime_types() {
        assert_eq!(mime_type(Path::new("app_bg.wasm")), "application/wasm");
        assert_eq!(
            mime_type(Path::new("site.webmanifest")),
            "application/manifest+json; charset=utf-8"
        );
        assert_eq!(mime_type(Path::new("font.woff2")), "font/woff2");
        assert_eq!(mime_type(Path::new("image.avif")), "image/avif");
        assert_eq!(mime_type(Path::new("clip.webm")), "video/webm");
    }

    #[test]
    fn copies_nested_web_assets_without_replacing_packager_outputs() {
        let temp =
            std::env::temp_dir().join(format!("kael-web-copy-assets-{}", std::process::id()));
        let source = temp.join("source");
        let output = temp.join("output");
        fs::create_dir_all(source.join("fonts")).unwrap();
        fs::create_dir_all(&output).unwrap();
        fs::write(source.join("fonts/inter.woff"), b"font").unwrap();
        fs::write(source.join("manifest.webmanifest"), b"{}").unwrap();

        copy_web_assets(&source, &output).unwrap();

        assert_eq!(fs::read(output.join("fonts/inter.woff")).unwrap(), b"font");
        assert_eq!(
            fs::read(output.join("manifest.webmanifest")).unwrap(),
            b"{}"
        );
        fs::write(source.join("app.js"), b"replacement").unwrap();
        assert!(copy_web_assets(&source, &output).is_err());
        fs::remove_dir_all(temp).ok();
    }

    #[test]
    fn rejects_output_nested_inside_web_assets() {
        let temp =
            std::env::temp_dir().join(format!("kael-web-nested-assets-{}", std::process::id()));
        let output = temp.join("dist");
        fs::create_dir_all(&output).unwrap();
        assert!(copy_web_assets(&temp, &output).is_err());
        fs::remove_dir_all(temp).ok();
    }
}