noxid-cli 0.2.1

The Noxid compiler command line: check, build, test, adapt, and the agent surface
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
use crate::modules::{ModuleGraph, compile_module_graph};
use noxid_compiler_core::Compilation;
use noxid_graph::EdgeKind;
use noxid_source::json_escape;
use std::collections::BTreeSet;
use std::fs;
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use std::path::{Component, Path, PathBuf};
use std::thread;
use std::time::{Duration, SystemTime};

pub struct AppOptions {
    pub entry: Option<String>,
    pub title: Option<String>,
    pub out_dir: PathBuf,
    pub development: bool,
}

pub struct AppBuild {
    pub entry: String,
    pub components: BTreeSet<String>,
    pub assets: Vec<String>,
}

pub fn build_app(
    input: &Path,
    compilation: &Compilation,
    module_graph: Option<&ModuleGraph>,
    options: &AppOptions,
) -> Result<AppBuild, String> {
    if compilation.has_errors() {
        return Err(format!(
            "{} diagnostic(s); no application emitted",
            compilation.diagnostics.len()
        ));
    }
    let stem = input
        .file_stem()
        .and_then(|value| value.to_str())
        .ok_or("input has no valid file stem")?;
    let entry = select_entry(compilation, stem, options.entry.as_deref())?;
    let merged_graph = module_graph.map(ModuleGraph::merged_graph);
    let components = component_closure(merged_graph.as_ref().unwrap_or(&compilation.graph), &entry);
    let compilations: Vec<&Compilation> = module_graph
        .map(|graph| {
            graph
                .modules()
                .map(|(_, module)| &module.compilation)
                .collect()
        })
        .unwrap_or_else(|| vec![compilation]);
    let asset_dir = options.out_dir.join("assets");
    fs::create_dir_all(&asset_dir)
        .map_err(|error| format!("cannot create {}: {error}", asset_dir.display()))?;

    let mut assets = Vec::new();
    let mut runtime_imports = BTreeSet::new();
    for selected in &components {
        let owner = compilations
            .iter()
            .find(|compilation| {
                compilation
                    .program
                    .components
                    .iter()
                    .any(|component| &component.name == selected)
            })
            .ok_or_else(|| format!("component `{selected}` has no compiled module"))?;
        let generated = owner
            .generated
            .as_ref()
            .ok_or_else(|| format!("component `{selected}` did not generate JavaScript"))?;
        let (javascript, imports) = if generated.modules.is_empty() {
            (&generated.javascript, &generated.runtime_imports)
        } else {
            let module = generated
                .modules
                .iter()
                .find(|module| &module.component == selected)
                .ok_or_else(|| format!("component `{selected}` has no generated chunk"))?;
            (&module.javascript, &module.runtime_imports)
        };
        let owner_stem = module_graph
            .and_then(|graph| graph.module_for_component(selected))
            .map(|(path, _)| path)
            .unwrap_or(input)
            .file_stem()
            .and_then(|value| value.to_str())
            .unwrap_or(selected);
        let rewrite = |contents: &str| {
            ["validators", "resources", "streams", "agents"]
                .into_iter()
                .fold(contents.to_string(), |output, suffix| {
                    output.replace(
                        &format!("./{owner_stem}.{suffix}.js"),
                        &format!("./{selected}.{suffix}.js"),
                    )
                })
        };
        let name = format!("{selected}.js");
        write(&asset_dir.join(&name), &rewrite(javascript))?;
        runtime_imports.extend(imports.iter().cloned());
        assets.push(format!("assets/{name}"));
        let component = owner
            .program
            .components
            .iter()
            .find(|component| &component.name == selected)
            .expect("selected component belongs to compilation");
        let uses_resources = !component.resources.is_empty();
        let uses_streams = !component.streams.is_empty();
        let uses_agents = !component.agents.is_empty();
        if uses_resources {
            runtime_imports.insert("createQueryClient".into());
            runtime_imports.insert("createResourceDefinition".into());
        }
        if uses_streams {
            runtime_imports.insert("createStreamDefinition".into());
        }
        if uses_agents {
            runtime_imports.insert("createAgentDefinition".into());
        }
        for (suffix, contents, required) in [
            (
                "validators",
                owner.generated_validators.as_deref(),
                uses_resources || uses_streams || uses_agents,
            ),
            (
                "resources",
                owner.generated_resources.as_deref(),
                uses_resources,
            ),
            ("streams", owner.generated_streams.as_deref(), uses_streams),
            ("agents", owner.generated_agents.as_deref(), uses_agents),
        ] {
            if !required {
                continue;
            }
            if let Some(contents) = contents {
                let name = format!("{selected}.{suffix}.js");
                write(&asset_dir.join(&name), &rewrite(contents))?;
                assets.push(format!("assets/{name}"));
            }
        }
    }
    let entry_module = format!("{entry}.js");

    let selected = compilations
        .iter()
        .flat_map(|compilation| compilation.program.components.iter())
        .filter(|component| components.contains(&component.name))
        .collect::<Vec<_>>();
    let has_resources = selected
        .iter()
        .any(|component| !component.resources.is_empty());
    let has_streams = selected
        .iter()
        .any(|component| !component.streams.is_empty());
    let has_agents = selected
        .iter()
        .any(|component| !component.agents.is_empty());
    if has_resources {
        runtime_imports.insert("createQueryClient".into());
        runtime_imports.insert("createResourceDefinition".into());
    }
    if has_streams {
        runtime_imports.insert("createStreamDefinition".into());
    }
    if has_agents {
        runtime_imports.insert("createAgentDefinition".into());
    }

    write(
        &asset_dir.join("noxid-runtime.js"),
        &compilation.runtime_javascript_for(&runtime_imports),
    )?;
    assets.push("assets/noxid-runtime.js".into());
    let css_name = format!("{stem}.css");
    let css = compilations
        .iter()
        .map(|compilation| compilation.css_for_components(&components))
        .collect::<Vec<_>>()
        .join("\n");
    write(&asset_dir.join(&css_name), &css)?;
    assets.push(format!("assets/{css_name}"));

    let boot = format!(
        "import {{ mount{} }} from \"./assets/{}\";\n\nconst root = document.querySelector(\"#app\");\nif (!root) throw new Error(\"NOXID_APP_ROOT_MISSING\");\nconst instance = mount{}(root);\nglobalThis.__NOXID_APP__ = Object.freeze({{ entry: \"component:{}\", instance }});\n",
        entry, entry_module, entry, entry
    );
    write(&options.out_dir.join("app.js"), &boot)?;
    assets.push("app.js".into());
    let title = options.title.as_deref().unwrap_or(&entry);
    write(
        &options.out_dir.join("index.html"),
        &html_shell(title, &format!("./assets/{css_name}"), options.development),
    )?;
    assets.push("index.html".into());
    assets.sort();

    write(
        &options.out_dir.join("app.manifest.json"),
        &app_manifest(input, &entry, &components, &assets),
    )?;
    write(
        &options.out_dir.join("app.meta.json"),
        &compilation.metadata_json(),
    )?;
    write(
        &options.out_dir.join("app.bundle.json"),
        &app_bundle(
            &entry,
            &components,
            &runtime_imports,
            has_resources,
            has_streams,
            has_agents,
        ),
    )?;
    Ok(AppBuild {
        entry,
        components,
        assets,
    })
}

