rs-web 0.4.3

A fast, Lua-driven static site generator with encryption support
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
//! Font processing module (rs.fonts)
//!
//! Provides:
//! - rs.fonts.download_google_font(family, options) - Download Google Font files
//!
//! Options:
//!   fonts_dir  (required) where to write woff2 files
//!   css_path   (required) where to write the @font-face CSS
//!   css_prefix URL prefix for rewritten font URLs (default "/fonts")
//!   weights    list of weights (default {400}); ignored when `axes` is set
//!   axes       full Google CSS2 axes spec, e.g. "ital,wght@0,400;0,500;1,400"
//!              or "ital,opsz,wght@0,6..72,400;0,6..72,500;1,6..72,400".
//!              When set, takes precedence over `weights` and unlocks italic,
//!              optical-size, and other variable axes.
//!   subsets    list of subset labels to keep (e.g. {"latin","latin-ext"}).
//!              Google emits each @font-face under a `/* <subset> */` comment;
//!              non-matching blocks are dropped before woff2 fetch, so the
//!              skipped Vietnamese / Cyrillic / Greek files never download.
//!   display    font-display value (default "swap")
//!   minify     minify generated CSS (default true)
//!   cache      true | false | path (default true)

use crate::assets::minify_css;
use crate::lua::async_io::{AsyncIOTask, CacheOption, runtime};
use crate::tracker::SharedTracker;
use mlua::{Lua, Result, Table, Value};
use regex::Regex;
use std::path::{Path, PathBuf};

