wasm-slim 0.1.1

WASM bundle size optimizer
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
//! Build orchestration logic
//!
//! Coordinates the build workflow across multiple tools

use console::style;
use std::path::PathBuf;

use crate::fmt::{format_bytes, CHECKMARK, HAMMER, SPARKLES};
use crate::infra::{CommandExecutor, FileSystem};
use crate::tools::ToolChain;

use super::config::PipelineConfig;
use super::error::PipelineError;
use super::metrics::SizeMetrics;
use super::result_formatter::ResultFormatter;
use super::tool_runner::ToolRunner;

/// Orchestrates the complete build workflow
pub struct BuildOrchestrator<FS: FileSystem, CE: CommandExecutor> {
    project_root: PathBuf,
    config: PipelineConfig,
    toolchain: ToolChain<CE>,
    tool_runner: ToolRunner<FS, CE>,
    fs: FS,
}

impl<FS: FileSystem + Clone, CE: CommandExecutor + Clone> BuildOrchestrator<FS, CE> {
    /// Create a new build orchestrator
    pub fn new(
        project_root: PathBuf,
        config: PipelineConfig,
        toolchain: ToolChain<CE>,
        fs: FS,
        cmd_executor: CE,
    ) -> Self {
        let tool_runner = ToolRunner::new(
            project_root.clone(),
            config.clone(),
            fs.clone(),
            cmd_executor.clone(),
        );
        Self {
            project_root,
            config,
            toolchain,
            tool_runner,
            fs,
        }
    }