pub fn serve(input: PathBuf, mut options: AppOptions, port: u16) -> Result<(), String> {
    options.development = true;
    let watch_input = input.clone();
    let build_input = input.clone();
    let out_dir = options.out_dir.clone();
    serve_rebuilding(
        &input,
        &out_dir,
        port,
        "/",
        move || source_stamp(&watch_input),
        move || rebuild(&build_input, &options),
    )
}

pub fn serve_rebuilding<S, F, B>(
    label: &Path,
    out_dir: &Path,
    port: u16,
    base_path: &str,
    mut source_stamp: F,
    mut rebuild: B,
) -> Result<(), String>
where
    S: Eq,
    F: FnMut() -> Result<S, String>,
    B: FnMut() -> Result<(), String>,
{
    let mut revision = 1_u64;
    let mut stamp = source_stamp()?;
    rebuild()?;
    let listener = TcpListener::bind(("127.0.0.1", port))
        .map_err(|error| format!("cannot bind http://127.0.0.1:{port}: {error}"))?;
    listener
        .set_nonblocking(true)
        .map_err(|error| format!("cannot configure development server: {error}"))?;
    println!(
        "noxid dev serving {} at http://127.0.0.1:{port}{}",
        label.display(),
        if base_path == "/" {
            "/".to_string()
        } else {
            format!("{base_path}/")
        }
    );
    loop {
        let current = source_stamp()?;
        if current != stamp {
            stamp = current;
            match rebuild() {
                Ok(()) => {
                    revision = revision.saturating_add(1);
                    println!("rebuilt {} (revision {revision})", label.display());
                }
                Err(error) => {
                    eprintln!("noxid: rebuild failed; serving last known good output\n{error}")
                }
            }
        }
        match listener.accept() {
            Ok((mut stream, _)) => {
                stream
                    .set_nonblocking(false)
                    .map_err(|error| format!("cannot configure development request: {error}"))?;
                if let Err(error) = respond(&mut stream, out_dir, revision, base_path) {
                    eprintln!("noxid: development request failed: {error}");
                }
            }
            Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
                thread::sleep(Duration::from_millis(40));
            }
            Err(error) => return Err(format!("development server failed: {error}")),
        }
    }
}

