fob-bundler 0.5.0

Fob bundler - Rolldown-based bundling on top of fob foundation
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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
//! Asset processor for production builds.
//!
//! Copies assets to the output directory with content-based hashing and
//! rewrites URLs in the bundled code to point to the hashed assets.

use super::asset_registry::{AssetInfo, AssetRegistry};
use crate::{Error, Result};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::path::Path;

/// Process assets for production build.
///
/// # Steps
///
/// 1. Copy assets to output directory with content hashes
/// 2. Update registry with hashed filenames
/// 3. Return mapping of original paths to public URLs
///
/// # Arguments
///
/// * `registry` - Asset registry with discovered assets
/// * `out_dir` - Output directory for the build
/// * `assets_dir` - Subdirectory for assets (e.g., "assets")
/// * `public_path` - Base URL path for assets (e.g., "/")
///
/// # Returns
///
/// Map of original specifier → public URL for URL rewriting
pub fn process_assets(
    registry: &AssetRegistry,
    out_dir: &Path,
    assets_dir: &str,
    public_path: &str,
) -> Result<HashMap<String, String>> {
    let assets_output = out_dir.join(assets_dir);

    // Create assets directory
    std::fs::create_dir_all(&assets_output).map_err(|e| Error::IoError {
        message: format!(
            "Failed to create assets directory: {}",
            assets_output.display()
        ),
        source: e,
    })?;

    let mut url_map = HashMap::new();

    // Process each asset
    for asset in registry.all_assets() {
        let processed = process_single_asset(&asset, &assets_output)?;

        // Build public URL
        let public_url = format!(
            "{}{}{}/{}",
            public_path.trim_end_matches('/'),
            if public_path.ends_with('/') { "" } else { "/" },
            assets_dir,
            processed.filename
        );

        // Update registry with hash
        registry.set_content_hash(&asset.source_path, processed.hash.clone());

        // Map original specifier to public URL
        url_map.insert(asset.specifier.clone(), public_url);
    }

    Ok(url_map)
}

/// Information about a processed asset.
struct ProcessedAsset {
    /// Content hash
    hash: String,

    /// Final filename with hash
    filename: String,
}

/// Process a single asset file.
///
/// Reads the file, computes hash, copies to output with hashed name.
fn process_single_asset(asset: &AssetInfo, output_dir: &Path) -> Result<ProcessedAsset> {
    // Read asset content
    let content = std::fs::read(&asset.source_path).map_err(|e| Error::IoError {
        message: format!("Failed to read asset: {}", asset.source_path.display()),
        source: e,
    })?;

    // Compute content hash
    let hash = hash_content(&content);

    // Generate filename: [name]-[hash8].[ext]
    let filename = generate_filename(&asset.source_path, &hash)?;

    // Write to output directory
    let output_path = output_dir.join(&filename);
    std::fs::write(&output_path, &content).map_err(|e| Error::IoError {
        message: format!("Failed to write asset: {}", output_path.display()),
        source: e,
    })?;

    Ok(ProcessedAsset { hash, filename })
}

/// Hash asset content using SHA-256.
///
/// Returns hex-encoded hash (64 characters).
fn hash_content(data: &[u8]) -> String {
    let mut hasher = Sha256::new();
    hasher.update(data);
    format!("{:x}", hasher.finalize())
}

/// Generate asset filename with content hash.
///
/// Format: `[stem]-[hash8].[ext]`
///
/// Example: `file.wasm` with hash `abcd1234...` → `file-abcd1234.wasm`
fn generate_filename(path: &Path, hash: &str) -> Result<String> {
    let stem = path.file_stem().and_then(|s| s.to_str()).ok_or_else(|| {
        Error::InvalidConfig(format!("Invalid asset filename: {}", path.display()))
    })?;

    let ext = path.extension().and_then(|s| s.to_str()).unwrap_or("");

    // Use first 8 characters of hash
    let hash_short = &hash[..8.min(hash.len())];

    if ext.is_empty() {
        Ok(format!("{}-{}", stem, hash_short))
    } else {
        Ok(format!("{}-{}.{}", stem, hash_short, ext))
    }
}

