ssg 0.0.47

A secure-by-default static site generator built in Rust. WCAG 2.2 AA validation, CSP/SRI hardening, native JS/CSS minification, automated CycloneDX SBOM, local LLM content pipeline, WebAssembly target, interactive islands, streaming compilation for 100K+ pages, 28-locale i18n, and one-command deployment.
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
// Copyright © 2023 - 2026 Static Site Generator (SSG). All rights reserved.
// SPDX-License-Identifier: Apache-2.0 OR MIT

//! Manifest fix plugin.

use super::helpers::{read_meta_sidecars, truncate_at_word};
use crate::error::{PathErrorExt, SsgError};
use crate::plugin::{Plugin, PluginContext};
use std::fs;

/// Fixes manifest.json description truncation by using full text or
/// word-boundary-safe truncation at 200 characters.
#[derive(Debug, Clone, Copy)]
pub struct ManifestFixPlugin;

impl Plugin for ManifestFixPlugin {
    fn name(&self) -> &'static str {
        "manifest-fix"
    }

    fn after_compile(&self, ctx: &PluginContext) -> Result<(), SsgError> {
        let manifest_path = ctx.site_dir.join("manifest.json");
        if !manifest_path.exists() {
            return Ok(());
        }

        let content =
            fs::read_to_string(&manifest_path).with_path(&manifest_path)?;

        let mut manifest: serde_json::Value = serde_json::from_str(&content)
            .map_err(|e| SsgError::io(e, &manifest_path))?;

        let meta_entries =
            read_meta_sidecars(&ctx.site_dir).unwrap_or_default();

        let full_description = find_full_description(&meta_entries);

        if let Some(desc) = full_description {
            let truncated = truncate_at_word(&desc, 200);
            manifest["description"] = serde_json::Value::String(truncated);
        } else if let Some(current) =
            manifest.get("description").and_then(|v| v.as_str())
        {
            if let Some(fixed) = fix_truncated_description(current) {
                manifest["description"] = serde_json::Value::String(fixed);
            }
        }

        // Drop icon entries whose `src` is empty; Chrome logs
        // "Error while trying to use the following icon from the Manifest"
        // when it tries to fetch them.
        drop_empty_icons(&mut manifest);

        let output = serialize_manifest(&manifest)
            .map_err(|e| SsgError::io(e, &manifest_path))?;
        fs::write(&manifest_path, output).with_path(&manifest_path)?;

        log::info!("[manifest-fix] Fixed manifest.json description");
        Ok(())
    }
}

/// Finds the full description from meta sidecars, preferring the root page.
fn find_full_description(
    meta_entries: &[(String, std::collections::HashMap<String, String>)],
) -> Option<String> {
    meta_entries
        .iter()
        .find(|(rel, _)| rel.is_empty() || rel == ".")
        .and_then(|(_, meta)| meta.get("description"))
        .or_else(|| {
            meta_entries
                .iter()
                .find_map(|(_, meta)| meta.get("description"))
        })
        .cloned()
}

/// Removes any entry from the manifest's `icons` array whose `src` is
/// missing or empty. Chrome logs a manifest icon download error for each
/// such entry, even though the manifest itself is otherwise valid.
fn drop_empty_icons(manifest: &mut serde_json::Value) {
    let Some(icons) = manifest.get_mut("icons").and_then(|v| v.as_array_mut())
    else {
        return;
    };
    icons.retain(|icon| {
        icon.get("src")
            .and_then(|s| s.as_str())
            .is_some_and(|s| !s.is_empty())
    });
    if icons.is_empty() {
        // An empty array is preferable to `[{src:""}]` — but if there are
        // truly no usable icons, drop the key entirely so the manifest
        // doesn't advertise an empty icon set. (`get_mut("icons")`
        // succeeding above guarantees this is an object.)
        let _ = manifest.as_object_mut().and_then(|map| map.remove("icons"));
    }
}