    /// Execute the complete build pipeline
    pub fn execute(&self) -> Result<SizeMetrics, PipelineError> {
        println!(
            "\n{} {} WASM Build Pipeline",
            HAMMER,
            style("Running").bold()
        );

        // Step 0: Validate project structure first (before checking tools)
        let cargo_toml = self.project_root.join("Cargo.toml");
        if self.fs.metadata(&cargo_toml).is_err() {
            return Err(PipelineError::FileNotFound(format!(
                "Cargo.toml not found in {}",
                self.project_root.display()
            )));
        }

        // Step 1: Check required tools are available
        self.toolchain.check_required()?;

        // Step 2: Build with cargo
        println!("\n{} Step 1: Building with cargo...", SPARKLES);
        let wasm_file = self.tool_runner.cargo_build()?;
        let before_size = self
            .fs
            .metadata(&wasm_file)
            .map_err(PipelineError::Io)?
            .len();
        println!(
            "   {} Built: {} ({})",
            CHECKMARK,
            style(wasm_file.display()).cyan(),
            style(format_bytes(before_size)).yellow()
        );

        // Step 3: Run wasm-bindgen
        println!("\n{} Step 2: Running wasm-bindgen...", SPARKLES);
        let bindgen_output = self.tool_runner.run_wasm_bindgen(&wasm_file)?;
        println!("   {} wasm-bindgen complete", CHECKMARK);

        // Get the size after wasm-bindgen
        let mut current_size = self
            .fs
            .metadata(&bindgen_output)
            .map_err(PipelineError::Io)?
            .len();

        // Step 4: Run wasm-opt if available
        if self.config.run_wasm_opt && self.toolchain.wasm_opt.is_installed() {
            println!(
                "\n{} Step 3: Running wasm-opt {}...",
                SPARKLES,
                self.config.opt_level.as_arg()
            );
            self.tool_runner.run_wasm_opt(&bindgen_output)?;
            current_size = self
                .fs
                .metadata(&bindgen_output)
                .map_err(PipelineError::Io)?
                .len();
            println!("   {} wasm-opt complete", CHECKMARK);
        } else if self.config.run_wasm_opt {
            println!(
                "\n{} Step 3: Skipping wasm-opt (not installed)",
                style("ℹ️")
            );
        }

        // Step 5: Run wasm-snip if requested and available
        if self.config.run_wasm_snip && self.toolchain.wasm_snip.is_installed() {
            println!("\n{} Step 4: Running wasm-snip...", SPARKLES);
            self.tool_runner.run_wasm_snip(&bindgen_output)?;
            current_size = self
                .fs
                .metadata(&bindgen_output)
                .map_err(PipelineError::Io)?
                .len();
            println!("   {} wasm-snip complete", CHECKMARK);
        }

        // Calculate final metrics
        let metrics = SizeMetrics {
            before_bytes: before_size,
            after_bytes: current_size,
        };

        // Print summary
        ResultFormatter::print_summary(&metrics);

        Ok(metrics)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::infra::{RealCommandExecutor, RealFileSystem};

    #[test]
    fn test_orchestrator_stores_config() {
        let config = PipelineConfig::default();
        let orchestrator = BuildOrchestrator::new(
            PathBuf::from("/test"),
            config.clone(),
            ToolChain::default(),
            RealFileSystem,
            RealCommandExecutor,
        );
        assert_eq!(orchestrator.config.target.as_str(), config.target.as_str());
    }

    #[test]
    fn test_orchestrator_creates_with_toolchain() {
        let config = PipelineConfig::default();
        let toolchain = ToolChain::default();
        let _ = toolchain.check_all();

        let orchestrator = BuildOrchestrator::new(
            PathBuf::from("/test"),
            config,
            toolchain,
            RealFileSystem,
            RealCommandExecutor,
        );

        assert_eq!(orchestrator.toolchain.cargo.name, "Cargo");
    }

    #[test]
    fn test_orchestrator_respects_config_flags() {
        let config = PipelineConfig {
            run_wasm_opt: false,
            run_wasm_snip: false,
            ..Default::default()
        };

        let orchestrator = BuildOrchestrator::new(
            PathBuf::from("/test"),
            config.clone(),
            ToolChain::default(),
            RealFileSystem,
            RealCommandExecutor,
        );

        assert!(!orchestrator.config.run_wasm_opt);
        assert!(!orchestrator.config.run_wasm_snip);
    }

    #[test]
    fn test_build_with_toolchain_structure() {
        // Test that builds correctly store toolchain information
        let config = PipelineConfig::default();
        let toolchain = ToolChain::default();

        let orchestrator = BuildOrchestrator::new(
            PathBuf::from("/test"),
            config,
            toolchain,
            RealFileSystem,
            RealCommandExecutor,
        );

        // Verify toolchain structure is preserved
        assert_eq!(orchestrator.toolchain.cargo.name, "Cargo");
        assert!(orchestrator.toolchain.cargo.required);
    }

    #[test]
    fn test_concurrent_builds() {
        // Test that orchestrator can handle multiple build configurations
        let config1 = PipelineConfig::default();
        let config2 = PipelineConfig {
            run_wasm_opt: false,
            ..Default::default()
        };

        let orchestrator1 = BuildOrchestrator::new(
            PathBuf::from("/test1"),
            config1,
            ToolChain::default(),
            RealFileSystem,
            RealCommandExecutor,
        );

        let orchestrator2 = BuildOrchestrator::new(
            PathBuf::from("/test2"),
            config2,
            ToolChain::default(),
            RealFileSystem,
            RealCommandExecutor,
        );

        // Verify different configs create different orchestrators
        assert_ne!(
            orchestrator1.config.run_wasm_opt,
            orchestrator2.config.run_wasm_opt
        );
    }
}

// Integration tests for the build orchestrator workflow
// These tests verify end-to-end behavior but don't require actual tools
#[cfg(test)]
mod integration_tests {
    use super::*;
    use crate::infra::{mock_exit_status, RealCommandExecutor, RealFileSystem};
    use std::io;
    use std::path::Path;
    use std::process::Command;
    use std::sync::{Arc, Mutex};

    // Mock FileSystem that tracks all operations
    #[derive(Clone)]
    struct MockFileSystem {
        metadata_size: Arc<Mutex<u64>>,
        operations: Arc<Mutex<Vec<String>>>,
    }

    impl MockFileSystem {
        fn new(size: u64) -> Self {
            Self {
                metadata_size: Arc::new(Mutex::new(size)),
                operations: Arc::new(Mutex::new(Vec::new())),
            }
        }

        fn operations(&self) -> Vec<String> {
            self.operations
                .lock()
                .expect("MockFileSystem operations lock should never be poisoned in tests")
                .clone()
        }
    }

