microsoft-webui-ffi 0.0.1

Core FFI bindings for 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
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

//! WebUI FFI (Foreign Function Interface) for interoperability with other languages.
//!
//! This crate provides C-compatible APIs for the WebUI handler to be used from languages
//! like Go, C#, Python, etc.
//!
//! ## Quick Start
//!
//! The simplest way to render an HTML template with data:
//!
//! ```c
//! char *result = webui_render("<h1>{{title}}</h1>", "{\"title\":\"Hello\"}");
//! if (result == NULL) {
//!     const char *err = webui_last_error();
//!     // handle error...
//! } else {
//!     // use result...
//!     webui_free(result);
//! }
//! ```
//!
//! ## Error Handling
//!
//! All functions that can fail return `NULL` on error. Call [`webui_last_error`] to
//! retrieve a human-readable error message. The error string is valid until the next
//! FFI call on the same thread (follows the POSIX `dlerror()` pattern).

use serde_json::Value;
use std::cell::RefCell;
use std::ffi::{CStr, CString};
use std::os::raw::{c_char, c_void};
use webui_handler::plugin::FastHydrationPlugin;
use webui_handler::{RenderOptions, ResponseWriter, WebUIHandler};
use webui_parser::HtmlParser;
use webui_protocol::WebUIProtocol;

// ---------------------------------------------------------------------------
// Thread-local error storage (POSIX dlerror() pattern)
// ---------------------------------------------------------------------------

thread_local! {
    /// Stores the last error message for the current thread.
    static LAST_ERROR: RefCell<Option<CString>> = const { RefCell::new(None) };
}

/// Record an error message so that `webui_last_error()` can return it.
fn set_last_error(msg: impl Into<String>) {
    let mut bytes = msg.into().into_bytes();
    if let Some(nul_pos) = bytes.iter().position(|byte| *byte == 0) {
        bytes.truncate(nul_pos);
    }

    // SAFETY: Any interior NUL byte was removed by truncating at its first position.
    let c_string = unsafe { CString::from_vec_unchecked(bytes) };
    LAST_ERROR.with(|cell| {
        cell.replace(Some(c_string));
    });
}

/// Clear any previously stored error.
fn clear_last_error() {
    LAST_ERROR.with(|cell| {
        cell.replace(None);
    });
}

// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------

/// Opaque context wrapping a `WebUIHandler`.
struct HandlerContext {
    handler: WebUIHandler,
}

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

impl StringResponseWriter {
    fn new() -> Self {
        Self {
            content: String::new(),
        }
    }
}

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

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

// ---------------------------------------------------------------------------
// FFI: error reporting
// ---------------------------------------------------------------------------

/// Return the last error message, or `NULL` if no error has occurred.
///
/// The returned pointer is valid until the next FFI call **on the same thread**.
/// Callers **must not** free the returned pointer.
///
/// # Thread Safety
///
/// Each thread has its own independent error state.
#[no_mangle]
pub extern "C" fn webui_last_error() -> *const c_char {
    LAST_ERROR.with(|cell| {
        let borrow = cell.borrow();
        match borrow.as_ref() {
            Some(c_str) => c_str.as_ptr(),
            None => std::ptr::null(),
        }
    })
}

// ---------------------------------------------------------------------------
// FFI: handler lifecycle
// ---------------------------------------------------------------------------

/// Create a new WebUI handler instance.
///
/// Returns an opaque pointer that must be passed to other `webui_handler_*`
/// functions and eventually freed with [`webui_handler_destroy`].
#[no_mangle]
pub extern "C" fn webui_handler_create() -> *mut c_void {
    let handler = WebUIHandler::new();
    let context = Box::new(HandlerContext { handler });
    Box::into_raw(context) as *mut c_void
}

