mini-build 0.1.0

Builds the directory a static server serves: CSS/JS bundling and minification via external tools, plus asset mirroring.
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
558
559
560
use std::collections::HashMap;
use std::ffi::OsString;
use std::fs;
use std::path::{Path, PathBuf};

use crate::tool::{self, group_by_parent};

/// External tools this crate knows how to invoke for CSS bundling/minification.
///
/// `#[non_exhaustive]` so a future preset (e.g. a second CSS tool) is an additive
/// variant, not a semver-breaking change for downstream `match` expressions.
///
/// # Installation
///
/// This crate does not install or manage these binaries — only looks them up on
/// `PATH` before a build starts and fails loudly if missing (see [`crate::Builder::css_tool`]).
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CssTool {
    /// <https://lightningcss.dev>, invoked via its separately-installed `lightningcss`
    /// CLI (npm package `lightningcss-cli`) — a different artifact from the Rust
    /// `lightningcss` crate this refactor removes.
    ///
    /// # Trust boundary
    ///
    /// Bundling delegates `@import` resolution entirely to this CLI process, which
    /// resolves imports relative to the file being processed with no root boundary
    /// this crate can inject. This is an accepted trade-off: CSS source folders are
    /// developer-authored build inputs, not request-time attacker input (unlike a
    /// static server's HTTP path resolver, which is guarded separately). An `@import`
    /// escaping the intended source tree is a build misconfiguration to catch in
    /// review, not a runtime exploit surface. [`tool::TOOL_TIMEOUT`] is the bound that
    /// replaces the old in-process import-depth/file-count ceilings.
    LightningCss,
    /// Copies the entry file to the output file unchanged. Test-only: lets
    /// orchestration (discovery, concatenation, error handling, `SourcePipeline`
    /// wiring) be exercised against a real subprocess without depending on
    /// `lightningcss` being installed in CI.
    #[cfg(test)]
    TestEcho,
    /// Always fails with `ToolError::NotFound`. Test-only, for exercising the
    /// startup PATH-probe and hard-fail-on-missing-binary paths.
    #[cfg(test)]
    TestMissing,
}

impl CssTool {
    pub(crate) fn binary_name(&self) -> &'static str {
        match self {
            CssTool::LightningCss => "lightningcss",
            #[cfg(test)]
            CssTool::TestEcho => "cp",
            #[cfg(test)]
            CssTool::TestMissing => "definitely-not-a-real-binary-9f3c2a",
        }
    }

    pub(crate) fn install_hint(&self) -> &'static str {
        match self {
            CssTool::LightningCss => {
                "install via `npm install -g lightningcss-cli` (or add it as a project \
                 devDependency and put its bin/ on PATH)"
            }
            #[cfg(test)]
            CssTool::TestEcho | CssTool::TestMissing => "test-only tool, not installable",
        }
    }

    fn args(&self, bundle: bool, minify: bool, entry: &Path, output: &Path) -> Vec<OsString> {
        match self {
            CssTool::LightningCss => {
                let mut args = Vec::new();
                if bundle {
                    args.push(OsString::from("--bundle"));
                }
                if minify {
                    args.push(OsString::from("--minify"));
                }
                args.push(OsString::from("-o"));
                args.push(output.into());
                args.push(entry.into());
                args
            }
            #[cfg(test)]
            CssTool::TestEcho => vec![entry.into(), output.into()],
            #[cfg(test)]
            CssTool::TestMissing => vec![],
        }
    }

    /// Arguments for transforming many inputs in **one** invocation, writing each result
    /// into `out_dir`.
    ///
    /// This is where nearly all of a real build's time goes: process startup, paid once
    /// per file. `lightningcss` accepts `[INPUT_FILE]...` with `--output-dir`, so N files
    /// cost one spawn instead of N.
    ///
    /// `--output-dir` **flattens** — `src/a.css` and `src/sub/a.css` would both land on
    /// `out/a.css`, silently losing one. Callers must therefore batch only files that
    /// share a parent directory, where basenames are unique by construction. See
    /// `group_by_parent`.
    fn batch_args(
        &self,
        bundle: bool,
        minify: bool,
        inputs: &[PathBuf],
        out_dir: &Path,
    ) -> Vec<OsString> {
        match self {
            CssTool::LightningCss => {
                let mut args = Vec::new();
                if bundle {
                    args.push(OsString::from("--bundle"));
                }
                if minify {
                    args.push(OsString::from("--minify"));
                }
                args.push(OsString::from("--output-dir"));
                args.push(out_dir.into());
                args.extend(inputs.iter().map(OsString::from));
                args
            }
            // `cp file... dir/` is the batch form of `cp file dir/file`.
            #[cfg(test)]
            CssTool::TestEcho => {
                let mut args: Vec<OsString> = inputs.iter().map(OsString::from).collect();
                args.push(out_dir.into());
                args
            }
            #[cfg(test)]
            CssTool::TestMissing => vec![],
        }
    }
}