fn rebuild(input: &Path, options: &AppOptions) -> Result<(), String> {
    let root = input.parent().unwrap_or_else(|| Path::new("."));
    let components = root.join("components");
    let graph = compile_module_graph(
        input,
        root,
        components.exists().then_some(components.as_path()),
    )?;
    build_app(input, &graph.root().compilation, Some(&graph), options).map(|_| ())
}

fn select_entry(
    compilation: &Compilation,
    stem: &str,
    requested: Option<&str>,
) -> Result<String, String> {
    let names = compilation
        .program
        .components
        .iter()
        .map(|component| component.name.clone())
        .collect::<Vec<_>>();
    if names.is_empty() {
        return Err("application requires at least one component".into());
    }
    if let Some(requested) = requested {
        return names
            .iter()
            .any(|name| name == requested)
            .then(|| requested.to_string())
            .ok_or_else(|| {
                format!(
                    "unknown entry component `{requested}`; available: {}",
                    names.join(", ")
                )
            });
    }
    if names.len() == 1 {
        return Ok(names[0].clone());
    }
    if names.iter().any(|name| name == stem) {
        return Ok(stem.to_string());
    }
    Err(format!(
        "multiple components require --entry <name>; available: {}",
        names.join(", ")
    ))
}

fn component_closure(graph: &noxid_graph::ApplicationGraph, entry: &str) -> BTreeSet<String> {
    let mut selected = BTreeSet::from([entry.to_string()]);
    let mut pending = vec![format!("component:{entry}")];
    while let Some(current) = pending.pop() {
        let owned = graph
            .edges
            .iter()
            .filter(|edge| edge.kind == EdgeKind::Owns && edge.from.as_str() == current)
            .map(|edge| edge.to.clone())
            .collect::<BTreeSet<_>>();
        for edge in &graph.edges {
            if edge.kind != EdgeKind::Mounts || !owned.contains(&edge.from) {
                continue;
            }
            let Some(name) = edge.to.as_str().strip_prefix("component:") else {
                continue;
            };
            if selected.insert(name.to_string()) {
                pending.push(edge.to.to_string());
            }
        }
    }
    selected
}

fn html_shell(title: &str, css: &str, development: bool) -> String {
    let reload = if development {
        r#"    <script type="module">
      let revision = null;
      async function poll() {
        try {
          const response = await fetch("/__noxid/revision", { cache: "no-store" });
          const next = await response.text();
          if (revision !== null && revision !== next) location.reload();
          revision = next;
        } catch {}
        setTimeout(poll, 400);
      }
      poll();
    </script>
"#
    } else {
        ""
    };
    format!(
        "<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n    <title>{}</title>\n    <link rel=\"stylesheet\" href=\"{}\">\n  </head>\n  <body>\n    <div id=\"app\"></div>\n    <script type=\"module\" src=\"./app.js\"></script>\n{reload}  </body>\n</html>\n",
        html_escape(title),
        html_escape(css),
    )
}

