microsoft-webui-press 0.0.26

High-performance Static Site Generator powered by WebUI Framework
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

use serde::Deserialize;

/// Documentation site configuration (read from config.json).
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DocsConfig {
    pub site: SiteConfig,
    pub base_path: String,
    pub content_dir: String,
    #[serde(default = "default_out_dir")]
    pub out_dir: String,
    #[serde(default = "default_public_dir")]
    pub public_dir: String,
    pub css: Option<String>,
    pub theme: Option<String>,
    pub components: Option<Vec<String>>,
    #[serde(default)]
    pub head: Vec<HeadTag>,
    pub nav: Vec<NavLink>,
    pub sidebar: Vec<SidebarSection>,
    #[serde(default)]
    pub sidebar_groups: std::collections::BTreeMap<String, Vec<SidebarSection>>,
    #[serde(default)]
    pub custom_pages: std::collections::HashMap<String, CustomPage>,
    /// Site-owned HTML fragments injected into named template regions before
    /// component discovery and protocol compilation.
    #[serde(default)]
    pub regions: std::collections::BTreeMap<String, RegionConfig>,
    /// Inline JSON object merged into every page's render state. Mutually
    /// exclusive with `stateFile`.
    pub state: Option<serde_json::Value>,
    /// Path (relative to `config.json`) of a JSON object merged into every
    /// page's render state. Mutually exclusive with `state`.
    pub state_file: Option<String>,
    pub hero: Option<HeroConfig>,
    pub footer: Option<FooterConfig>,
    /// Optional JavaScript bundler configuration (overrides defaults).
    pub bundler: Option<BundlerConfig>,
}

/// Site-owned content for one compile-time template region.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RegionConfig {
    /// Inline HTML fragment. Mutually exclusive with `htmlFile`.
    pub html: Option<String>,
    /// HTML fragment path relative to `config.json`. Mutually exclusive with
    /// `html`.
    pub html_file: Option<String>,
    /// Inline JSON object exposed beneath the region's dotted state path.
    /// Mutually exclusive with `stateFile`.
    pub state: Option<serde_json::Value>,
    /// JSON object path relative to `config.json`. Mutually exclusive with
    /// `state`.
    pub state_file: Option<String>,
    /// Optional JavaScript/TypeScript file bundled only on pages where the
    /// region is active.
    pub script_file: Option<String>,
}

fn default_out_dir() -> String {
    "./dist".to_string()
}
fn default_public_dir() -> String {
    "./public".to_string()
}

#[derive(Debug, Deserialize)]
pub struct SiteConfig {
    pub title: String,
    #[serde(default)]
    pub description: String,
}

