microsoft-webui-wasm 0.0.13

WebAssembly bindings for WebUI framework — powers the online playground
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

//! WebAssembly bindings for the WebUI framework.
//!
//! This crate exposes the WebUI rendering pipeline to JavaScript via `wasm-bindgen`,
//! powering the interactive playground in the documentation site.
//!
//! Two modes of operation:
//! - **`render`** — Takes a pre-built protocol (JSON) + state and renders HTML.
//! - **`build_and_render`** — Takes virtual files + state, parses and renders HTML
//!   using the real `webui-parser` (same parser used by the CLI).

use serde_json::Value;
use std::collections::HashMap;
use wasm_bindgen::prelude::*;
use webui_handler::plugin::fast_v2::FastV2HydrationPlugin;
use webui_handler::plugin::fast_v3::FastV3HydrationPlugin;
use webui_handler::plugin::webui::WebUIHydrationPlugin;
use webui_handler::{RenderOptions, ResponseWriter, WebUIHandler};
use webui_parser::{CssStrategy, HtmlParser, Plugin};
use webui_protocol::WebUIProtocol;

/// A simple string buffer for collecting rendered output.
struct StringWriter {
    content: String,
}

impl StringWriter {
    fn with_capacity(cap: usize) -> Self {
        Self {
            content: String::with_capacity(cap),
        }
    }
}

impl ResponseWriter for StringWriter {
    fn write(&mut self, content: &str) -> webui_handler::Result<()> {
        self.content.push_str(content);
        Ok(())
    }

    fn end(&mut self) -> webui_handler::Result<()> {
        Ok(())
    }
}

/// Render a pre-built WebUI protocol with state data.
///
/// # Arguments
///
/// * `protocol_json` — JSON string of the serialized `WebUIProtocol`.
/// * `state_json` — JSON string of the state data.
/// * `plugin` — Optional plugin identifier (see crate documentation for available identifiers).
///
/// # Returns
///
/// The rendered HTML string, or throws a JS error on failure.
#[wasm_bindgen]
pub fn render(
    protocol_json: &str,
    state_json: &str,
    entry: &str,
    request_path: &str,
    plugin: Option<String>,
) -> Result<String, JsValue> {
    let plugin = plugin
        .map(|s| s.parse::<Plugin>())
        .transpose()
        .map_err(|e| JsValue::from_str(&e))?;
    render_inner(protocol_json, state_json, entry, request_path, plugin)
        .map_err(|e| JsValue::from_str(&e.to_string()))
}

/// Build and render a WebUI application from virtual files.
///
/// Uses a lightweight pure-Rust parser suitable for the playground.
/// Handles signals, for-loops, if-conditions, components, and dynamic attributes.
///
/// # Arguments
///
/// * `files` — A JS object mapping filenames to their string content.
///   Example: `{ "index.html": "<h1>{{title}}</h1>", "my-card.html": "<p><slot></slot></p>" }`
/// * `state_json` — A JSON string of the state data to render with.
/// * `entry` — The entry HTML filename (e.g. `"index.html"`).
///
/// # Returns
///
/// The rendered HTML string, or throws a JS error on failure.
#[wasm_bindgen]
pub fn build_and_render(
    files: JsValue,
    state_json: &str,
    entry: &str,
    request_path: &str,
) -> Result<String, JsValue> {
    let files_map: HashMap<String, String> =
        serde_wasm_bindgen::from_value(files).map_err(|e| JsValue::from_str(&e.to_string()))?;

    build_and_render_inner(&files_map, state_json, entry, request_path)
        .map_err(|e| JsValue::from_str(&e.to_string()))
}

/// Build the protocol JSON from virtual files without rendering.
///
/// Returns the serialized `WebUIProtocol` as a JSON string.
#[wasm_bindgen]
pub fn build_protocol(files: JsValue, entry: &str) -> Result<String, JsValue> {
    let files_map: HashMap<String, String> =
        serde_wasm_bindgen::from_value(files).map_err(|e| JsValue::from_str(&e.to_string()))?;

    build_protocol_inner(&files_map, entry).map_err(|e| JsValue::from_str(&e.to_string()))
}