/// A directory removed when this value is dropped.
///
/// The scratch dir holds per-file tool output on its way into the bundle. Cleanup has to
/// survive the `?` on every fallible step between creating it and finishing with it,
/// which a `remove_dir_all` at the end of the function does not.
struct ScratchDir {
    path: PathBuf,
}

impl ScratchDir {
    fn new(path: PathBuf) -> Result<Self, CssError> {
        fs::create_dir_all(&path).map_err(|e| CssError::WriteOutput {
            path: path.clone(),
            reason: e.to_string(),
        })?;
        Ok(ScratchDir { path })
    }
}

impl Drop for ScratchDir {
    fn drop(&mut self) {
        let _ = fs::remove_dir_all(&self.path);
    }
}

/// Configuration for [`crate::Builder::css_tool`]: independent `bundle`/`minify`
/// toggles, all four combinations valid.
#[derive(Debug, Clone)]
pub struct CssOptions {
    bundle: bool,
    minify: bool,
    bundle_output_name: String,
}

impl CssOptions {
    /// Neither bundle nor minify — CSS is copied through unchanged.
    pub fn new() -> Self {
        CssOptions {
            bundle: false,
            minify: false,
            bundle_output_name: "styles.css".to_string(),
        }
    }

    /// Bundle every `.css` under the source folders into a single output file,
    /// resolving `@import` via the configured [`CssTool`].
    pub fn bundle(mut self, bundle: bool) -> Self {
        self.bundle = bundle;
        self
    }

    /// Minify CSS via the configured [`CssTool`].
    pub fn minify(mut self, minify: bool) -> Self {
        self.minify = minify;
        self
    }

    /// Output file name for bundle mode, under the server's output dir (default
    /// `styles.css`). Ignored when `bundle` is `false`.
    pub fn bundle_output_name(mut self, name: impl Into<String>) -> Self {
        self.bundle_output_name = name.into();
        self
    }

    pub(crate) fn is_bundle(&self) -> bool {
        self.bundle
    }

    pub(crate) fn is_minify(&self) -> bool {
        self.minify
    }

    pub(crate) fn output_file_name(&self) -> &str {
        &self.bundle_output_name
    }
}

impl Default for CssOptions {
    fn default() -> Self {
        Self::new()
    }
}

/// Errors from CSS tool orchestration: discovery, subprocess execution, and output
/// writing.
#[derive(Debug)]
pub enum CssError {
    ReadSource { path: PathBuf, reason: String },
    WriteOutput { path: PathBuf, reason: String },
    NoFilesFound(PathBuf),
    Tool(tool::ToolError),
}

impl std::fmt::Display for CssError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CssError::ReadSource { path, reason } => {
                write!(f, "failed to read {}: {reason}", path.display())
            }
            CssError::WriteOutput { path, reason } => {
                write!(f, "failed to write {}: {reason}", path.display())
            }
            CssError::NoFilesFound(path) => write!(f, "no CSS files found in {}", path.display()),
            CssError::Tool(e) => write!(f, "{e}"),
        }
    }
}

impl std::error::Error for CssError {}

impl From<tool::ToolError> for CssError {
    fn from(e: tool::ToolError) -> Self {
        CssError::Tool(e)
    }
}

