coatcheck 0.2.1

Contracts and a Playwright accessibility runner for Topcoat component workbenches.
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
#![forbid(unsafe_code)]

use std::error::Error;
use std::ffi::OsStr;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, ExitStatus, Stdio};
use std::thread;
use std::time::{Duration, Instant};

use clap::{Parser, Subcommand, ValueEnum};
use coatcheck::config::{CONFIG_FILE, Config};
use coatcheck::runner::{fetch_manifest, finish_review, generate};

const PLAYWRIGHT_PACKAGE: &str = "@playwright/test@1.61.1";
const AXE_PACKAGE: &str = "@axe-core/playwright@4.12.1";
const CONFIG_TEMPLATE: &str = include_str!("../templates/Coatcheck.toml");
const PACKAGE_TEMPLATE: &str = include_str!("../templates/package.json");
const CUSTOM_SPEC_TEMPLATE: &str = include_str!("../templates/custom.spec.ts");

#[derive(Debug, Parser)]
#[command(
    name = "coatcheck",
    version,
    about = "Semantic component checks for Topcoat workbenches"
)]
struct Cli {
    /// Project directory containing Coatcheck.toml.
    #[arg(long, global = true, default_value = ".")]
    project_root: PathBuf,

    #[command(subcommand)]
    command: Commands,
}

#[derive(Debug, Subcommand)]
enum Commands {
    /// Scaffold Coatcheck.toml and the project-local Bun/Playwright runner.
    Init {
        /// JavaScript package manager used for the runner.
        #[arg(long, value_enum, default_value_t = PackageManager::Bun)]
        package_manager: PackageManager,
        /// Replace Coatcheck.toml if it already exists.
        #[arg(long)]
        force: bool,
        /// Write files without installing JavaScript dependencies or Chromium.
        #[arg(long)]
        skip_install: bool,
    },
    /// Check configuration, Bun, Playwright, Axe, Chromium, and host reachability.
    Doctor {
        /// Install missing project-local runner dependencies and Chromium.
        #[arg(long)]
        fix: bool,
    },
    /// Run the configured host command in the foreground.
    Dev,
    /// Fetch the host manifest, generate explicit cases, and run Playwright.
    Test {
        /// Use an already-running host instead of starting host.command.
        #[arg(long)]
        no_host: bool,
        /// Show Chromium while tests execute.
        #[arg(long)]
        headed: bool,
        /// Run one exact story ID from the manifest.
        #[arg(long)]
        story: Option<String>,
        /// Slow browser operations for visual inspection, in milliseconds.
        #[arg(long)]
        slow_mo: Option<u64>,
    },
}

#[derive(Clone, Copy, Debug, ValueEnum)]
enum PackageManager {
    Bun,
}

fn main() {
    if let Err(error) = run() {
        eprintln!("coatcheck: {error}");
        std::process::exit(1);
    }
}

fn run() -> Result<(), Box<dyn Error>> {
    let cli = Cli::parse();
    let project_root = absolute_project_root(&cli.project_root)?;

    match cli.command {
        Commands::Init {
            package_manager,
            force,
            skip_install,
        } => init(&project_root, package_manager, force, skip_install),
        Commands::Doctor { fix } => doctor(&project_root, fix),
        Commands::Dev => dev(&project_root),
        Commands::Test {
            no_host,
            headed,
            story,
            slow_mo,
        } => test(&project_root, no_host, headed, story.as_deref(), slow_mo),
    }
}