/// Create a new WebUI handler instance with a named plugin.
///
/// # Arguments
///
/// * `plugin_id` - Null-terminated UTF-8 string identifying the plugin.
///   Currently supported: `"fast"`. Pass `NULL` for no plugin.
///
/// # Returns
///
/// An opaque pointer that must be freed with [`webui_handler_destroy`],
/// or `NULL` on error (call [`webui_last_error`] for details).
///
/// # Safety
///
/// `plugin_id` must be a valid null-terminated UTF-8 string, or `NULL`.
#[no_mangle]
pub unsafe extern "C" fn webui_handler_create_with_plugin(plugin_id: *const c_char) -> *mut c_void {
    clear_last_error();

    let handler = if plugin_id.is_null() {
        WebUIHandler::new()
    } else {
        match CStr::from_ptr(plugin_id).to_str() {
            Ok("fast") => WebUIHandler::with_plugin(|| Box::new(FastHydrationPlugin::new())),
            Ok(unknown) => {
                set_last_error(format!("unknown plugin: {unknown}"));
                return std::ptr::null_mut();
            }
            Err(e) => {
                set_last_error(format!("invalid UTF-8 in plugin_id: {e}"));
                return std::ptr::null_mut();
            }
        }
    };

    let context = Box::new(HandlerContext { handler });
    Box::into_raw(context) as *mut c_void
}

/// Destroy a WebUI handler instance.
///
/// # Safety
///
/// `handler_ptr` must be a valid pointer returned by [`webui_handler_create`],
/// or `NULL` (in which case this function is a no-op).
#[no_mangle]
pub unsafe extern "C" fn webui_handler_destroy(handler_ptr: *mut c_void) {
    if !handler_ptr.is_null() {
        let _ = Box::from_raw(handler_ptr as *mut HandlerContext);
    }
}

// ---------------------------------------------------------------------------
// FFI: protobuf-based render (existing API, now with error reporting)
// ---------------------------------------------------------------------------

/// Render a WebUI protocol (protobuf binary) with JSON data.
///
/// # Arguments
///
/// * `handler_ptr`   - Pointer returned by [`webui_handler_create`].
/// * `protocol_data` - Pointer to protobuf binary data.
/// * `protocol_len`  - Length of the protobuf data in bytes.
/// * `data_json`     - Null-terminated JSON string with the render state.
/// * `entry_id`      - Null-terminated UTF-8 string for the entry fragment.
/// * `request_path`  - Null-terminated UTF-8 string for the URL path to match
///   routes against (e.g., `"/contacts/42"`).
///
/// # Returns
///
/// A pointer to a null-terminated UTF-8 string with the rendered HTML, or
/// `NULL` on error.  The caller **must** free the returned string with
/// [`webui_free`].  On error, call [`webui_last_error`] for details.
///
/// # Safety
///
/// * `handler_ptr` must be a valid pointer returned by [`webui_handler_create`].
/// * `protocol_data` must point to `protocol_len` bytes of valid memory.
/// * `data_json`, `entry_id`, and `request_path` must be valid null-terminated UTF-8 strings.
#[no_mangle]
pub unsafe extern "C" fn webui_handler_render(
    handler_ptr: *mut c_void,
    protocol_data: *const u8,
    protocol_len: usize,
    data_json: *const c_char,
    entry_id: *const c_char,
    request_path: *const c_char,
) -> *mut c_char {
    clear_last_error();

    if handler_ptr.is_null()
        || protocol_data.is_null()
        || data_json.is_null()
        || entry_id.is_null()
        || request_path.is_null()
    {
        set_last_error("one or more required arguments are null");
        return std::ptr::null_mut();
    }

    // SAFETY: caller guarantees handler_ptr is valid and exclusively owned.
    let context = &*(handler_ptr as *const HandlerContext);

    // SAFETY: caller guarantees protocol_data points to protocol_len valid bytes.
    let protocol_bytes = std::slice::from_raw_parts(protocol_data, protocol_len);

    // SAFETY: caller guarantees data_json is a valid null-terminated string.
    let data_str = match CStr::from_ptr(data_json).to_str() {
        Ok(s) => s,
        Err(e) => {
            set_last_error(format!("invalid UTF-8 in data_json: {e}"));
            return std::ptr::null_mut();
        }
    };

    // SAFETY: caller guarantees entry_id is a valid null-terminated string.
    let entry_str = match CStr::from_ptr(entry_id).to_str() {
        Ok(s) => s,
        Err(e) => {
            set_last_error(format!("invalid UTF-8 in entry_id: {e}"));
            return std::ptr::null_mut();
        }
    };

    // SAFETY: caller guarantees request_path is a valid null-terminated string.
    let path_str = match CStr::from_ptr(request_path).to_str() {
        Ok(s) => s,
        Err(e) => {
            set_last_error(format!("invalid UTF-8 in request_path: {e}"));
            return std::ptr::null_mut();
        }
    };

    // Parse protocol from protobuf binary data
    let protocol = match WebUIProtocol::from_protobuf(protocol_bytes) {
        Ok(p) => p,
        Err(e) => {
            set_last_error(format!("failed to parse protobuf protocol: {e}"));
            return std::ptr::null_mut();
        }
    };

    // Parse data JSON
    let data: Value = match serde_json::from_str(data_str) {
        Ok(d) => d,
        Err(e) => {
            set_last_error(format!("failed to parse data JSON: {e}"));
            return std::ptr::null_mut();
        }
    };

    // Render
    let mut writer = StringResponseWriter::new();
    match context.handler.render(
        &protocol,
        &data,
        &RenderOptions::new(entry_str, path_str),
        &mut writer,
    ) {
        Ok(_) => match CString::new(writer.content) {
            Ok(s) => s.into_raw(),
            Err(e) => {
                set_last_error(format!("rendered output contains interior NUL byte: {e}"));
                std::ptr::null_mut()
            }
        },
        Err(e) => {
            set_last_error(format!("render failed: {e}"));
            std::ptr::null_mut()
        }
    }
}