/// Create the rs.fonts module table
pub fn create_module(lua: &Lua, project_root: &Path, tracker: SharedTracker) -> Result<Table> {
    let fonts_module = lua.create_table()?;
    let root = project_root.to_path_buf();

    // rs.fonts.download_google_font(family, options) - Download Google Font files (async)
    // options: { fonts_dir, css_path, css_prefix?, weights?, display?, cache?, minify? }
    // Returns: AsyncIOTask handle - call rs.async.await() to wait for completion
    let root_clone = root.clone();
    let tracker_clone = tracker.clone();
    let download_google_font_fn =
        lua.create_function(move |_lua, (family, options): (String, Table)| {
            // Required: fonts_dir and css_path
            let fonts_dir_str: String = options.get("fonts_dir").map_err(|_| {
                mlua::Error::external("download_google_font: 'fonts_dir' is required")
            })?;
            let css_path_str: String = options.get("css_path").map_err(|_| {
                mlua::Error::external("download_google_font: 'css_path' is required")
            })?;

            // Optional: css_prefix (URL prefix for fonts in CSS), defaults to "/fonts"
            let css_prefix: String = options
                .get::<String>("css_prefix")
                .unwrap_or_else(|_| "/fonts".to_string());

            // Optional: weights
            let weights: Vec<u32> = options
                .get::<Table>("weights")
                .ok()
                .map(|table| {
                    table
                        .pairs::<i64, u32>()
                        .filter_map(|pair| pair.ok().map(|(_, v)| v))
                        .collect()
                })
                .unwrap_or_else(|| vec![400]);

            // Optional: axes - full Google CSS2 spec like "ital,wght@0,400;1,400".
            // When provided, overrides `weights` for the URL.
            let axes: Option<String> = options.get::<String>("axes").ok();

            // Optional: subsets - list of subset labels to keep ("latin",
            // "latin-ext", "vietnamese", ...). Empty/missing means keep all.
            let subsets: Vec<String> = options
                .get::<Table>("subsets")
                .ok()
                .map(|table| {
                    table
                        .pairs::<i64, String>()
                        .filter_map(|pair| pair.ok().map(|(_, v)| v))
                        .collect()
                })
                .unwrap_or_default();

            // Optional: display
            let display: String = options
                .get::<String>("display")
                .unwrap_or_else(|_| "swap".to_string());

            // Optional: minify CSS output (default: true)
            let minify: bool = options
                .get::<Option<bool>>("minify")
                .ok()
                .flatten()
                .unwrap_or(true);

            // Optional: cache (bool or string path), defaults to true
            let cache_option = match options.get::<Value>("cache") {
                Ok(Value::Boolean(b)) => {
                    if b {
                        CacheOption::Auto
                    } else {
                        CacheOption::Disabled
                    }
                }
                Ok(Value::String(s)) => match s.to_str() {
                    Ok(borrowed) if !borrowed.is_empty() => {
                        let path_str = borrowed.to_string();
                        let path = if Path::new(&path_str).is_absolute() {
                            PathBuf::from(&path_str)
                        } else {
                            root_clone.join(&path_str)
                        };
                        CacheOption::Path(path)
                    }
                    _ => CacheOption::Auto,
                },
                _ => CacheOption::Auto,
            };

            // Resolve paths
            let fonts_dir = if Path::new(&fonts_dir_str).is_absolute() {
                PathBuf::from(&fonts_dir_str)
            } else {
                root_clone.join(&fonts_dir_str)
            };

            let css_path = if Path::new(&css_path_str).is_absolute() {
                PathBuf::from(&css_path_str)
            } else {
                root_clone.join(&css_path_str)
            };

            // Build Google Fonts CSS URL.
            // Prefer the explicit `axes` spec (supports italic, opsz, etc.);
            // otherwise fall back to the legacy `wght@{weights}` form.
            let family_encoded = family.replace(' ', "+");
            let axes_part = match &axes {
                Some(a) if !a.is_empty() => a.clone(),
                _ => format!(
                    "wght@{}",
                    weights
                        .iter()
                        .map(|w| w.to_string())
                        .collect::<Vec<_>>()
                        .join(";")
                ),
            };
            let css_url = format!(
                "https://fonts.googleapis.com/css2?family={}:{}&display={}",
                family_encoded, axes_part, display
            );

            let project_root = root_clone.clone();
            let tracker = tracker_clone.clone();
            let minify_opt = minify;
            let subset_filter = subsets;

            // Spawn async task
            let handle = runtime().spawn(async move {
                // Fetch CSS with Chrome UA
                let raw_css =
                    fetch_google_fonts_css_async(&css_url, &project_root, &cache_option).await?;

                // Subset filter: drop @font-face blocks whose preceding
                // `/* <subset> */` comment isn't in the allow-list. Skipping
                // here means the corresponding woff2 URLs never get fetched.
                let css = filter_subsets(&raw_css, &subset_filter);

                // Create fonts directory
                tokio::fs::create_dir_all(&fonts_dir)
                    .await
                    .map_err(|e| format!("Failed to create fonts directory: {}", e))?;

                // Parse CSS for font URLs
                let url_regex = Regex::new(r"url\(([^)]+)\)").unwrap();
                let mut local_css = css.clone();

                // Collect all font URLs and filenames
                let font_entries: Vec<(String, String)> = url_regex
                    .captures_iter(&css)
                    .filter_map(|cap| {
                        let font_url = cap[1].to_string();
                        extract_font_filename(&font_url).map(|filename| (font_url, filename))
                    })
                    .collect();

                // Fetch all fonts concurrently
                let client = reqwest::Client::new();
                let font_futures: Vec<_> = font_entries
                    .iter()
                    .map(|(url, filename)| {
                        let client = client.clone();
                        let url = url.clone();
                        let filename = filename.clone();
                        let cache_path = get_cache_path(&url, &project_root, &cache_option);
                        async move {
                            // Check cache first
                            if let Some(ref path) = cache_path
                                && let Ok(cached) = tokio::fs::read(path).await
                            {
                                return (url, filename, Ok(cached));
                            }

                            // Fetch from network
                            let result = match client.get(&url).send().await {
                                Ok(resp) if resp.status().is_success() => {
                                    match resp.bytes().await {
                                        Ok(bytes) => {
                                            let data = bytes.to_vec();
                                            // Write to cache
                                            if let Some(ref path) = cache_path {
                                                if let Some(parent) = path.parent() {
                                                    let _ = tokio::fs::create_dir_all(parent).await;
                                                }
                                                let _ = tokio::fs::write(path, &data).await;
                                            }
                                            Ok(data)
                                        }
                                        Err(e) => Err(e.to_string()),
                                    }
                                }
                                Ok(resp) => Err(format!("HTTP {}", resp.status())),
                                Err(e) => Err(e.to_string()),
                            };
                            (url, filename, result)
                        }
                    })
                    .collect();

                let font_results = futures::future::join_all(font_futures).await;

                // Write fonts and update CSS
                let mut write_tasks: Vec<(PathBuf, Vec<u8>)> = Vec::new();
                for (font_url, filename, result) in font_results {
                    match result {
                        Ok(font_data) => {
                            let font_path = fonts_dir.join(&filename);
                            write_tasks.push((font_path, font_data));

                            // Update CSS to use local path
                            let css_prefix_clean = css_prefix.trim_end_matches('/');
                            local_css = local_css
                                .replace(&font_url, &format!("{}/{}", css_prefix_clean, filename));

                            log::info!("Downloaded font: {}", filename);
                        }
                        Err(e) => {
                            log::warn!("Failed to download font {}: {}", font_url, e);
                        }
                    }
                }

                // Write all font files concurrently
                let write_futures: Vec<_> = write_tasks
                    .iter()
                    .map(|(path, data)| tokio::fs::write(path, data))
                    .collect();
                let write_results = futures::future::join_all(write_futures).await;
                for (i, result) in write_results.into_iter().enumerate() {
                    if let Err(e) = result {
                        log::warn!("Failed to write font file: {}", e);
                    } else {
                        // Track the write
                        let (path, data) = &write_tasks[i];
                        let canonical = path.canonicalize().unwrap_or_else(|_| path.clone());
                        tracker.record_write(canonical, data);
                    }
                }

                // Create CSS parent directory if needed
                if let Some(parent) = css_path.parent() {
                    tokio::fs::create_dir_all(parent)
                        .await
                        .map_err(|e| format!("Failed to create CSS directory: {}", e))?;
                }

                // Minify CSS if requested (default: true)
                let final_css = if minify_opt {
                    minify_css(&local_css).unwrap_or_else(|_| local_css.clone())
                } else {
                    local_css
                };

                // Write CSS file
                tokio::fs::write(&css_path, &final_css)
                    .await
                    .map_err(|e| format!("Failed to write CSS: {}", e))?;

                // Track the CSS write
                let canonical = css_path.canonicalize().unwrap_or(css_path.clone());
                tracker.record_write(canonical, final_css.as_bytes());

                log::info!("Saved CSS for {} to {:?}", family, css_path);

                Ok(())
            });

            Ok(AsyncIOTask::new(handle))
        })?;
    fonts_module.set("download_google_font", download_google_font_fn)?;

    Ok(fonts_module)
}