/// Bundle every `.css` file discovered under `source_dirs` into a single file at
/// `output_path`, per `options`. Each discovered file is run through `css_tool`
/// (bundle/minify per `options`) into a scratch file, then concatenated in sorted
/// path order — same shape as the old in-process bundler, just delegated per-file.
///
/// # Errors
///
/// Returns `Err` without touching `output_path` if discovery, any tool invocation, or
/// the final write fails — a broken rebuild leaves the previous good output in place
/// rather than serving a partial or corrupt bundle.
pub(crate) fn build_css_bundle(
    css_tool: CssTool,
    options: &CssOptions,
    source_dirs: &[PathBuf],
    output_path: &Path,
) -> Result<(), CssError> {
    let css_files = find_css_files(source_dirs)?;
    if css_files.is_empty() {
        let first = source_dirs
            .first()
            .cloned()
            .unwrap_or_else(|| PathBuf::from("."));
        return Err(CssError::NoFilesFound(first));
    }

    // Passthrough: no tool runs at all, so there is nothing to batch.
    if !options.bundle && !options.minify {
        let mut combined = Vec::new();
        for file in &css_files {
            let bytes = fs::read(file).map_err(|e| CssError::ReadSource {
                path: file.clone(),
                reason: e.to_string(),
            })?;
            combined.extend_from_slice(&bytes);
        }
        return write_output(output_path, &combined);
    }

    // One invocation per source directory rather than per file. Process startup, not the
    // work itself, is what a real build spends its time on — measured at roughly 19 ms a
    // spawn against about 5 ms of actual transformation — so collapsing N spawns into one
    // per directory is the difference between a second and a few tens of milliseconds on
    // a realistic tree. Grouping by directory rather than batching everything at once is
    // what keeps it correct: `--output-dir` distinguishes results by basename only.
    let scratch = ScratchDir::new(scratch_dir_path(output_path))?;
    let mut produced: HashMap<PathBuf, PathBuf> = HashMap::new();

    for (index, (_parent, files)) in group_by_parent(&css_files).into_iter().enumerate() {
        let group_dir = scratch.path.join(index.to_string());
        fs::create_dir_all(&group_dir).map_err(|e| CssError::WriteOutput {
            path: group_dir.clone(),
            reason: e.to_string(),
        })?;

        let outputs: Vec<PathBuf> = files
            .iter()
            .map(|file| group_dir.join(file.file_name().unwrap_or_default()))
            .collect();

        run_tool_batch(
            css_tool,
            options.bundle,
            options.minify,
            &files,
            &group_dir,
            &outputs,
        )?;

        for (file, output) in files.into_iter().zip(outputs) {
            produced.insert(file, output);
        }
    }

    // Concatenated in the original sorted order, not group order: the bundle's contents
    // must not depend on how the work happened to be batched.
    let mut combined = Vec::new();
    for file in &css_files {
        let output = produced.get(file).ok_or_else(|| CssError::ReadSource {
            path: file.clone(),
            reason: "the tool produced no output for this file".to_string(),
        })?;
        let bytes = fs::read(output).map_err(|e| CssError::ReadSource {
            path: output.clone(),
            reason: e.to_string(),
        })?;
        combined.extend_from_slice(&bytes);
    }

    write_output(output_path, &combined)
}

/// Process a single CSS file (bundle disabled) into its mirrored `output` path.
///
/// A malformed source degrades to a raw copy rather than failing the pipeline — the
/// server must still serve the file and keep the browser in sync. The degradation is
/// logged, not silent.
/// Transform many files in as few invocations as possible, each into its mirrored
/// `output`.
///
/// Files the tool would not touch anyway — passthrough mode, or `*.min.css` — are copied
/// without a process. The rest are grouped by output directory and sent one invocation
/// per group, because `--output-dir` tells results apart by basename and basenames are
/// unique only within a directory.
///
/// A failed batch **falls back to building its files one at a time** rather than failing.
/// Per-file mode's contract is that one malformed source degrades to a raw copy and the
/// build carries on; batching must not quietly upgrade that to "one bad file breaks the
/// whole directory". The fallback costs a spawn per file, but only in the case that was
/// already going wrong.
pub(crate) fn build_css_files(
    css_tool: CssTool,
    options: &CssOptions,
    pairs: &[(PathBuf, PathBuf)],
) -> Result<(), CssError> {
    let (transform, bypass): (Vec<_>, Vec<_>) = pairs
        .iter()
        .partition(|(source, _)| options.minify && !is_already_minified(source));

    for (source, output) in bypass {
        copy_file(source, output)?;
    }
    if transform.is_empty() {
        return Ok(());
    }

    let by_output_dir = group_by_parent(
        &transform
            .iter()
            .map(|(_, output)| output.clone())
            .collect::<Vec<_>>(),
    );

    for (out_dir, outputs) in by_output_dir {
        fs::create_dir_all(&out_dir).map_err(|e| CssError::WriteOutput {
            path: out_dir.clone(),
            reason: e.to_string(),
        })?;

        let group: Vec<&(PathBuf, PathBuf)> = transform
            .iter()
            .copied()
            .filter(|(_, output)| outputs.contains(output))
            .collect();
        let inputs: Vec<PathBuf> = group.iter().map(|(source, _)| source.clone()).collect();

        if run_tool_batch(css_tool, false, true, &inputs, &out_dir, &outputs).is_err() {
            for (source, output) in group {
                build_css_file(css_tool, options, source, output)?;
            }
        }
    }

    Ok(())
}