// ---------------------------------------------------------------------------
// FFI: HTML-based render (new high-level API)
// ---------------------------------------------------------------------------

/// Parse an HTML template and render it with JSON data in a single call.
///
/// This is the **recommended entry point** for Go, C#, and Python consumers.
/// It eliminates the need for callers to deal with protobuf serialisation.
///
/// # Arguments
///
/// * `html`      - Null-terminated UTF-8 string containing the HTML template.
/// * `data_json` - Null-terminated UTF-8 JSON string with the render state.
///
/// # Returns
///
/// A pointer to a null-terminated UTF-8 string with the rendered HTML, or
/// `NULL` on error.  The caller **must** free the returned string with
/// [`webui_free`].  On error, call [`webui_last_error`] for details.
///
/// # Safety
///
/// Both `html` and `data_json` must be valid null-terminated UTF-8 strings.
#[no_mangle]
pub unsafe extern "C" fn webui_render(
    html: *const c_char,
    data_json: *const c_char,
) -> *mut c_char {
    clear_last_error();

    if html.is_null() || data_json.is_null() {
        set_last_error("html and data_json must not be null");
        return std::ptr::null_mut();
    }

    // --- Extract C strings ---------------------------------------------------
    let html_str = match CStr::from_ptr(html).to_str() {
        Ok(s) => s,
        Err(e) => {
            set_last_error(format!("invalid UTF-8 in html: {e}"));
            return std::ptr::null_mut();
        }
    };

    let data_str = match CStr::from_ptr(data_json).to_str() {
        Ok(s) => s,
        Err(e) => {
            set_last_error(format!("invalid UTF-8 in data_json: {e}"));
            return std::ptr::null_mut();
        }
    };

    // --- Parse HTML template into a WebUI protocol ---------------------------
    let entry_key = "template";
    let mut parser = HtmlParser::new();
    if let Err(e) = parser.parse(entry_key, html_str) {
        set_last_error(format!("HTML parse error: {e}"));
        return std::ptr::null_mut();
    }

    let protocol = WebUIProtocol::new(parser.into_fragment_records());

    // --- Parse JSON state ----------------------------------------------------
    let data: Value = match serde_json::from_str(data_str) {
        Ok(d) => d,
        Err(e) => {
            set_last_error(format!("failed to parse data JSON: {e}"));
            return std::ptr::null_mut();
        }
    };

    // --- Render --------------------------------------------------------------
    let handler = WebUIHandler::new();
    let mut writer = StringResponseWriter::new();

    match handler.render(
        &protocol,
        &data,
        &RenderOptions::new(entry_key, "/"),
        &mut writer,
    ) {
        Ok(_) => match CString::new(writer.content) {
            Ok(s) => s.into_raw(),
            Err(e) => {
                set_last_error(format!("rendered output contains interior NUL byte: {e}"));
                std::ptr::null_mut()
            }
        },
        Err(e) => {
            set_last_error(format!("render failed: {e}"));
            std::ptr::null_mut()
        }
    }
}

// ---------------------------------------------------------------------------
// FFI: unified partial response
// ---------------------------------------------------------------------------