/// Generate cache path from URL and cache option
fn get_cache_path(url: &str, project_root: &Path, cache_option: &CacheOption) -> Option<PathBuf> {
    use std::hash::{Hash, Hasher};
    use twox_hash::XxHash64;

    match cache_option {
        CacheOption::Disabled => None,
        CacheOption::Auto => {
            let mut hasher = XxHash64::with_seed(0);
            url.hash(&mut hasher);
            let hash = hasher.finish();
            Some(
                project_root
                    .join(".rs-web-cache/downloads")
                    .join(format!("{:016x}", hash)),
            )
        }
        CacheOption::Path(base_path) => {
            let mut hasher = XxHash64::with_seed(0);
            url.hash(&mut hasher);
            let hash = hasher.finish();
            Some(base_path.join(format!("{:016x}", hash)))
        }
    }
}

/// Fetch Google Fonts CSS with Chrome User-Agent (async with caching)
async fn fetch_google_fonts_css_async(
    url: &str,
    project_root: &Path,
    cache_option: &CacheOption,
) -> std::result::Result<String, String> {
    // Check cache first
    let cache_path = get_cache_path(url, project_root, cache_option);
    if let Some(ref path) = cache_path
        && let Ok(cached) = tokio::fs::read_to_string(path).await
    {
        log::debug!("Using cached Google Fonts CSS: {:?}", path);
        return Ok(cached);
    }

    let client = reqwest::Client::new();
    let resp = client
        .get(url)
        .header(
            "User-Agent",
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
        )
        .send()
        .await
        .map_err(|e| e.to_string())?;

    if !resp.status().is_success() {
        return Err(format!("HTTP {}", resp.status()));
    }

    let text = resp.text().await.map_err(|e| e.to_string())?;

    // Write to cache if enabled
    if let Some(ref path) = cache_path {
        if let Some(parent) = path.parent() {
            let _ = tokio::fs::create_dir_all(parent).await;
        }
        let _ = tokio::fs::write(path, &text).await;
        log::debug!("Cached Google Fonts CSS: {:?}", path);
    }

    Ok(text)
}

/// Keep only `@font-face` blocks whose preceding `/* <subset> */` comment is in
/// the allow-list. Empty list means no filtering (return original CSS).
fn filter_subsets(css: &str, allow: &[String]) -> String {
    if allow.is_empty() {
        return css.to_string();
    }
    let allow_set: std::collections::HashSet<&str> = allow.iter().map(|s| s.as_str()).collect();

    // Match `/* subset */\s*@font-face { ... }`. Stops at the first `}` because
    // @font-face blocks in Google's output never contain nested braces.
    let re = Regex::new(r"/\*\s*([\w-]+)\s*\*/\s*(@font-face\s*\{[^}]*\})").unwrap();
    let mut out = String::with_capacity(css.len());
    for cap in re.captures_iter(css) {
        let label = &cap[1];
        if allow_set.contains(label) {
            out.push_str(&cap[2]);
            out.push('\n');
        }
    }
    out
}

/// Extract filename from Google Fonts URL
fn extract_font_filename(url: &str) -> Option<String> {
    if let Some(pos) = url.rfind('/') {
        let path = &url[pos + 1..];
        if let Some(ext_pos) = path.find(".woff2") {
            return Some(path[..ext_pos + 6].to_string());
        }
        if let Some(ext_pos) = path.find(".ttf") {
            return Some(path[..ext_pos + 4].to_string());
        }
        if let Some(ext_pos) = path.find(".woff") {
            return Some(path[..ext_pos + 5].to_string());
        }
    }
    None
}