/// Produce a complete JSON partial response for client-side navigation.
///
/// Combines application state, route templates, inventory, request path, and
/// matched route chain into a single JSON string:
/// `{"state":{...},"templates":[...],"inventory":"...","path":"...","chain":[...]}`.
///
/// Host servers return this directly — no assembly required.
#[wasm_bindgen]
pub fn render_partial(
    protocol_json: &str,
    state_json: &str,
    entry_id: &str,
    request_path: &str,
    inventory_hex: &str,
) -> Result<String, JsValue> {
    let protocol: WebUIProtocol = serde_json::from_str(protocol_json)
        .map_err(|e| JsValue::from_str(&format!("Protocol JSON error: {e}")))?;

    let state: serde_json::Value = serde_json::from_str(state_json)
        .map_err(|e| JsValue::from_str(&format!("invalid state JSON: {e}")))?;

    // TODO: ProtocolIndex is created per-request here. Ideally the host should
    // cache it alongside the protocol — it's deterministic per protocol.
    let mut index = webui_handler::route_handler::ProtocolIndex::new(&protocol);

    let mut result = webui_handler::route_handler::render_partial(
        &protocol,
        entry_id,
        request_path,
        inventory_hex,
        &mut index,
    )
    .map_err(|e| JsValue::from_str(&format!("render_partial failed: {e}")))?;
    if let Some(obj) = result.as_object_mut() {
        obj.insert("state".into(), state);
    }

    serde_json::to_string(&result)
        .map_err(|e| JsValue::from_str(&format!("JSON serialize error: {e}")))
}

/// Extract the CSS token name list from a protocol JSON string.
///
/// Returns a JavaScript array of token name strings, preserving the original
/// order from the build step.
#[wasm_bindgen]
pub fn protocol_tokens(protocol_json: &str) -> Result<JsValue, JsValue> {
    let protocol: WebUIProtocol = serde_json::from_str(protocol_json)
        .map_err(|e| JsValue::from_str(&format!("Protocol JSON error: {e}")))?;

    serde_wasm_bindgen::to_value(&protocol.tokens)
        .map_err(|e| JsValue::from_str(&format!("Serialization error: {e}")))
}

#[wasm_bindgen]
pub fn render_component_templates(
    protocol_json: &str,
    component_tags_json: &str,
    inventory_hex: &str,
) -> Result<String, JsValue> {
    let protocol: WebUIProtocol = serde_json::from_str(protocol_json)
        .map_err(|e| JsValue::from_str(&format!("Protocol JSON error: {e}")))?;

    let tags: Vec<String> = serde_json::from_str(component_tags_json)
        .map_err(|e| JsValue::from_str(&format!("invalid tags JSON: {e}")))?;
    let tag_refs: Vec<&str> = tags.iter().map(|s| s.as_str()).collect();

    // Per-request index — see ProtocolIndex doc for caching guidance.
    let index = webui_handler::route_handler::ProtocolIndex::new(&protocol);

    let result = webui_handler::route_handler::render_component_templates(
        &protocol,
        &tag_refs,
        inventory_hex,
        &index,
    )
    .map_err(|e| JsValue::from_str(&format!("render_component_templates failed: {e}")))?;

    serde_json::to_string(&result)
        .map_err(|e| JsValue::from_str(&format!("JSON serialize error: {e}")))
}

fn build_protocol_inner(
    files: &HashMap<String, String>,
    entry: &str,
) -> Result<String, BuildError> {
    let protocol = parse_to_protocol(files, entry)?;
    serde_json::to_string(&protocol).map_err(BuildError::Protocol)
}

/// Create a handler with an optional plugin.
fn create_handler(plugin: Option<Plugin>) -> Result<WebUIHandler, BuildError> {
    match plugin {
        Some(Plugin::Fast | Plugin::FastV2) => Ok(WebUIHandler::with_plugin(|| {
            Box::new(FastV2HydrationPlugin::new())
        })),
        Some(Plugin::FastV3) => Ok(WebUIHandler::with_plugin(|| {
            Box::new(FastV3HydrationPlugin::new())
        })),
        Some(Plugin::WebUI) => Ok(WebUIHandler::with_plugin(|| {
            Box::new(WebUIHydrationPlugin::new())
        })),
        None => Ok(WebUIHandler::new()),
    }
}