fn init(
    project_root: &Path,
    package_manager: PackageManager,
    force: bool,
    skip_install: bool,
) -> Result<(), Box<dyn Error>> {
    let config_path = project_root.join(CONFIG_FILE);
    if config_path.exists() && !force {
        return Err(message(format!(
            "{} already exists; pass --force to replace it",
            config_path.display()
        )));
    }

    let project_name = project_root
        .file_name()
        .and_then(OsStr::to_str)
        .unwrap_or("coatcheck-project");
    let encoded_name = serde_json::to_string(project_name)?;
    let rendered_config = CONFIG_TEMPLATE.replace("{{project_name}}", &encoded_name);
    fs::write(&config_path, rendered_config)?;
    write_if_missing(&project_root.join("package.json"), PACKAGE_TEMPLATE)?;
    write_if_missing(
        &project_root.join("coatcheck/example.spec.ts"),
        CUSTOM_SPEC_TEMPLATE,
    )?;
    ensure_gitignore(project_root)?;

    println!("created {}", config_path.display());
    println!("created project-local Coatcheck spec scaffold");

    if skip_install {
        println!("skipped Bun and Chromium installation");
    } else {
        install_runner(project_root, package_manager)?;
    }

    Ok(())
}

fn doctor(project_root: &Path, fix: bool) -> Result<(), Box<dyn Error>> {
    let config = load_config(project_root)?;
    println!("ok  {}", project_root.join(CONFIG_FILE).display());

    if fix {
        write_if_missing(&project_root.join("package.json"), PACKAGE_TEMPLATE)?;
        install_runner(project_root, PackageManager::Bun)?;
    }

    check_command(project_root, "bun", &["--version"], "Bun")?;
    check_command(
        project_root,
        "bun",
        &[
            "-e",
            "await import('@playwright/test'); await import('@axe-core/playwright')",
        ],
        "project-local Playwright and Axe",
    )?;

    let chromium_path = command_stdout(
        project_root,
        "bun",
        &[
            "-e",
            "import { chromium } from '@playwright/test'; console.log(chromium.executablePath())",
        ],
    )?;
    let chromium_path = PathBuf::from(chromium_path.trim());
    if !chromium_path.is_file() {
        return Err(message(format!(
            "Chromium is not installed at {}; run `coatcheck doctor --fix`",
            chromium_path.display()
        )));
    }
    println!("ok  Chromium {}", chromium_path.display());

    let health_url = config.endpoint(&config.host.health)?;
    match ureq::get(health_url.as_str()).call() {
        Ok(response) => println!("ok  host health {} {}", response.status(), health_url),
        Err(error) => {
            println!("warn host is not reachable at {health_url}: {error} (run `coatcheck dev`)");
        }
    }

    println!("doctor passed");
    Ok(())
}

fn dev(project_root: &Path) -> Result<(), Box<dyn Error>> {
    let config = load_config(project_root)?;
    println!("running {}", display_command(&config.host.command));
    let status = host_command(project_root, &config)?
        .stdin(Stdio::inherit())
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .status()?;
    require_success(status, "host command")
}

fn test(
    project_root: &Path,
    no_host: bool,
    headed: bool,
    story: Option<&str>,
    slow_mo: Option<u64>,
) -> Result<(), Box<dyn Error>> {
    let config = load_config(project_root)?;
    check_command(
        project_root,
        "bun",
        &[
            "-e",
            "await import('@playwright/test'); await import('@axe-core/playwright')",
        ],
        "project-local Playwright and Axe",
    )?;

    let health_url = config.endpoint(&config.host.health)?;
    let host_is_ready = ureq::get(health_url.as_str()).call().is_ok();
    let mut host = if no_host || host_is_ready {
        if host_is_ready {
            println!("reusing host at {health_url}");
        }
        None
    } else {
        println!("starting {}", display_command(&config.host.command));
        Some(HostGuard::spawn(project_root, &config)?)
    };

    wait_for_health(&config)?;
    let manifest_url = config.endpoint(&config.host.manifest)?;
    let mut manifest = fetch_manifest(&manifest_url)?;
    if let Some(story) = story {
        manifest.stories.retain(|candidate| candidate.id == story);
        if manifest.stories.is_empty() {
            return Err(message(format!("story not found in manifest: {story}")));
        }
    }
    let generated = generate(project_root, &config, &manifest)?;
    println!(
        "generated {} manifest cases in {}",
        generated.case_count,
        generated.directory.display()
    );

    let mut command = Command::new("bunx");
    command
        .current_dir(project_root)
        .arg("playwright")
        .arg("test")
        .arg("--config")
        .arg(&generated.config)
        .stdin(Stdio::inherit())
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit());
    if headed {
        command.env("COATCHECK_HEADED", "1");
    }
    if let Some(slow_mo) = slow_mo {
        command.env("COATCHECK_SLOW_MO", slow_mo.to_string());
    }
    let status = command.status()?;
    let success = status.success();
    finish_review(&generated, &manifest, success)?;

    if let Some(host) = host.as_mut() {
        host.stop();
    }

    if success {
        println!("semantic gates passed");
        println!("review artifacts: {}", generated.review.display());
        Ok(())
    } else {
        Err(message(format!(
            "semantic gates failed; review {}",
            generated.review.display()
        )))
    }
}