#[derive(Debug, Deserialize)]
pub struct NavLink {
    pub text: String,
    pub link: String,
    /// Markdown file backing this link, relative to `contentDir` with forward
    /// slashes (e.g. `ai/SKILL.md`). Pages are normally routed by filename, so
    /// this is only needed when a file's name is dictated by an outside
    /// convention and should not leak into the URL.
    #[serde(default)]
    pub source: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct SidebarSection {
    pub title: String,
    pub items: Vec<SidebarItem>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct SidebarItem {
    pub text: String,
    #[serde(default)]
    pub link: String,
    #[serde(default)]
    pub items: Vec<SidebarItem>,
}

#[derive(Debug, Deserialize)]
#[serde(untagged)]
pub enum CustomPage {
    Html(String),
    #[serde(rename_all = "camelCase")]
    Full {
        html: String,
        layout: Option<String>,
        /// Inline state object merged into the page's render state under the
        /// `pageData` key. Mutually exclusive with `state_file`.
        state: Option<serde_json::Value>,
        /// Path (relative to `config.json`) of a JSON file whose contents
        /// are merged into the page's render state under the `pageData` key.
        /// The build pipeline caches each unique file so that pages that share
        /// a state file only read it once. Mutually exclusive with `state`.
        state_file: Option<String>,
        /// Path (relative to `config.json`) of a TypeScript/JavaScript file
        /// to bundle as a per-page script. The file is bundled with esbuild
        /// and a `<script>` tag is appended to the page output.
        script_file: Option<String>,
    },
}

impl CustomPage {
    pub fn html(&self) -> &str {
        match self {
            Self::Html(s) => s,
            Self::Full { html, .. } => html,
        }
    }

    pub fn layout(&self) -> &str {
        match self {
            Self::Html(_) => "doc",
            Self::Full { layout, .. } => layout.as_deref().unwrap_or("doc"),
        }
    }

    pub fn inline_state(&self) -> Option<&serde_json::Value> {
        match self {
            Self::Html(_) => None,
            Self::Full { state, .. } => state.as_ref(),
        }
    }

    pub fn state_file(&self) -> Option<&str> {
        match self {
            Self::Html(_) => None,
            Self::Full { state_file, .. } => state_file.as_deref(),
        }
    }

    pub fn script_file(&self) -> Option<&str> {
        match self {
            Self::Html(_) => None,
            Self::Full { script_file, .. } => script_file.as_deref(),
        }
    }
}

#[derive(Debug, Deserialize)]
pub struct HeroConfig {
    #[serde(default)]
    pub text: Option<String>,
    pub tagline: String,
    #[serde(default)]
    pub manifesto: Option<String>,
    pub actions: Vec<HeroAction>,
    pub features: Vec<HeroFeature>,
}

#[derive(Debug, Deserialize)]
pub struct HeroAction {
    pub text: String,
    pub link: String,
    #[serde(default)]
    pub brand: bool,
}

#[derive(Debug, Deserialize)]
pub struct HeroFeature {
    pub icon: String,
    pub title: String,
    pub description: String,
}

/// An HTML tag to inject into `<head>`.
///
/// JSON format: `{ "tag": "link", "attrs": { "rel": "icon", "href": "/favicon.ico" } }`
/// or with content: `{ "tag": "script", "attrs": { "type": "text/javascript" }, "content": "..." }`
#[derive(Debug, Deserialize)]
pub struct HeadTag {
    pub tag: String,
    #[serde(default)]
    pub attrs: std::collections::BTreeMap<String, String>,
    #[serde(default)]
    pub content: Option<String>,
}

impl HeadTag {
    /// Render this tag as an HTML string.
    pub fn to_html(&self) -> String {
        let mut html = String::with_capacity(128);
        html.push('<');
        html.push_str(&self.tag);
        for (key, value) in &self.attrs {
            html.push(' ');
            html.push_str(key);
            html.push_str("=\"");
            for ch in value.chars() {
                match ch {
                    '"' => html.push_str("&quot;"),
                    '&' => html.push_str("&amp;"),
                    '<' => html.push_str("&lt;"),
                    _ => html.push(ch),
                }
            }
            html.push('"');
        }
        html.push('>');

        if let Some(ref content) = self.content {
            html.push_str(content);
            html.push_str("</");
            html.push_str(&self.tag);
            html.push('>');
        } else if !is_void_element(&self.tag) {
            html.push_str("</");
            html.push_str(&self.tag);
            html.push('>');
        }

        html
    }
}

fn is_void_element(tag: &str) -> bool {
    matches!(
        tag,
        "link" | "meta" | "br" | "hr" | "img" | "input" | "base" | "col" | "embed" | "source"
    )
}

#[derive(Debug, Deserialize)]
pub struct FooterConfig {
    pub html: String,
}

/// JavaScript bundler configuration overrides.
///
/// All fields are optional; sensible defaults are applied when omitted.
/// These settings affect how generated page script entries are bundled into
/// the output `assets/` directory.
#[derive(Debug, Clone, Default, Deserialize)]
pub struct BundlerConfig {
    /// ECMAScript target (e.g. `"es2022"`). Defaults to `"es2022"`.
    pub target: Option<String>,
    /// Packages to treat as external (not bundled).
    #[serde(default)]
    pub external: Vec<String>,
    /// Compile-time constant replacements (e.g. `{ "process.env.NODE_ENV": "\"production\"" }`).
    #[serde(default)]
    pub define: std::collections::HashMap<String, String>,
    /// Module path aliases (e.g. `{ "~": "./src" }`).
    #[serde(default)]
    pub alias: std::collections::HashMap<String, String>,
    /// Additional projection fragments for separately built external bundles.
    #[serde(default, rename = "projectionManifests")]
    pub projection_manifests: Vec<String>,
}

/// A processed page ready for rendering.
pub struct PageDescriptor {
    pub path: String,
    pub is_home: bool,
    pub state: serde_json::Value,
}

/// Build output statistics.
#[allow(dead_code)] // Public lib API; the binary's main.rs does not consume the fields.
pub struct BuildStats {
    pub pages: usize,
    pub protocol_bytes: usize,
}

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

    // --- HeadTag::to_html ------------------------------------------------

    fn tag(name: &str, attrs: &[(&str, &str)], content: Option<&str>) -> HeadTag {
        let mut map = BTreeMap::new();
        for (k, v) in attrs {
            map.insert((*k).to_string(), (*v).to_string());
        }
        HeadTag {
            tag: name.to_string(),
            attrs: map,
            content: content.map(String::from),
        }
    }

    #[test]
    fn head_tag_void_element_has_no_closing_tag() {
        let t = tag("link", &[("rel", "icon"), ("href", "/favicon.ico")], None);
        let html = t.to_html();
        assert!(html.starts_with("<link "), "got {html}");
        assert!(
            !html.contains("</link>"),
            "void element must not close: {html}"
        );
    }

    #[test]
    fn head_tag_non_void_self_closes() {
        let t = tag("script", &[("src", "/app.js")], None);
        let html = t.to_html();
        assert!(html.ends_with("</script>"), "got {html}");
    }

    #[test]
    fn head_tag_with_content_emits_inner() {
        let t = tag("script", &[], Some("console.log('x');"));
        assert_eq!(t.to_html(), "<script>console.log('x');</script>");
    }

    #[test]
    fn head_tag_attribute_order_is_deterministic() {
        // BTreeMap iterates in sorted key order; same input → same output every time.
        let t = tag(
            "meta",
            &[("zz", "last"), ("aa", "first"), ("mm", "mid")],
            None,
        );
        let html = t.to_html();
        let aa = html.find("aa=").expect("aa present");
        let mm = html.find("mm=").expect("mm present");
        let zz = html.find("zz=").expect("zz present");
        assert!(aa < mm && mm < zz, "expected sorted order, got {html}");
    }

    #[test]
    fn head_tag_escapes_attribute_values() {
        let t = tag("meta", &[("content", r#"a"b<c&d"#)], None);
        let html = t.to_html();
        assert!(html.contains("&quot;"), "{html}");
        assert!(html.contains("&lt;"), "{html}");
        assert!(html.contains("&amp;"), "{html}");
    }

    #[test]
    fn head_tag_multiple_runs_produce_identical_output() {
        // Regression: HashMap order non-determinism would have flunked this.
        let t1 = tag(
            "meta",
            &[("a", "1"), ("b", "2"), ("c", "3"), ("d", "4")],
            None,
        );
        let t2 = tag(
            "meta",
            &[("d", "4"), ("c", "3"), ("b", "2"), ("a", "1")],
            None,
        );
        assert_eq!(t1.to_html(), t2.to_html());
    }

    // --- BundlerConfig ---------------------------------------------------

    #[test]
    fn bundler_config_deserializes_all_fields() {
        let json = r#"{
            "target": "es2022",
            "external": ["lodash"],
            "define": { "process.env.NODE_ENV": "\"production\"" },
            "alias": { "~": "./src" },
            "projectionManifests": ["./shared/projection.json"]
        }"#;
        let cfg: BundlerConfig = serde_json::from_str(json).unwrap();
        assert_eq!(cfg.target.as_deref(), Some("es2022"));
        assert_eq!(cfg.external, vec!["lodash"]);
        assert_eq!(
            cfg.define.get("process.env.NODE_ENV").unwrap(),
            "\"production\""
        );
        assert_eq!(cfg.alias.get("~").unwrap(), "./src");
        assert_eq!(cfg.projection_manifests, vec!["./shared/projection.json"]);
    }

    #[test]
    fn bundler_config_defaults_when_empty() {
        let cfg: BundlerConfig = serde_json::from_str("{}").unwrap();
        assert!(cfg.target.is_none());
        assert!(cfg.external.is_empty());
        assert!(cfg.define.is_empty());
        assert!(cfg.alias.is_empty());
        assert!(cfg.projection_manifests.is_empty());
    }

    // --- CustomPage::script_file -------------------------------------------

    #[test]
    fn custom_page_script_file_deserializes() {
        let json = r#"{
            "layout": "full",
            "html": "<my-comp></my-comp>",
            "scriptFile": "./components/my-comp/my-comp.ts"
        }"#;
        let page: CustomPage = serde_json::from_str(json).unwrap();
        assert_eq!(page.script_file(), Some("./components/my-comp/my-comp.ts"));
    }

    #[test]
    fn custom_page_script_file_none_when_absent() {
        let json = r#"{ "layout": "full", "html": "<p>hi</p>" }"#;
        let page: CustomPage = serde_json::from_str(json).unwrap();
        assert!(page.script_file().is_none());
    }

    #[test]
    fn region_config_deserializes_file_backed_content() {
        let config: RegionConfig = serde_json::from_str(
            r#"{
                "htmlFile": "./regions/summary.html",
                "stateFile": "./state/summary.json",
                "scriptFile": "./regions/summary.ts"
            }"#,
        )
        .unwrap();
        assert!(config.html.is_none());
        assert_eq!(config.html_file.as_deref(), Some("./regions/summary.html"));
        assert_eq!(config.state_file.as_deref(), Some("./state/summary.json"));
        assert_eq!(config.script_file.as_deref(), Some("./regions/summary.ts"));
    }
}