    impl FileSystem for MockFileSystem {
        fn metadata(&self, path: &Path) -> io::Result<std::fs::Metadata> {
            self.operations
                .lock()
                .expect("MockFileSystem operations lock should never be poisoned in tests")
                .push(format!("metadata: {}", path.display()));

            // Create a real file temporarily to get metadata
            let temp = tempfile::NamedTempFile::new()?;
            let size = *self
                .metadata_size
                .lock()
                .expect("MockFileSystem size lock should never be poisoned in tests");
            std::fs::write(temp.path(), vec![0u8; size as usize])?;
            std::fs::metadata(temp.path())
        }

        fn read_dir(&self, path: &Path) -> io::Result<std::fs::ReadDir> {
            self.operations
                .lock()
                .expect("MockFileSystem operations lock should never be poisoned in tests")
                .push(format!("read_dir: {}", path.display()));
            // Return an actual empty directory
            let temp_dir = std::env::temp_dir().join(format!("mock_{}", path.display()));
            std::fs::create_dir_all(&temp_dir)?;
            std::fs::read_dir(&temp_dir)
        }

        fn read_to_string(&self, _path: &Path) -> io::Result<String> {
            unimplemented!()
        }

        fn write(&self, _path: &Path, _contents: impl AsRef<[u8]>) -> io::Result<()> {
            unimplemented!()
        }

        fn create_dir_all(&self, _path: &Path) -> io::Result<()> {
            unimplemented!()
        }

        fn copy(&self, _from: &Path, _to: &Path) -> io::Result<u64> {
            unimplemented!()
        }
    }

    // Mock CommandExecutor that simulates tool behavior
    #[derive(Clone)]
    struct MockCommandExecutor {
        fail_at_step: Arc<Mutex<Option<String>>>,
        operations: Arc<Mutex<Vec<String>>>,
    }

    impl MockCommandExecutor {
        fn new() -> Self {
            Self {
                fail_at_step: Arc::new(Mutex::new(None)),
                operations: Arc::new(Mutex::new(Vec::new())),
            }
        }

        fn set_fail_at_step(&self, step: &str) {
            *self
                .fail_at_step
                .lock()
                .expect("MockCommandExecutor lock should never be poisoned in tests") =
                Some(step.to_string());
        }

        fn operations(&self) -> Vec<String> {
            self.operations
                .lock()
                .expect("MockCommandExecutor operations lock should never be poisoned in tests")
                .clone()
        }
    }

    impl CommandExecutor for MockCommandExecutor {
        fn status(&self, cmd: &mut Command) -> io::Result<std::process::ExitStatus> {
            let program = cmd.get_program().to_string_lossy().to_string();
            self.operations
                .lock()
                .expect("MockCommandExecutor operations lock should never be poisoned in tests")
                .push(format!("execute: {}", program));

            // Check if we should fail at this step
            if let Some(ref fail_step) = *self
                .fail_at_step
                .lock()
                .expect("MockCommandExecutor fail_at_step lock should never be poisoned in tests")
            {
                if program.contains(fail_step) {
                    return Ok(mock_exit_status(1));
                }
            }

            Ok(mock_exit_status(0))
        }

        fn output(&self, cmd: &mut Command) -> io::Result<std::process::Output> {
            let program = cmd.get_program().to_string_lossy().to_string();
            self.operations
                .lock()
                .expect("MockCommandExecutor operations lock should never be poisoned in tests")
                .push(format!("output: {}", program));

            // Check if we should fail at this step
            if let Some(ref fail_step) = *self
                .fail_at_step
                .lock()
                .expect("MockCommandExecutor fail_at_step lock should never be poisoned in tests")
            {
                if program.contains(fail_step) {
                    return Ok(std::process::Output {
                        status: mock_exit_status(1),
                        stdout: Vec::new(),
                        stderr: b"mock failure".to_vec(),
                    });
                }
            }

            // Return success with mock version info
            Ok(std::process::Output {
                status: mock_exit_status(0),
                stdout: b"mock-version 1.0.0\n".to_vec(),
                stderr: Vec::new(),
            })
        }
    }