fn load_config(project_root: &Path) -> Result<Config, Box<dyn Error>> {
    Ok(Config::load(&project_root.join(CONFIG_FILE))?)
}

fn install_runner(
    project_root: &Path,
    package_manager: PackageManager,
) -> Result<(), Box<dyn Error>> {
    match package_manager {
        PackageManager::Bun => {
            println!("installing {PLAYWRIGHT_PACKAGE} and {AXE_PACKAGE}");
            let status = Command::new("bun")
                .current_dir(project_root)
                .args(["add", "--dev", "--exact", PLAYWRIGHT_PACKAGE, AXE_PACKAGE])
                .status()?;
            require_success(status, "Bun dependency installation")?;

            println!("installing Playwright Chromium");
            let status = Command::new("bunx")
                .current_dir(project_root)
                .args(["playwright", "install", "chromium"])
                .status()?;
            require_success(status, "Chromium installation")?;
        }
    }
    Ok(())
}

fn wait_for_health(config: &Config) -> Result<(), Box<dyn Error>> {
    let health_url = config.endpoint(&config.host.health)?;
    let deadline = Instant::now() + Duration::from_secs(config.host.startup_timeout_seconds);
    let mut last_error = String::new();

    while Instant::now() < deadline {
        match ureq::get(health_url.as_str()).call() {
            Ok(_) => {
                println!("host ready at {health_url}");
                return Ok(());
            }
            Err(error) => last_error = error.to_string(),
        }
        thread::sleep(Duration::from_millis(200));
    }

    Err(message(format!(
        "host did not become ready at {health_url}: {last_error}"
    )))
}

fn host_command(project_root: &Path, config: &Config) -> Result<Command, Box<dyn Error>> {
    let (program, args) = config
        .host
        .command
        .split_first()
        .ok_or_else(|| message("host.command is empty"))?;
    let mut command = Command::new(program);
    command.current_dir(project_root).args(args);
    Ok(command)
}

fn check_command(
    project_root: &Path,
    program: &str,
    args: &[&str],
    label: &str,
) -> Result<(), Box<dyn Error>> {
    let status = Command::new(program)
        .current_dir(project_root)
        .args(args)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .map_err(|error| message(format!("{label} is unavailable: {error}")))?;
    if !status.success() {
        return Err(message(format!(
            "{label} check failed; run `coatcheck doctor --fix`"
        )));
    }
    println!("ok  {label}");
    Ok(())
}

fn command_stdout(
    project_root: &Path,
    program: &str,
    args: &[&str],
) -> Result<String, Box<dyn Error>> {
    let output = Command::new(program)
        .current_dir(project_root)
        .args(args)
        .output()?;
    if !output.status.success() {
        return Err(message(format!(
            "{program} command failed: {}",
            String::from_utf8_lossy(&output.stderr).trim()
        )));
    }
    Ok(String::from_utf8(output.stdout)?)
}

fn require_success(status: ExitStatus, label: &str) -> Result<(), Box<dyn Error>> {
    if status.success() {
        Ok(())
    } else {
        Err(message(format!("{label} exited with {status}")))
    }
}