fn app_manifest(
    input: &Path,
    entry: &str,
    components: &BTreeSet<String>,
    assets: &[String],
) -> String {
    format!(
        "{{\n  \"schemaVersion\": 1,\n  \"source\": \"{}\",\n  \"entry\": \"component:{}\",\n  \"components\": [{}],\n  \"assets\": [{}]\n}}\n",
        json_escape(&input.to_string_lossy()),
        json_escape(entry),
        components
            .iter()
            .map(|name| format!("\"component:{}\"", json_escape(name)))
            .collect::<Vec<_>>()
            .join(", "),
        assets
            .iter()
            .map(|name| format!("\"{}\"", json_escape(name)))
            .collect::<Vec<_>>()
            .join(", "),
    )
}

fn app_bundle(
    entry: &str,
    components: &BTreeSet<String>,
    imports: &BTreeSet<String>,
    resources: bool,
    streams: bool,
    agents: bool,
) -> String {
    format!(
        "{{\n  \"schemaVersion\": 1,\n  \"entry\": \"component:{}\",\n  \"componentChunks\": [{}],\n  \"runtimeImports\": [{}],\n  \"hasResourceModule\": {},\n  \"hasStreamModule\": {},\n  \"hasAgentModule\": {}\n}}\n",
        json_escape(entry),
        components
            .iter()
            .map(|name| format!("\"assets/{name}.js\""))
            .collect::<Vec<_>>()
            .join(", "),
        imports
            .iter()
            .map(|name| format!("\"{}\"", json_escape(name)))
            .collect::<Vec<_>>()
            .join(", "),
        resources,
        streams,
        agents,
    )
}

fn write(path: &Path, contents: &str) -> Result<(), String> {
    fs::write(path, contents).map_err(|error| format!("cannot write {}: {error}", path.display()))
}

fn source_stamp(path: &Path) -> Result<(SystemTime, u64), String> {
    let metadata = fs::metadata(path)
        .map_err(|error| format!("cannot inspect {}: {error}", path.display()))?;
    Ok((
        metadata.modified().unwrap_or(SystemTime::UNIX_EPOCH),
        metadata.len(),
    ))
}

fn respond(
    stream: &mut TcpStream,
    root: &Path,
    revision: u64,
    base_path: &str,
) -> Result<(), String> {
    stream
        .set_read_timeout(Some(Duration::from_secs(2)))
        .map_err(|error| error.to_string())?;
    let mut buffer = [0_u8; 8192];
    let count = stream
        .read(&mut buffer)
        .map_err(|error| error.to_string())?;
    let request = String::from_utf8_lossy(&buffer[..count]);
    let first = request.lines().next().unwrap_or_default();
    let mut parts = first.split_whitespace();
    let method = parts.next().unwrap_or_default();
    let target = parts.next().unwrap_or("/");
    if method != "GET" && method != "HEAD" {
        return send(
            stream,
            405,
            "text/plain; charset=utf-8",
            b"Method Not Allowed",
            method == "HEAD",
        );
    }
    let request_path = target.split('?').next().unwrap_or("/");
    let revision_path = if base_path == "/" {
        "/__noxid/revision".to_string()
    } else {
        format!("{base_path}/__noxid/revision")
    };
    if request_path == revision_path {
        return send(
            stream,
            200,
            "text/plain; charset=utf-8",
            revision.to_string().as_bytes(),
            method == "HEAD",
        );
    }
    let Some(application_path) = strip_base_path(request_path, base_path) else {
        return send(
            stream,
            404,
            "text/plain; charset=utf-8",
            b"Not Found",
            method == "HEAD",
        );
    };
    let relative = safe_relative_path(application_path)?;
    let mut path = root.join(&relative);
    if path.is_dir() {
        path = path.join("index.html");
    }
    if !path.exists()
        && !application_path
            .rsplit('/')
            .next()
            .unwrap_or_default()
            .contains('.')
    {
        path = root.join("index.html");
    }
    match fs::read(&path) {
        Ok(body) => send(stream, 200, mime(&path), &body, method == "HEAD"),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => send(
            stream,
            404,
            "text/plain; charset=utf-8",
            b"Not Found",
            method == "HEAD",
        ),
        Err(error) => Err(format!("cannot read {}: {error}", path.display())),
    }
}

fn strip_base_path<'a>(request_path: &'a str, base_path: &str) -> Option<&'a str> {
    if base_path == "/" {
        return Some(request_path);
    }
    if request_path == base_path {
        return Some("/");
    }
    request_path
        .strip_prefix(base_path)
        .filter(|remainder| remainder.starts_with('/'))
}