/// Produce a complete JSON partial response for client-side navigation.
///
/// Combines route templates, inventory, and matched route chain into a single
/// JSON string: `{"templates":[...],"inventory":"...","chain":[...]}`.
///
/// # Arguments
///
/// * `protocol_data` - Pointer to protobuf binary data.
/// * `protocol_len`  - Length of the protobuf data in bytes.
/// * `entry_id`      - Null-terminated UTF-8 string for the persistent entry fragment.
/// * `request_path`  - Null-terminated UTF-8 route path used to select the active route chain.
/// * `inventory_hex` - Null-terminated hex string of the client's inventory bitmask
///   (pass empty string `""` if no inventory).
///
/// # Returns
///
/// A heap-allocated JSON string, or `NULL` on error. Caller frees with [`webui_free`].
///
/// # Safety
///
/// * `protocol_data` must point to `protocol_len` bytes of valid memory.
/// * `state_json`, `entry_id`, `request_path`, and `inventory_hex` must be valid
///   null-terminated UTF-8 strings.
#[no_mangle]
pub unsafe extern "C" fn webui_render_partial(
    protocol_data: *const u8,
    protocol_len: usize,
    state_json: *const c_char,
    entry_id: *const c_char,
    request_path: *const c_char,
    inventory_hex: *const c_char,
) -> *mut c_char {
    clear_last_error();

    match std::panic::catch_unwind(|| {
        if protocol_data.is_null()
            || state_json.is_null()
            || entry_id.is_null()
            || request_path.is_null()
            || inventory_hex.is_null()
        {
            set_last_error("one or more required arguments are null");
            return std::ptr::null_mut();
        }

        // SAFETY: The caller guarantees `protocol_data` points to `protocol_len` readable bytes.
        let protocol_bytes = unsafe { std::slice::from_raw_parts(protocol_data, protocol_len) };

        // SAFETY: The caller guarantees `state_json` is a valid null-terminated string.
        let state_str = match unsafe { CStr::from_ptr(state_json) }.to_str() {
            Ok(s) => s,
            Err(e) => {
                set_last_error(format!("invalid UTF-8 in state_json: {e}"));
                return std::ptr::null_mut();
            }
        };

        let state: Value = match serde_json::from_str(state_str) {
            Ok(v) => v,
            Err(e) => {
                set_last_error(format!("invalid state JSON: {e}"));
                return std::ptr::null_mut();
            }
        };

        // SAFETY: The caller guarantees `entry_id` is a valid null-terminated string.
        let entry_str = match unsafe { CStr::from_ptr(entry_id) }.to_str() {
            Ok(s) => s,
            Err(e) => {
                set_last_error(format!("invalid UTF-8 in entry_id: {e}"));
                return std::ptr::null_mut();
            }
        };

        // SAFETY: The caller guarantees `request_path` is a valid null-terminated string.
        let request_path_str = match unsafe { CStr::from_ptr(request_path) }.to_str() {
            Ok(s) => s,
            Err(e) => {
                set_last_error(format!("invalid UTF-8 in request_path: {e}"));
                return std::ptr::null_mut();
            }
        };

        // SAFETY: The caller guarantees `inventory_hex` is a valid null-terminated string.
        let inv_str = match unsafe { CStr::from_ptr(inventory_hex) }.to_str() {
            Ok(s) => s,
            Err(e) => {
                set_last_error(format!("invalid UTF-8 in inventory_hex: {e}"));
                return std::ptr::null_mut();
            }
        };

        let protocol = match WebUIProtocol::from_protobuf(protocol_bytes) {
            Ok(p) => p,
            Err(e) => {
                set_last_error(format!("failed to parse protobuf protocol: {e}"));
                return std::ptr::null_mut();
            }
        };

        let result = webui_handler::route_handler::render_partial(
            &protocol,
            state,
            entry_str,
            request_path_str,
            inv_str,
        );

        match CString::new(result.to_string()) {
            Ok(s) => s.into_raw(),
            Err(e) => {
                set_last_error(format!("JSON output contains interior NUL byte: {e}"));
                std::ptr::null_mut()
            }
        }
    }) {
        Ok(ptr) => ptr,
        Err(_) => {
            set_last_error("panic in webui_render_partial");
            std::ptr::null_mut()
        }
    }
}

/// Free a string returned by a WebUI FFI function.
///
/// # Safety
///
/// `string_ptr` must be a pointer returned by a WebUI FFI function (e.g.
/// [`webui_handler_render`] or [`webui_render`]), or `NULL`
/// (in which case this function is a no-op).
#[no_mangle]
pub unsafe extern "C" fn webui_free(string_ptr: *mut c_char) {
    if !string_ptr.is_null() {
        let _ = CString::from_raw(string_ptr);
    }
}