fn write_if_missing(path: &Path, contents: &str) -> Result<(), Box<dyn Error>> {
    if path.exists() {
        return Ok(());
    }
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(path, contents)?;
    println!("created {}", path.display());
    Ok(())
}

fn ensure_gitignore(project_root: &Path) -> Result<(), Box<dyn Error>> {
    let path = project_root.join(".gitignore");
    let mut contents = fs::read_to_string(&path).unwrap_or_default();
    if contents.lines().any(|line| line.trim() == ".coatcheck/") {
        return Ok(());
    }
    if !contents.is_empty() && !contents.ends_with('\n') {
        contents.push('\n');
    }
    contents.push_str(".coatcheck/\n");
    fs::write(path, contents)?;
    Ok(())
}

fn absolute_project_root(path: &Path) -> Result<PathBuf, Box<dyn Error>> {
    let path = if path.is_absolute() {
        path.to_path_buf()
    } else {
        std::env::current_dir()?.join(path)
    };
    if !path.is_dir() {
        return Err(message(format!(
            "project root does not exist: {}",
            path.display()
        )));
    }
    Ok(path.canonicalize()?)
}

fn display_command(command: &[String]) -> String {
    command
        .iter()
        .map(|part| {
            if part.contains(char::is_whitespace) {
                format!("{part:?}")
            } else {
                part.clone()
            }
        })
        .collect::<Vec<_>>()
        .join(" ")
}

fn message(message: impl Into<String>) -> Box<dyn Error> {
    Box::new(io::Error::other(message.into()))
}

struct HostGuard {
    child: Child,
    stopped: bool,
}

impl HostGuard {
    fn spawn(project_root: &Path, config: &Config) -> Result<Self, Box<dyn Error>> {
        let mut command = host_command(project_root, config)?;
        command
            .stdin(Stdio::null())
            .stdout(Stdio::inherit())
            .stderr(Stdio::inherit());
        #[cfg(unix)]
        {
            use std::os::unix::process::CommandExt;
            command.process_group(0);
        }
        Ok(Self {
            child: command.spawn()?,
            stopped: false,
        })
    }

    fn stop(&mut self) -> Option<ExitStatus> {
        if self.stopped {
            return self.child.try_wait().ok().flatten();
        }
        self.stopped = true;

        if let Ok(Some(status)) = self.child.try_wait() {
            return Some(status);
        }

        #[cfg(unix)]
        {
            signal("-INT", &self.child.id().to_string());
        }
        #[cfg(not(unix))]
        {
            let _ = self.child.kill();
        }

        for _ in 0..100 {
            if let Ok(Some(status)) = self.child.try_wait() {
                return Some(status);
            }
            thread::sleep(Duration::from_millis(50));
        }

        #[cfg(unix)]
        {
            signal("-KILL", &format!("-{}", self.child.id()));
        }
        let _ = self.child.kill();
        self.child.wait().ok()
    }
}

impl Drop for HostGuard {
    fn drop(&mut self) {
        self.stop();
    }
}

#[cfg(unix)]
fn signal(signal: &str, target: &str) {
    let _ = Command::new("kill")
        .args([signal, "--", target])
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status();
}

#[cfg(all(test, unix))]
mod tests {
    use std::os::unix::process::ExitStatusExt;

    use super::{Config, HostGuard};

    #[test]
    fn host_stop_interrupts_the_child_without_terminating_its_parent() {
        let project = tempfile::tempdir().unwrap();
        let config: Config = toml::from_str(
            r#"
version = 1
name = "Host cleanup"

[host]
command = ["sleep", "30"]
url = "http://127.0.0.1:3000"
"#,
        )
        .unwrap();
        let mut host = HostGuard::spawn(project.path(), &config).unwrap();

        let status = host.stop().expect("host should be reaped");

        assert_eq!(status.signal(), Some(2));
    }
}