pub(crate) fn build_css_file(
    css_tool: CssTool,
    options: &CssOptions,
    source: &Path,
    output: &Path,
) -> Result<(), CssError> {
    if !options.minify || is_already_minified(source) {
        return copy_file(source, output);
    }

    if let Err(e) = run_tool(css_tool, false, true, source, output) {
        eprintln!(
            "css tool: minify failed for {}, serving raw bytes: {e}",
            source.display()
        );
        return copy_file(source, output);
    }
    Ok(())
}

fn run_tool(
    css_tool: CssTool,
    bundle: bool,
    minify: bool,
    entry: &Path,
    output: &Path,
) -> Result<(), tool::ToolError> {
    if let Some(parent) = output.parent() {
        let _ = fs::create_dir_all(parent);
    }
    let args = css_tool.args(bundle, minify, entry, output);
    tool::execute(
        css_tool.binary_name(),
        css_tool.install_hint(),
        css_tool.binary_name(),
        &args,
        &[output],
        tool::TOOL_TIMEOUT,
    )
}

/// Transform every path in `inputs` in a single invocation, writing into `out_dir`.
///
/// `expected` is what the caller believes will be produced; `execute` verifies every one
/// of them exists and is non-empty, so a tool that quietly skipped an input fails here
/// rather than leaving a hole in the bundle.
fn run_tool_batch(
    css_tool: CssTool,
    bundle: bool,
    minify: bool,
    inputs: &[PathBuf],
    out_dir: &Path,
    expected: &[PathBuf],
) -> Result<(), tool::ToolError> {
    let args = css_tool.batch_args(bundle, minify, inputs, out_dir);
    let expected: Vec<&Path> = expected.iter().map(PathBuf::as_path).collect();
    tool::execute(
        css_tool.binary_name(),
        css_tool.install_hint(),
        css_tool.binary_name(),
        &args,
        &expected,
        tool::TOOL_TIMEOUT,
    )
}

/// True if `path`'s filename indicates it's already minified (`*.min.css`). Such
/// files should be served as-is — running a minifier on already-minified input is
/// wasted work at best and a correctness risk at worst.
fn is_already_minified(path: &Path) -> bool {
    path.file_name()
        .and_then(|name| name.to_str())
        .is_some_and(|name| name.ends_with(".min.css"))
}

/// Where per-file tool output is staged before being concatenated into the bundle.
///
/// A sibling of the bundle rather than a system temp dir: it must be on the same
/// filesystem, and it is visible next to the output when a build is interrupted, which
/// makes a leak obvious rather than mysterious.
fn scratch_dir_path(output_path: &Path) -> PathBuf {
    let file_name = output_path
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("output");
    output_path.with_file_name(format!(".{file_name}.building"))
}

fn write_output(output_path: &Path, bytes: &[u8]) -> Result<(), CssError> {
    if let Some(parent) = output_path.parent() {
        fs::create_dir_all(parent).map_err(|e| CssError::WriteOutput {
            path: output_path.to_path_buf(),
            reason: e.to_string(),
        })?;
    }
    fs::write(output_path, bytes).map_err(|e| CssError::WriteOutput {
        path: output_path.to_path_buf(),
        reason: e.to_string(),
    })
}

fn copy_file(source: &Path, output: &Path) -> Result<(), CssError> {
    if let Some(parent) = output.parent() {
        fs::create_dir_all(parent).map_err(|e| CssError::WriteOutput {
            path: output.to_path_buf(),
            reason: e.to_string(),
        })?;
    }
    fs::copy(source, output).map_err(|e| CssError::WriteOutput {
        path: output.to_path_buf(),
        reason: e.to_string(),
    })?;
    Ok(())
}

/// Find every `.css` file under `source_dirs`, recursively, sorted by path.
fn find_css_files(source_dirs: &[PathBuf]) -> Result<Vec<PathBuf>, CssError> {
    let mut files = Vec::new();
    for dir in source_dirs {
        let found = walk_for_extension(dir, "css").map_err(|e| CssError::ReadSource {
            path: dir.clone(),
            reason: e.to_string(),
        })?;
        files.extend(found);
    }
    files.sort();
    Ok(files)
}

fn walk_for_extension(dir: &Path, ext: &str) -> std::io::Result<Vec<PathBuf>> {
    let mut files = Vec::new();
    let mut dirs = vec![dir.to_path_buf()];

    while let Some(current_dir) = dirs.pop() {
        for entry in fs::read_dir(&current_dir)? {
            let entry = entry?;
            let path = entry.path();
            let file_type = entry.file_type()?;

            if file_type.is_dir() {
                dirs.push(path);
            } else if file_type.is_file() && path.extension().and_then(|s| s.to_str()) == Some(ext)
            {
                files.push(path);
            }
        }
    }

    Ok(files)
}

#[cfg(test)]
#[path = "../tests/unit/css.rs"]
mod tests;