/// Report of URL rewrite operations.
#[derive(Debug, Clone)]
pub struct RewriteReport {
    /// Number of URLs successfully rewritten
    pub replacements: usize,
    /// Specifiers that were found and rewritten
    pub rewritten_specifiers: Vec<String>,
    /// Specifiers from url_map that were not found in the code
    pub unused_specifiers: Vec<String>,
}

impl RewriteReport {
    fn new() -> Self {
        Self {
            replacements: 0,
            rewritten_specifiers: Vec::new(),
            unused_specifiers: Vec::new(),
        }
    }
}

/// Rewrite URLs in bundled JavaScript code using regex-based pattern matching.
///
/// Replaces `new URL(specifier, import.meta.url)` (optionally with `.href`)
/// with the mapped public URL from the url_map.
///
/// This function uses regex patterns that handle whitespace variations,
/// making it robust against minification and formatting differences.
///
/// # Arguments
///
/// * `code` - JavaScript code to rewrite
/// * `url_map` - Map of original specifier → public URL
///
/// # Returns
///
/// Result containing rewritten code and a report of operations
pub fn rewrite_urls_ast(
    code: &str,
    url_map: &HashMap<String, String>,
) -> Result<(String, RewriteReport)> {
    use regex::Regex;

    // If no mappings, return original code
    if url_map.is_empty() {
        return Ok((
            code.to_string(),
            RewriteReport {
                replacements: 0,
                rewritten_specifiers: Vec::new(),
                unused_specifiers: Vec::new(),
            },
        ));
    }

    let mut rewritten = code.to_string();
    let mut report = RewriteReport::new();

    // Escape special regex characters in specifiers
    for (specifier, public_url) in url_map {
        let escaped_specifier = regex::escape(specifier);

        // Pattern 1: new URL('specifier', import.meta.url) - single quotes, no .href
        let pattern1 = format!(
            r#"new\s+URL\s*\(\s*'({})'\s*,\s*import\.meta\.url\s*\)"#,
            escaped_specifier
        );
        if let Ok(re) = Regex::new(&pattern1) {
            if re.is_match(&rewritten) {
                rewritten = re
                    .replace_all(&rewritten, format!("'{}'", public_url))
                    .to_string();
                report.replacements += 1;
                report.rewritten_specifiers.push(specifier.clone());
            }
        }

        // Pattern 2: new URL("specifier", import.meta.url) - double quotes, no .href
        let pattern2 = format!(
            r#"new\s+URL\s*\(\s*"({})"\s*,\s*import\.meta\.url\s*\)"#,
            escaped_specifier
        );
        if let Ok(re) = Regex::new(&pattern2) {
            if re.is_match(&rewritten) {
                rewritten = re
                    .replace_all(&rewritten, format!("\"{}\"", public_url))
                    .to_string();
                report.replacements += 1;
                if !report.rewritten_specifiers.contains(specifier) {
                    report.rewritten_specifiers.push(specifier.clone());
                }
            }
        }

        // Pattern 3: new URL(`specifier`, import.meta.url) - template literals, no .href
        let pattern3 = format!(
            r#"new\s+URL\s*\(\s*`({})`\s*,\s*import\.meta\.url\s*\)"#,
            escaped_specifier
        );
        if let Ok(re) = Regex::new(&pattern3) {
            if re.is_match(&rewritten) {
                rewritten = re
                    .replace_all(&rewritten, format!("`{}`", public_url))
                    .to_string();
                report.replacements += 1;
                if !report.rewritten_specifiers.contains(specifier) {
                    report.rewritten_specifiers.push(specifier.clone());
                }
            }
        }

        // Pattern 4: new URL('specifier', import.meta.url).href - single quotes with .href
        let pattern4 = format!(
            r#"new\s+URL\s*\(\s*'({})'\s*,\s*import\.meta\.url\s*\)\s*\.href"#,
            escaped_specifier
        );
        if let Ok(re) = Regex::new(&pattern4) {
            if re.is_match(&rewritten) {
                rewritten = re
                    .replace_all(&rewritten, format!("'{}'", public_url))
                    .to_string();
                report.replacements += 1;
                if !report.rewritten_specifiers.contains(specifier) {
                    report.rewritten_specifiers.push(specifier.clone());
                }
            }
        }

        // Pattern 5: new URL("specifier", import.meta.url).href - double quotes with .href
        let pattern5 = format!(
            r#"new\s+URL\s*\(\s*"({})"\s*,\s*import\.meta\.url\s*\)\s*\.href"#,
            escaped_specifier
        );
        if let Ok(re) = Regex::new(&pattern5) {
            if re.is_match(&rewritten) {
                rewritten = re
                    .replace_all(&rewritten, format!("\"{}\"", public_url))
                    .to_string();
                report.replacements += 1;
                if !report.rewritten_specifiers.contains(specifier) {
                    report.rewritten_specifiers.push(specifier.clone());
                }
            }
        }

        // Pattern 6: new URL(`specifier`, import.meta.url).href - template literals with .href
        let pattern6 = format!(
            r#"new\s+URL\s*\(\s*`({})`\s*,\s*import\.meta\.url\s*\)\s*\.href"#,
            escaped_specifier
        );
        if let Ok(re) = Regex::new(&pattern6) {
            if re.is_match(&rewritten) {
                rewritten = re
                    .replace_all(&rewritten, format!("`{}`", public_url))
                    .to_string();
                report.replacements += 1;
                if !report.rewritten_specifiers.contains(specifier) {
                    report.rewritten_specifiers.push(specifier.clone());
                }
            }
        }
    }

    // Track unused specifiers
    for specifier in url_map.keys() {
        if !report.rewritten_specifiers.contains(specifier) {
            report.unused_specifiers.push(specifier.clone());
        }
    }

    Ok((rewritten, report))
}

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

    #[test]
    fn test_hash_content() {
        let content = b"Hello, World!";
        let hash = hash_content(content);

        // SHA-256 produces 64 hex characters
        assert_eq!(hash.len(), 64);

        // Same content produces same hash
        let hash2 = hash_content(content);
        assert_eq!(hash, hash2);

        // Different content produces different hash
        let hash3 = hash_content(b"Different");
        assert_ne!(hash, hash3);
    }

    #[test]
    fn test_generate_filename() {
        let path = Path::new("file.wasm");
        let hash = "abcd1234567890abcdef";

        let filename = generate_filename(path, hash).unwrap();
        assert_eq!(filename, "file-abcd1234.wasm");
    }

    #[test]
    fn test_generate_filename_no_extension() {
        let path = Path::new("LICENSE");
        let hash = "abcd1234567890abcdef";

        let filename = generate_filename(path, hash).unwrap();
        assert_eq!(filename, "LICENSE-abcd1234");
    }

    #[test]
    fn test_rewrite_urls_basic() {
        let code = r#"
            const url1 = new URL('./file.wasm', import.meta.url);
            const url2 = new URL("./image.png", import.meta.url);
            const url3 = new URL(`./font.woff2`, import.meta.url);
        "#;

        let mut url_map = HashMap::new();
        url_map.insert(
            "./file.wasm".to_string(),
            "/assets/file-abc123.wasm".to_string(),
        );
        url_map.insert(
            "./image.png".to_string(),
            "/assets/image-def456.png".to_string(),
        );
        url_map.insert(
            "./font.woff2".to_string(),
            "/assets/font-ghi789.woff2".to_string(),
        );

        let (rewritten, _report) = rewrite_urls_ast(code, &url_map).unwrap();

        assert!(rewritten.contains("'/assets/file-abc123.wasm'"));
        assert!(rewritten.contains("\"/assets/image-def456.png\""));
        assert!(rewritten.contains("`/assets/font-ghi789.woff2`"));

        // Original patterns should be gone
        assert!(!rewritten.contains("new URL('./file.wasm'"));
        assert!(!rewritten.contains("new URL(\"./image.png\""));
        assert!(!rewritten.contains("new URL(`./font.woff2`"));
    }

    #[test]
    fn test_rewrite_urls_with_href() {
        // Test .href patterns used in dynamic imports
        let code = r#"
            const module = await import(new URL('../wasm/web/joy_bundler_wasm.js', import.meta.url).href);
            const url1 = new URL('./file.wasm', import.meta.url).href;
            const url2 = new URL("./image.png", import.meta.url).href;
            const url3 = new URL(`./font.woff2`, import.meta.url).href;
        "#;

        let mut url_map = HashMap::new();
        url_map.insert(
            "../wasm/web/joy_bundler_wasm.js".to_string(),
            "/__fob_assets__/joy_bundler_wasm.js".to_string(),
        );
        url_map.insert(
            "./file.wasm".to_string(),
            "/__fob_assets__/file.wasm".to_string(),
        );
        url_map.insert(
            "./image.png".to_string(),
            "/__fob_assets__/image.png".to_string(),
        );
        url_map.insert(
            "./font.woff2".to_string(),
            "/__fob_assets__/font.woff2".to_string(),
        );

        let (rewritten, _report) = rewrite_urls_ast(code, &url_map).unwrap();

        // Check that .href patterns are rewritten
        assert!(rewritten.contains("'/__fob_assets__/joy_bundler_wasm.js'"));
        assert!(rewritten.contains("'/__fob_assets__/file.wasm'"));
        assert!(rewritten.contains("\"/__fob_assets__/image.png\""));
        assert!(rewritten.contains("`/__fob_assets__/font.woff2`"));

        // Original patterns should be gone
        assert!(!rewritten.contains("new URL('../wasm/web/joy_bundler_wasm.js'"));
        assert!(!rewritten.contains("new URL('./file.wasm', import.meta.url).href"));
        assert!(!rewritten.contains("new URL(\"./image.png\", import.meta.url).href"));
        assert!(!rewritten.contains("new URL(`./font.woff2`, import.meta.url).href"));
    }

    #[test]
    fn test_rewrite_urls_ast_minified() {
        // Test minified code (no spaces)
        let code = r#"const url=new URL('../wasm/web/joy_bundler_wasm.js',import.meta.url).href;"#;

        let mut url_map = HashMap::new();
        url_map.insert(
            "../wasm/web/joy_bundler_wasm.js".to_string(),
            "/__fob_assets__/joy_bundler_wasm.js".to_string(),
        );

        let (rewritten, report) = rewrite_urls_ast(code, &url_map).unwrap();

        assert_eq!(report.replacements, 1);
        assert!(rewritten.contains("'/__fob_assets__/joy_bundler_wasm.js'"));
        assert!(!rewritten.contains("new URL"));
    }

    #[test]
    fn test_rewrite_urls_ast_spaced() {
        // Test code with extra spaces
        let code =
            r#"const url = new URL ( '../wasm/web/joy_bundler_wasm.js' , import.meta.url ) .href;"#;

        let mut url_map = HashMap::new();
        url_map.insert(
            "../wasm/web/joy_bundler_wasm.js".to_string(),
            "/__fob_assets__/joy_bundler_wasm.js".to_string(),
        );

        let (rewritten, report) = rewrite_urls_ast(code, &url_map).unwrap();

        assert_eq!(report.replacements, 1);
        assert!(rewritten.contains("'/__fob_assets__/joy_bundler_wasm.js'"));
    }

    #[test]
    fn test_rewrite_urls_ast_template_literal() {
        // Test template literal
        let code = r#"const url = new URL(`../wasm/web/joy_bundler_wasm.js`, import.meta.url);"#;

        let mut url_map = HashMap::new();
        url_map.insert(
            "../wasm/web/joy_bundler_wasm.js".to_string(),
            "/__fob_assets__/joy_bundler_wasm.js".to_string(),
        );

        let (rewritten, report) = rewrite_urls_ast(code, &url_map).unwrap();

        assert_eq!(report.replacements, 1);
        assert!(rewritten.contains("`/__fob_assets__/joy_bundler_wasm.js`"));
    }

    #[test]
    fn test_rewrite_urls_ast_preserves_quote_type() {
        // Test that quote types are preserved
        let code = r#"
            const url1 = new URL('./file.wasm', import.meta.url);
            const url2 = new URL("./image.png", import.meta.url);
            const url3 = new URL(`./font.woff2`, import.meta.url);
        "#;

        let mut url_map = HashMap::new();
        url_map.insert("./file.wasm".to_string(), "/assets/file.wasm".to_string());
        url_map.insert("./image.png".to_string(), "/assets/image.png".to_string());
        url_map.insert("./font.woff2".to_string(), "/assets/font.woff2".to_string());

        let (rewritten, report) = rewrite_urls_ast(code, &url_map).unwrap();

        assert_eq!(report.replacements, 3);
        assert!(rewritten.contains("'/assets/file.wasm'"));
        assert!(rewritten.contains("\"/assets/image.png\""));
        assert!(rewritten.contains("`/assets/font.woff2`"));
    }

    #[test]
    fn test_rewrite_urls_ast_unused_specifiers() {
        // Test that unused specifiers are tracked
        let code = r#"const url = new URL('./file.wasm', import.meta.url);"#;

        let mut url_map = HashMap::new();
        url_map.insert("./file.wasm".to_string(), "/assets/file.wasm".to_string());
        url_map.insert("./unused.png".to_string(), "/assets/unused.png".to_string());

        let (_rewritten, report) = rewrite_urls_ast(code, &url_map).unwrap();

        assert_eq!(report.replacements, 1);
        assert_eq!(report.rewritten_specifiers.len(), 1);
        assert_eq!(report.unused_specifiers.len(), 1);
        assert!(
            report
                .unused_specifiers
                .contains(&"./unused.png".to_string())
        );
    }

    #[test]
    fn test_rewrite_urls_ast_empty_map() {
        // Test with empty url_map
        let code = r#"const url = new URL('./file.wasm', import.meta.url);"#;

        let url_map = HashMap::new();

        let (rewritten, report) = rewrite_urls_ast(code, &url_map).unwrap();

        assert_eq!(report.replacements, 0);
        assert_eq!(rewritten, code);
    }

    #[test]
    fn test_process_single_asset() {
        use std::fs;
        use tempfile::TempDir;

        let temp = TempDir::new().unwrap();
        let source_file = temp.path().join("test.wasm");
        let output_dir = temp.path().join("out");

        // Create source asset
        fs::write(&source_file, b"test content").unwrap();
        fs::create_dir(&output_dir).unwrap();

        // Create asset info
        let asset = AssetInfo {
            source_path: source_file.clone(),
            referrer: "index.js".to_string(),
            specifier: "./test.wasm".to_string(),
            content_type: "application/wasm".to_string(),
            size: Some(12),
            url_path: None,
            content_hash: None,
        };

        // Process asset
        let processed = process_single_asset(&asset, &output_dir).unwrap();

        assert_eq!(processed.hash.len(), 64);
        assert!(processed.filename.starts_with("test-"));
        assert!(processed.filename.ends_with(".wasm"));

        // Check output file exists
        let output_file = output_dir.join(&processed.filename);
        assert!(output_file.exists());

        // Verify content and size
        let content = fs::read(&output_file).unwrap();
        assert_eq!(content, b"test content");
        assert_eq!(content.len(), 12);
    }
}