fn safe_relative_path(target: &str) -> Result<PathBuf, String> {
    if target.contains('%') || target.contains('\\') {
        return Err("invalid request path".into());
    }
    let path = Path::new(target.trim_start_matches('/'));
    if path
        .components()
        .any(|component| !matches!(component, Component::Normal(_)))
        && !path.as_os_str().is_empty()
    {
        return Err("invalid request path".into());
    }
    Ok(path.to_path_buf())
}

fn send(
    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",
    };
    let header = format!(
        "HTTP/1.1 {status} {reason}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n",
        body.len()
    );
    stream
        .write_all(header.as_bytes())
        .and_then(|_| if head { Ok(()) } else { stream.write_all(body) })
        .map_err(|error| error.to_string())
}

fn mime(path: &Path) -> &'static str {
    match path.extension().and_then(|value| value.to_str()) {
        Some("html") => "text/html; charset=utf-8",
        Some("js") => "text/javascript; charset=utf-8",
        Some("css") => "text/css; charset=utf-8",
        Some("json") => "application/json; charset=utf-8",
        // WO-53 serves the agent context files (llms.txt, llms-full.txt, and
        // every llms/<topic>.txt chunk) as readable text, not a download.
        Some("txt") => "text/plain; charset=utf-8",
        Some("svg") => "image/svg+xml",
        Some("png") => "image/png",
        Some("jpg" | "jpeg") => "image/jpeg",
        _ => "application/octet-stream",
    }
}

fn html_escape(value: &str) -> String {
    value
        .replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&#39;")
}

#[cfg(test)]
mod tests {
    use super::*;
    use noxid_compiler_core::compile;
    use noxid_source::{SourceFile, SourceId};
    use std::process;

    #[test]
    fn request_paths_cannot_escape_the_app_root() {
        assert!(safe_relative_path("/assets/app.js").is_ok());
        assert!(safe_relative_path("/../secret").is_err());
        assert!(safe_relative_path("/%2e%2e/secret").is_err());
        assert!(safe_relative_path("/..\\secret").is_err());
    }

    #[test]
    fn deployment_base_is_a_strict_path_boundary() {
        assert_eq!(strip_base_path("/console", "/console"), Some("/"));
        assert_eq!(
            strip_base_path("/console/accounts/7", "/console"),
            Some("/accounts/7")
        );
        assert_eq!(strip_base_path("/consolex", "/console"), None);
    }

    #[test]
    fn app_build_emits_only_the_entry_component_closure() {
        let source = SourceFile::new(
            SourceId(0),
            "Bundle.nox",
            r#"component Child {
                view { <p class="child">Child</p> }
                style { .child { color: blue; } }
            }
            component App {
                view { <main><Child /></main> }
            }
            component Unrelated {
                state { count: Int = 0 }
                actions { increment() { count = count + 1 } }
                view { <button +click={increment}>Unrelated</button> }
                style { button { color: hotpink; } }
            }"#,
        );
        let compilation = compile(&source);
        assert!(!compilation.has_errors(), "{:?}", compilation.diagnostics);
        let out_dir = std::env::temp_dir().join(format!(
            "noxid-app-build-test-{}-{}",
            process::id(),
            SystemTime::now()
                .duration_since(SystemTime::UNIX_EPOCH)
                .expect("system clock")
                .as_nanos()
        ));
        let build = build_app(
            Path::new("Bundle.nox"),
            &compilation,
            None,
            &AppOptions {
                entry: Some("App".into()),
                title: None,
                out_dir: out_dir.clone(),
                development: false,
            },
        )
        .expect("app build");
        assert_eq!(
            build.components,
            BTreeSet::from(["App".into(), "Child".into()])
        );
        assert!(out_dir.join("assets/App.js").exists());
        assert!(out_dir.join("assets/Child.js").exists());
        assert!(!out_dir.join("assets/Unrelated.js").exists());
        let bundle = fs::read_to_string(out_dir.join("app.bundle.json")).expect("bundle");
        assert!(!bundle.contains("runAction"));
        let css = fs::read_to_string(out_dir.join("assets/Bundle.css")).expect("css");
        assert!(css.contains("color: blue"));
        assert!(!css.contains("hotpink"));
        fs::remove_dir_all(out_dir).expect("remove test output");
    }
}