/// Serialize the manifest with a fault-injection hook so tests can
/// drive the error branch (pretty-printing a `Value` cannot fail in
/// practice).
fn serialize_manifest(
    manifest: &serde_json::Value,
) -> serde_json::Result<String> {
    fail_point!("postprocess::manifest-serialize", |_| Err(
        <serde_json::Error as serde::ser::Error>::custom(
            "injected: postprocess::manifest-serialize"
        )
    ));
    serde_json::to_string_pretty(manifest)
}

/// Fixes a truncated description by ensuring it ends at a word boundary.
/// Returns `None` if the description already ends with proper punctuation.
fn fix_truncated_description(current: &str) -> Option<String> {
    if current.ends_with('.')
        || current.ends_with('!')
        || current.ends_with('?')
        || current.ends_with("...")
    {
        return None;
    }
    Some(if let Some(last_space) = current.rfind(' ') {
        format!("{}...", &current[..last_space])
    } else {
        format!("{current}...")
    })
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use crate::plugin::PluginContext;
    use anyhow::Result;
    use std::path::Path;
    use tempfile::tempdir;

    fn test_ctx(site_dir: &Path) -> PluginContext {
        crate::test_support::init_logger();
        PluginContext::new(
            Path::new("content"),
            Path::new("build"),
            site_dir,
            Path::new("templates"),
        )
    }

    #[test]
    fn test_drop_empty_icons_removes_empty_src() {
        let mut m: serde_json::Value = serde_json::from_str(
            r#"{"icons":[{"src":"","sizes":"512x512"},{"src":"/icon.svg","sizes":"512x512"}]}"#,
        )
        .unwrap();
        drop_empty_icons(&mut m);
        let icons = m["icons"].as_array().unwrap();
        assert_eq!(icons.len(), 1);
        assert_eq!(icons[0]["src"], "/icon.svg");
    }

    #[test]
    fn test_drop_empty_icons_removes_key_when_all_empty() {
        let mut m: serde_json::Value =
            serde_json::from_str(r#"{"name":"x","icons":[{"src":""}]}"#)
                .unwrap();
        drop_empty_icons(&mut m);
        assert!(m.get("icons").is_none(), "icons key should be dropped");
    }

    #[test]
    fn name_is_stable() {
        assert_eq!(ManifestFixPlugin.name(), "manifest-fix");
    }

    #[test]
    #[serial_test::parallel]
    fn after_compile_no_op_when_manifest_missing() -> Result<()> {
        let tmp = tempdir().unwrap();
        let ctx = test_ctx(tmp.path());
        ManifestFixPlugin.after_compile(&ctx).unwrap();
        assert!(!tmp.path().join("manifest.json").exists());
        Ok(())
    }

    #[test]
    #[serial_test::parallel]
    fn after_compile_returns_error_on_invalid_json() {
        let tmp = tempdir().unwrap();
        fs::write(tmp.path().join("manifest.json"), "not valid json").unwrap();
        let ctx = test_ctx(tmp.path());
        let err = ManifestFixPlugin.after_compile(&ctx).unwrap_err();
        assert!(
            err.to_string().contains("invalid JSON")
                || err.to_string().contains("manifest"),
            "expected JSON parse error, got: {err}"
        );
    }

    #[test]
    fn drop_empty_icons_keeps_array_with_real_entries() {
        let mut m: serde_json::Value = serde_json::from_str(
            r#"{"icons":[{"src":"/a.svg"},{"src":"/b.svg"}]}"#,
        )
        .unwrap();
        drop_empty_icons(&mut m);
        let icons = m["icons"].as_array().unwrap();
        assert_eq!(icons.len(), 2);
    }

    #[test]
    fn drop_empty_icons_no_op_when_no_icons_key() {
        let mut m: serde_json::Value =
            serde_json::from_str(r#"{"name":"x"}"#).unwrap();
        drop_empty_icons(&mut m);
        assert!(m.get("icons").is_none());
        assert_eq!(m["name"], "x");
    }

    #[test]
    fn drop_empty_icons_no_op_when_icons_not_array() {
        // Defensive: malformed manifest with non-array icons.
        let mut m: serde_json::Value =
            serde_json::from_str(r#"{"icons":"not an array"}"#).unwrap();
        drop_empty_icons(&mut m);
        assert_eq!(m["icons"], "not an array");
    }

    #[test]
    fn fix_truncated_description_returns_none_when_already_terminated() {
        assert!(fix_truncated_description("ends with period.").is_none());
        assert!(fix_truncated_description("ends with bang!").is_none());
        assert!(fix_truncated_description("ends with question?").is_none());
        assert!(fix_truncated_description("ends with ellipsis...").is_none());
    }

    #[test]
    fn fix_truncated_description_truncates_at_word_boundary() {
        let out =
            fix_truncated_description("a long description without ending");
        assert_eq!(out.as_deref(), Some("a long description without..."));
    }

    #[test]
    fn fix_truncated_description_no_space_appends_ellipsis() {
        // Edge case: a single very long word without spaces.
        let out = fix_truncated_description("supercalifragilistic");
        assert_eq!(out.as_deref(), Some("supercalifragilistic..."));
    }

    #[test]
    #[serial_test::parallel]
    fn after_compile_drops_empty_icons_in_manifest() -> Result<()> {
        let tmp = tempdir().unwrap();
        let manifest_path = tmp.path().join("manifest.json");
        fs::write(
            &manifest_path,
            r#"{"name":"X","description":"Already terminated.","icons":[{"src":""}]}"#,
        ).unwrap();
        let ctx = test_ctx(tmp.path());
        ManifestFixPlugin.after_compile(&ctx).unwrap();
        let after: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(&manifest_path).unwrap())
                .unwrap();
        assert!(after.get("icons").is_none(), "empty icon should be dropped");
        Ok(())
    }

    #[test]
    #[serial_test::parallel]
    fn test_manifest_fix_repairs_truncated_description() -> Result<()> {
        let tmp = tempdir().unwrap();
        let manifest_path = tmp.path().join("manifest.json");
        fs::write(
            &manifest_path,
            r#"{"name":"Test","description":"A new paper suggests Shor's algorithm could run on as few as 10,000 qubits. The threshold for cryptographically relevant"}"#,
        ).unwrap();

        let ctx = test_ctx(tmp.path());
        ManifestFixPlugin.after_compile(&ctx).unwrap();

        let result = fs::read_to_string(&manifest_path).unwrap();
        let manifest: serde_json::Value =
            serde_json::from_str(&result).unwrap();
        let desc = manifest["description"].as_str().unwrap();
        // Non-short-circuiting `|` so every operand is evaluated.
        let clean =
            desc.ends_with("...") | desc.ends_with('.') | desc.ends_with('!');
        assert!(clean, "Description should end cleanly, got: {desc}");
        Ok(())
    }

    #[test]
    #[serial_test::parallel]
    fn test_manifest_fix_uses_sidecar_description() -> Result<()> {
        let tmp = tempdir().unwrap();
        let manifest_path = tmp.path().join("manifest.json");
        fs::write(
            &manifest_path,
            r#"{"name":"Test","description":"Short description"}"#,
        )
        .unwrap();
        fs::write(
            tmp.path().join("index.meta.json"),
            r#"{"description":"This is a very long description that we are using to test manifest metadata sidecar description truncation logic in the manifest fix plugin. We need to make sure that the total length of this text exceeds two hundred characters so that the truncation is triggered."}"#,
        ).unwrap();

        let ctx = test_ctx(tmp.path());
        ManifestFixPlugin.after_compile(&ctx).unwrap();

        let result = fs::read_to_string(&manifest_path).unwrap();
        let manifest: serde_json::Value =
            serde_json::from_str(&result).unwrap();
        let desc = manifest["description"].as_str().unwrap();
        assert!(desc.starts_with("This is a very long"));
        assert!(desc.ends_with("..."));
        Ok(())
    }

    #[test]
    fn test_find_full_description_fallback() {
        let mut entries = Vec::new();
        let mut meta1 = std::collections::HashMap::new();
        let _ = meta1.insert("title".to_string(), "No description".to_string());
        entries.push(("root".to_string(), meta1));

        let mut meta2 = std::collections::HashMap::new();
        let _ = meta2
            .insert("description".to_string(), "Fallback desc".to_string());
        entries.push(("subpage".to_string(), meta2));

        let desc = find_full_description(&entries);
        assert_eq!(desc.as_deref(), Some("Fallback desc"));
    }

    #[test]
    fn test_find_full_description_none() {
        let mut entries = Vec::new();
        let mut meta1 = std::collections::HashMap::new();
        let _ = meta1.insert("title".to_string(), "No description".to_string());
        entries.push(("root".to_string(), meta1));

        let desc = find_full_description(&entries);
        assert!(desc.is_none());
    }

    // -----------------------------------------------------------------
    // after_compile: manifest without a description key
    // -----------------------------------------------------------------

    #[test]
    #[serial_test::parallel]
    fn after_compile_handles_manifest_without_description() {
        let tmp = tempdir().unwrap();
        let manifest_path = tmp.path().join("manifest.json");
        fs::write(&manifest_path, r#"{"name":"X"}"#).unwrap();
        let ctx = test_ctx(tmp.path());
        ManifestFixPlugin.after_compile(&ctx).unwrap();
        let after: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(&manifest_path).unwrap())
                .unwrap();
        assert!(
            after.get("description").is_none(),
            "no description key must be invented"
        );
    }

    // -----------------------------------------------------------------
    // Error paths
    // -----------------------------------------------------------------

    #[test]
    #[serial_test::parallel]
    fn after_compile_errors_on_invalid_utf8_manifest() {
        let tmp = tempdir().unwrap();
        let manifest_path = tmp.path().join("manifest.json");
        fs::write(&manifest_path, [0xFF, 0xFE, 0xFD]).unwrap();
        let ctx = test_ctx(tmp.path());
        let err = ManifestFixPlugin.after_compile(&ctx).unwrap_err();
        assert!(format!("{err}").contains("manifest.json"));
    }

    #[test]
    #[cfg(unix)]
    fn after_compile_write_failure_on_readonly_manifest() {
        use std::os::unix::fs::PermissionsExt;
        let tmp = tempdir().unwrap();
        let manifest_path = tmp.path().join("manifest.json");
        fs::write(&manifest_path, r#"{"name":"X","description":"Done."}"#)
            .unwrap();
        fs::set_permissions(&manifest_path, fs::Permissions::from_mode(0o444))
            .unwrap();

        let ctx = test_ctx(tmp.path());
        let result = ManifestFixPlugin.after_compile(&ctx);
        let _ = fs::set_permissions(
            &manifest_path,
            fs::Permissions::from_mode(0o644),
        );
        let err = result.unwrap_err();
        assert!(format!("{err}").contains("manifest.json"));
    }
}

#[cfg(all(test, feature = "test-fault-injection"))]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod fault_tests {
    use super::*;
    use crate::plugin::PluginContext;
    use serial_test::serial;
    use std::path::Path;
    use tempfile::tempdir;

    /// RAII guard that disables a failpoint on drop.
    struct FailGuard(&'static str);

    impl Drop for FailGuard {
        fn drop(&mut self) {
            let _ = fail::cfg(self.0, "off");
        }
    }

    #[test]
    #[serial]
    fn after_compile_maps_serialize_failure_to_io_error() {
        let _guard = FailGuard("postprocess::manifest-serialize");
        fail::cfg("postprocess::manifest-serialize", "return")
            .expect("activate failpoint");

        let tmp = tempdir().unwrap();
        fs::write(
            tmp.path().join("manifest.json"),
            r#"{"name":"X","description":"Already terminated."}"#,
        )
        .unwrap();
        crate::test_support::init_logger();
        let ctx = PluginContext::new(
            Path::new("content"),
            Path::new("build"),
            tmp.path(),
            Path::new("templates"),
        );
        let err = ManifestFixPlugin
            .after_compile(&ctx)
            .expect_err("injected serialize failure must propagate");
        let msg = format!("{err}");
        assert!(msg.contains("manifest.json"), "got: {msg}");
        assert!(
            msg.contains("injected: postprocess::manifest-serialize"),
            "got: {msg}"
        );
    }
}