fn render_inner(
    protocol_json: &str,
    state_json: &str,
    entry: &str,
    request_path: &str,
    plugin: Option<Plugin>,
) -> Result<String, BuildError> {
    let protocol: WebUIProtocol =
        serde_json::from_str(protocol_json).map_err(BuildError::Protocol)?;
    let state: Value = serde_json::from_str(state_json).map_err(BuildError::State)?;

    let mut writer = StringWriter::with_capacity(1024);
    let handler = create_handler(plugin)?;
    handler.render(
        &protocol,
        &state,
        &RenderOptions::new(entry, request_path),
        &mut writer,
    )?;

    Ok(writer.content)
}

/// Core build-and-render implementation (testable without WASM).
pub(crate) fn build_and_render_inner(
    files: &HashMap<String, String>,
    state_json: &str,
    entry: &str,
    request_path: &str,
) -> Result<String, BuildError> {
    let protocol = parse_to_protocol(files, entry)?;

    let state: Value = serde_json::from_str(state_json).map_err(BuildError::State)?;

    let mut writer = StringWriter::with_capacity(1024);
    let handler = create_handler(None)?;
    handler.render(
        &protocol,
        &state,
        &RenderOptions::new(entry, request_path),
        &mut writer,
    )?;

    Ok(writer.content)
}

/// Parse virtual files into a `WebUIProtocol` using the real `webui-parser`.
fn parse_to_protocol(
    files: &HashMap<String, String>,
    entry: &str,
) -> Result<WebUIProtocol, BuildError> {
    let entry_html = files
        .get(entry)
        .ok_or_else(|| BuildError::MissingEntry(entry.to_string()))?;

    let mut parser = HtmlParser::new();
    parser.set_css_strategy(CssStrategy::Style);

    // Register components from virtual files (no filesystem needed)
    for (filename, content) in files {
        if filename != entry && filename.ends_with(".html") {
            let tag_name = filename.trim_end_matches(".html");
            if tag_name.contains('-') {
                let css_key = format!("{tag_name}.css");
                let css = files.get(&css_key).map(|s| s.as_str());
                parser
                    .component_registry_mut()
                    .register_component(tag_name, content, css)?;
            }
        }
    }

    parser.parse(entry, entry_html)?;

    Ok(WebUIProtocol::new(parser.into_fragment_records()))
}

/// Errors from the build-and-render pipeline.
#[derive(Debug, thiserror::Error)]
pub(crate) enum BuildError {
    #[error("Entry file '{0}' not found")]
    MissingEntry(String),