    #[test]
    fn test_orchestrator_with_failed_cargo_stops_pipeline() {
        let config = PipelineConfig::default();
        let fs = MockFileSystem::new(1000);
        let cmd_executor = MockCommandExecutor::new();
        cmd_executor.set_fail_at_step("cargo");

        let orchestrator = BuildOrchestrator::new(
            PathBuf::from("/test"),
            config,
            ToolChain::with_executor(cmd_executor.clone()),
            fs.clone(),
            cmd_executor.clone(),
        );

        let result = orchestrator.execute();
        assert!(result.is_err());

        // Verify cargo tool check was attempted (via version check)
        let ops = cmd_executor.operations();
        assert!(
            ops.iter().any(|op| op.contains("cargo")),
            "Expected cargo in operations: {:?}",
            ops
        );
    }

    #[test]
    fn test_orchestrator_tracks_size_changes_through_pipeline() {
        let config = PipelineConfig {
            run_wasm_opt: false,
            run_wasm_snip: false,
            ..Default::default()
        };

        let fs = MockFileSystem::new(1000);
        let cmd_executor = MockCommandExecutor::new();

        let orchestrator = BuildOrchestrator::new(
            PathBuf::from("/test"),
            config,
            ToolChain::with_executor(cmd_executor.clone()),
            fs.clone(),
            cmd_executor,
        );

        // Note: This will fail because mock doesn't provide actual wasm files
        // But we can verify the setup is correct
        let _ = orchestrator.execute();

        // Verify file system operations were tracked
        let ops = fs.operations();
        assert!(!ops.is_empty());
    }

    #[test]
    fn test_orchestrator_skips_wasm_opt_when_disabled() {
        let config = PipelineConfig {
            run_wasm_opt: false,
            run_wasm_snip: false,
            ..Default::default()
        };

        let fs = MockFileSystem::new(1000);
        let cmd_executor = MockCommandExecutor::new();

        let orchestrator = BuildOrchestrator::new(
            PathBuf::from("/test"),
            config,
            ToolChain::with_executor(cmd_executor.clone()),
            fs,
            cmd_executor.clone(),
        );

        let _ = orchestrator.execute();

        // Verify wasm-opt was not run
        let ops = cmd_executor.operations();
        assert!(!ops.iter().any(|op| op.contains("wasm-opt")));
    }

    #[test]
    fn test_orchestrator_runs_wasm_opt_when_enabled_and_available() {
        let config = PipelineConfig {
            run_wasm_opt: true,
            run_wasm_snip: false,
            ..Default::default()
        };

        let orchestrator = BuildOrchestrator::new(
            PathBuf::from("/test"),
            config.clone(),
            ToolChain::default(),
            RealFileSystem,
            RealCommandExecutor,
        );

        // Just verify the config is stored correctly
        assert!(orchestrator.config.run_wasm_opt);
    }

    #[test]
    fn test_orchestrator_skips_wasm_snip_when_disabled() {
        let config = PipelineConfig {
            run_wasm_opt: false,
            run_wasm_snip: false,
            ..Default::default()
        };

        let fs = MockFileSystem::new(1000);
        let cmd_executor = MockCommandExecutor::new();

        let orchestrator = BuildOrchestrator::new(
            PathBuf::from("/test"),
            config,
            ToolChain::with_executor(cmd_executor.clone()),
            fs,
            cmd_executor.clone(),
        );

        let _ = orchestrator.execute();

        // Verify wasm-snip was not run
        let ops = cmd_executor.operations();
        assert!(!ops.iter().any(|op| op.contains("wasm-snip")));
    }

    #[test]
    fn test_orchestrator_runs_wasm_snip_when_enabled_and_available() {
        let config = PipelineConfig {
            run_wasm_opt: false,
            run_wasm_snip: true,
            ..Default::default()
        };

        let orchestrator = BuildOrchestrator::new(
            PathBuf::from("/test"),
            config.clone(),
            ToolChain::default(),
            RealFileSystem,
            RealCommandExecutor,
        );

        // Just verify the config is stored correctly
        assert!(orchestrator.config.run_wasm_snip);
    }
}