    #[error("{0}")]
    Parse(#[from] webui_parser::ParserError),

    #[error("Protocol JSON error: {0}")]
    Protocol(serde_json::Error),

    #[error("State JSON error: {0}")]
    State(serde_json::Error),

    #[error("{0}")]
    Render(#[from] webui_handler::HandlerError),
}

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

    #[test]
    fn test_simple_render() {
        let mut files = HashMap::new();
        files.insert(
            "index.html".to_string(),
            "<h1>Hello, {{name}}!</h1>".to_string(),
        );

        let result = build_and_render_inner(&files, r#"{"name": "WebUI"}"#, "index.html", "/");
        assert_eq!(result.unwrap(), "<h1>Hello, WebUI!</h1>");
    }

    #[test]
    fn test_missing_entry_file() {
        let files = HashMap::new();
        let result = build_and_render_inner(&files, "{}", "index.html", "/");
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("not found"), "Unexpected error: {}", err);
    }

    #[test]
    fn test_with_component() {
        let mut files = HashMap::new();
        files.insert(
            "index.html".to_string(),
            "<my-card>World</my-card>".to_string(),
        );
        files.insert(
            "my-card.html".to_string(),
            "<div class=\"card\"><slot></slot></div>".to_string(),
        );

        let result = build_and_render_inner(&files, "{}", "index.html", "/");
        assert!(result.is_ok(), "Render failed: {:?}", result);
        let html = result.as_deref().unwrap_or("");
        assert!(html.contains("card"), "Expected card class in: {}", html);
    }

    #[test]
    fn test_with_for_loop() {
        let mut files = HashMap::new();
        files.insert(
            "index.html".to_string(),
            "<for each=\"item in items\">{{item.name}}, </for>".to_string(),
        );

        let state = r#"{"items": [{"name": "A"}, {"name": "B"}]}"#;
        let result = build_and_render_inner(&files, state, "index.html", "/");
        assert!(result.is_ok(), "Render failed: {:?}", result);
        let html = result.as_deref().unwrap_or("");
        assert!(html.contains("A"), "Expected 'A' in: {}", html);
        assert!(html.contains("B"), "Expected 'B' in: {}", html);
    }

    #[test]
    fn test_with_if_condition() {
        let mut files = HashMap::new();
        files.insert(
            "index.html".to_string(),
            "<if condition=\"show\">Visible</if>".to_string(),
        );

        let result_true = build_and_render_inner(&files, r#"{"show": true}"#, "index.html", "/");
        assert_eq!(result_true.unwrap(), "Visible");

        let result_false = build_and_render_inner(&files, r#"{"show": false}"#, "index.html", "/");
        assert_eq!(result_false.unwrap(), "");
    }

    #[test]
    fn test_invalid_state_json() {
        let mut files = HashMap::new();
        files.insert("index.html".to_string(), "<p>Hi</p>".to_string());

        let result = build_and_render_inner(&files, "not json", "index.html", "/");
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("State JSON error"),
            "Unexpected error: {}",
            err
        );
    }

    #[test]
    fn test_component_with_css() {
        let mut files = HashMap::new();
        files.insert(
            "index.html".to_string(),
            "<my-card>Content</my-card>".to_string(),
        );
        files.insert(
            "my-card.html".to_string(),
            "<p><slot></slot></p>".to_string(),
        );
        files.insert("my-card.css".to_string(), "p { color: red; }".to_string());

        let result = build_and_render_inner(&files, "{}", "index.html", "/");
        assert!(result.is_ok(), "Render failed: {:?}", result);
        let html = result.as_deref().unwrap_or("");
        // WASM uses CssStrategy::Style, so CSS should be in <style> tags, not <link>
        assert!(
            html.contains("<style>p { color: red; }</style>"),
            "Expected inline <style> tag in: {}",
            html
        );
        assert!(
            !html.contains("<link"),
            "Should not have external <link> tag in: {}",
            html
        );
    }

    #[test]
    fn test_raw_signal() {
        let mut files = HashMap::new();
        files.insert(
            "index.html".to_string(),
            "<div>{{{raw_html}}}</div>".to_string(),
        );

        let result =
            build_and_render_inner(&files, r#"{"raw_html": "<b>bold</b>"}"#, "index.html", "/");
        assert!(result.is_ok(), "Render failed: {:?}", result);
        let html = result.as_deref().unwrap_or("");
        assert!(
            html.contains("<b>bold</b>"),
            "Expected raw HTML in: {}",
            html
        );
    }

    #[test]
    fn test_static_html_passthrough() {
        let mut files = HashMap::new();
        files.insert(
            "index.html".to_string(),
            "<h1>Static</h1><p>Content</p>".to_string(),
        );

        let result = build_and_render_inner(&files, "{}", "index.html", "/");
        assert_eq!(result.unwrap(), "<h1>Static</h1><p>Content</p>");
    }

    #[test]
    fn test_protocol_tokens_empty() {
        let protocol = WebUIProtocol::new(HashMap::new());
        let json = serde_json::to_string(&protocol).unwrap();
        let decoded: WebUIProtocol = serde_json::from_str(&json).unwrap();
        assert!(decoded.tokens.is_empty());
    }

    #[test]
    fn test_protocol_tokens_roundtrip() {
        let tokens = vec![
            "colorBrandBackground".to_string(),
            "fontSizeBase300".to_string(),
        ];
        let protocol = WebUIProtocol::with_tokens(HashMap::new(), tokens.clone());
        let json = serde_json::to_string(&protocol).unwrap();
        let decoded: WebUIProtocol = serde_json::from_str(&json).unwrap();
        assert_eq!(decoded.tokens, tokens);
    }

    #[test]
    fn test_protocol_tokens_preserves_order() {
        let tokens = vec!["zeta".to_string(), "alpha".to_string(), "zeta".to_string()];
        let protocol = WebUIProtocol::with_tokens(HashMap::new(), tokens.clone());
        let json = serde_json::to_string(&protocol).unwrap();
        let decoded: WebUIProtocol = serde_json::from_str(&json).unwrap();
        assert_eq!(decoded.tokens, tokens);
    }
}