leptris 1.6.10

Rust bindings for libleptris — fast XML 1.0 parsing, XPath 1.0, SAX
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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
//! wasm-bindgen face over the compiled-in engine (leptris#1900 slice 2).
//!
//! Only compiled for wasm32 + the `wasm` feature: the engine is linked
//! statically by build.rs (wasm/shim/ supplies the freestanding libc),
//! so the raw C ABI is callable directly — no dlopen layer.

#![allow(non_snake_case)]

use crate::ffi;
use std::ffi::{CStr, CString};
use std::os::raw::{c_char, c_int};
use wasm_bindgen::prelude::*;

extern "C" {
    fn shim_fs_register(path: *const c_char, data: *const u8, len: usize) -> c_int;
    fn shim_fs_has(path: *const c_char) -> c_int;
    fn shim_fs_clear();
}

/// Register file contents under a virtual path so the engine's
/// path-based APIs (xsd compile set, schemaLocation imports) can read
/// them inside the freestanding wasm environment. Re-registering the
/// same path replaces its contents.
#[wasm_bindgen]
pub fn register_file(path: String, bytes: Vec<u8>) -> Result<(), JsError> {
    let cpath =
        CString::new(path.as_str()).map_err(|_| JsError::new("path contains a NUL byte"))?;
    let rc = unsafe { shim_fs_register(cpath.as_ptr(), bytes.as_ptr(), bytes.len()) };
    if rc != 0 {
        return Err(JsError::new("register_file failed (out of memory)"));
    }
    Ok(())
}

/// Drop every registered virtual file and reset any open handles.
#[wasm_bindgen]
pub fn clear_registered_files() {
    unsafe { shim_fs_clear() };
}

/// One attribute row of the batched snapshot: name and value always
/// carry; prefix/uri are undefined for no-namespace attributes.
#[wasm_bindgen]
pub struct WasmAttribute {
    name: String,
    value: String,
    prefix: Option<String>,
    uri: Option<String>,
}

#[wasm_bindgen]
impl WasmAttribute {
    #[wasm_bindgen(getter)]
    pub fn name(&self) -> String {
        self.name.clone()
    }

    #[wasm_bindgen(getter)]
    pub fn value(&self) -> String {
        self.value.clone()
    }

    #[wasm_bindgen(getter)]
    pub fn prefix(&self) -> Option<String> {
        self.prefix.clone()
    }

    #[wasm_bindgen(getter)]
    pub fn uri(&self) -> Option<String> {
        self.uri.clone()
    }
}

/// The engine's capability descriptor (leptris#1905): the raw bitset
/// plus the descriptor version (bits append per the engine's
/// contract; the descriptor version gates shape changes).
#[wasm_bindgen]
pub struct WasmCapabilities {
    caps: u64,
    descriptor_version: u32,
}

#[wasm_bindgen]
impl WasmCapabilities {
    #[wasm_bindgen(getter)]
    pub fn caps(&self) -> f64 {
        self.caps as f64
    }

    #[wasm_bindgen(getter)]
    pub fn descriptor_version(&self) -> u32 {
        self.descriptor_version
    }

    /// Whether the engine serves the given LEPTRIS_CAP_* bit value.
    pub fn serves(&self, bit: f64) -> bool {
        self.caps & (bit as u64) != 0
    }
}

/// A parsed document living in engine (wasm linear) memory.
#[wasm_bindgen]
pub struct WasmDocument {
    raw: *mut ffi::LeptrisDocument,
}

/// A compiled XSD schema. Owns its engine-side memory.
/// [`WasmSchema::validate_doc`] answers validity;
/// [`WasmSchema::last_errors`] returns the rows of the most recent
/// run.
#[wasm_bindgen]
pub struct WasmSchema {
    raw: *mut ffi::LeptrisXsdSchema,
}

impl Drop for WasmSchema {
    fn drop(&mut self) {
        if !self.raw.is_null() {
            unsafe { ffi::leptris_xsd_free(self.raw) };
        }
    }
}

/// The engine's capability descriptor (leptris#1905): what THIS
/// installed engine serves, as a versioned bitset. Bits append per
/// the engine's contract; decode against the LEPTRIS_CAP_* layout of
/// the reported descriptor version.
#[wasm_bindgen]
pub fn engine_capabilities() -> WasmCapabilities {
    let raw = unsafe { ffi::leptris_capabilities() };
    WasmCapabilities {
        caps: raw.caps,
        descriptor_version: raw.descriptor_version,
    }
}

/// Compile a schema SET: every listed document's declarations merge
/// into ONE schema (imports resolve across the set; the first
/// document's targetNamespace is the schema's). Paths resolve
/// relative to each document's own directory — register every file
/// the set will touch (heads and imported members) under the exact
/// virtual path first via register_file(); unregistered paths fail.
#[wasm_bindgen]
pub fn compile_xsd_set(paths: Vec<String>) -> Result<WasmSchema, JsError> {
    if paths.is_empty() {
        return Err(JsError::new("schema set needs at least one path"));
    }
    let cpaths: Vec<CString> = paths
        .iter()
        .map(|p| CString::new(p.as_str()))
        .collect::<Result<_, _>>()
        .map_err(|_| JsError::new("schema path contains a NUL byte"))?;
    for (p, cp) in paths.iter().zip(&cpaths) {
        if unsafe { shim_fs_has(cp.as_ptr()) } == 0 {
            return Err(JsError::new(&format!(
                "schema path not registered: {p} — call register_file() for every \
                 document the set will read (heads and imported members) first"
            )));
        }
    }
    let ptrs: Vec<*const std::os::raw::c_char> = cpaths.iter().map(|p| p.as_ptr()).collect();
    let mut st = ffi::LEPTRIS_OK;
    let raw = unsafe { ffi::leptris_xsd_compile_set(ptrs.as_ptr(), ptrs.len(), &mut st) };
    finish_schema(raw, st, "leptris xsd compile_set")
}

/// The engine's XSD compile faces return an ERROR-CARRYING HANDLE on
/// failure (non-NULL with status set) — the status is authoritative.
/// Surface the engine's error text and drop the handle.
fn finish_schema(
    raw: *mut ffi::LeptrisXsdSchema,
    st: ffi::LeptrisStatus,
    what: &str,
) -> Result<WasmSchema, JsError> {
    if st != ffi::LEPTRIS_OK {
        let mut msg = String::new();
        if !raw.is_null() {
            let p = unsafe { ffi::leptris_xsd_error(raw) };
            if !p.is_null() {
                msg = unsafe { CStr::from_ptr(p) }.to_string_lossy().into_owned();
            }
            unsafe { ffi::leptris_xsd_free(raw) };
        }
        return Err(JsError::new(&format!("{what} failed (status {st}): {msg}")));
    }
    if raw.is_null() {
        return Err(JsError::new(&format!("{what} failed (status {st})")));
    }
    Ok(WasmSchema { raw })
}

/// Parse an HTML string through the engine's WHATWG-conformant HTML
/// mode (implied head/body, void elements, case-normalized names).
#[wasm_bindgen]
pub fn parse_html(html: &str) -> Result<WasmDocument, JsError> {
    let chtml = CString::new(html).map_err(|_| JsError::new("html contains a NUL byte"))?;
    let mut st = ffi::LEPTRIS_OK;
    let raw = unsafe { ffi::leptris_parse_html_string(chtml.as_ptr(), html.len(), &mut st) };
    if raw.is_null() {
        return Err(JsError::new(&format!(
            "leptris html parse failed (status {st})"
        )));
    }
    Ok(WasmDocument { raw })
}

/// Compile an XSD schema (tier-1 subset). For multi-document schemas
/// (xsd:import / xsd:include across files) use register_file() +
/// compile_xsd_set().
#[wasm_bindgen]
pub fn compile_xsd(xsd: &str) -> Result<WasmSchema, JsError> {
    let cxsd = CString::new(xsd).map_err(|_| JsError::new("xsd contains a NUL byte"))?;
    let mut st: ffi::LeptrisStatus = ffi::LEPTRIS_OK;
    let raw = unsafe { ffi::leptris_xsd_compile(cxsd.as_ptr(), xsd.len(), &mut st) };
    finish_schema(raw, st, "leptris xsd compile")
}

#[wasm_bindgen]
impl WasmSchema {
    /// Validate a document: Ok(true) valid, Ok(false) invalid (fetch
    /// the rows via `last_errors`), Err on bad args.
    pub fn validate_doc(&self, doc: &WasmDocument) -> Result<bool, JsError> {
        let r = unsafe { ffi::leptris_xsd_validate(self.raw, doc.raw) };
        if r < 0 {
            return Err(JsError::new("leptris xsd validation failed"));
        }
        Ok(r == 1)
    }

    /// The error rows of the most recent validate run (schema-owned;
    /// replaced by the next run).
    pub fn last_errors(&self) -> Vec<String> {
        unsafe {
            let n = ffi::leptris_xsd_error_count(self.raw);
            (0..n)
                .filter_map(|i| {
                    let p = ffi::leptris_xsd_error_at(self.raw, i);
                    if p.is_null() {
                        None
                    } else {
                        Some(CStr::from_ptr(p).to_string_lossy().into_owned())
                    }
                })
                .collect()
        }
    }
}

impl Drop for WasmDocument {
    fn drop(&mut self) {
        if !self.raw.is_null() {
            unsafe { ffi::leptris_document_free(self.raw) };
        }
    }
}

#[wasm_bindgen]
impl WasmDocument {
    /// Parse an XML string. Errors carry the engine's LeptrisStatus.
    #[wasm_bindgen(constructor)]
    pub fn parse(xml: &str) -> Result<WasmDocument, JsError> {
        let cxml = CString::new(xml).map_err(|_| JsError::new("xml contains a NUL byte"))?;
        let mut st: ffi::LeptrisStatus = ffi::LEPTRIS_OK;
        let raw = unsafe { ffi::leptris_parse_string(cxml.as_ptr(), xml.len(), &mut st) };
        if raw.is_null() {
            return Err(JsError::new(&format!("leptris parse failed (status {st})")));
        }
        Ok(WasmDocument { raw })
    }

    /// Evaluate an XPath expression; the string-value of the result.
    pub fn xpath(&self, expression: &str) -> Result<String, JsError> {
        let cexpr =
            CString::new(expression).map_err(|_| JsError::new("xpath contains a NUL byte"))?;
        let result =
            unsafe { ffi::leptris_xpath_eval(self.raw, std::ptr::null_mut(), cexpr.as_ptr()) };
        if result.is_null() {
            return Err(JsError::new("leptris xpath evaluation failed"));
        }
        let s = unsafe { take_string(ffi::leptris_xpath_result_string(result)) };
        unsafe { ffi::leptris_xpath_result_free(result) };
        s.map_err(|_| JsError::new("result string materialization failed"))
    }

    /// Count nodes matching the expression.
    pub fn xpath_count(&self, expression: &str) -> Result<usize, JsError> {
        let cexpr =
            CString::new(expression).map_err(|_| JsError::new("xpath contains a NUL byte"))?;
        let result =
            unsafe { ffi::leptris_xpath_eval(self.raw, std::ptr::null_mut(), cexpr.as_ptr()) };
        if result.is_null() {
            return Err(JsError::new("leptris xpath evaluation failed"));
        }
        let n = unsafe { ffi::leptris_xpath_result_count(result) };
        unsafe { ffi::leptris_xpath_result_free(result) };
        Ok(n)
    }

    /// Serialize the document back to XML.
    pub fn to_xml(&self) -> Result<String, JsError> {
        unsafe {
            take_string(ffi::leptris_document_serialize(
                self.raw,
                std::ptr::null_mut(),
            ))
        }
        .map_err(|_| JsError::new("serialization failed"))
    }

    /// Root element name.
    pub fn root_name(&self) -> Option<String> {
        let root = unsafe { ffi::leptris_document_root(self.raw) };
        if root.is_null() {
            return None;
        }
        unsafe {
            Some(
                CStr::from_ptr(ffi::leptris_element_name(root))
                    .to_string_lossy()
                    .into_owned(),
            )
        }
    }
}

/// Take ownership of an engine-allocated C string (leptris_free_string
/// contract) and convert to a Rust String.
unsafe fn take_string(p: *mut c_char) -> Result<String, ()> {
    if p.is_null() {
        return Err(());
    }
    let s = CStr::from_ptr(p as *const c_char)
        .to_string_lossy()
        .into_owned();
    // The mirror's free face (same name as the header's).
    extern "C" {
        fn leptris_free_string(str: *mut c_char);
    }
    leptris_free_string(p);
    let _ = c_int::MAX; // keep the c_int import honest when unused
    Ok(s)
}

/* ---- #15 faces: node handles, result shapes, write face ---------- */

/// Node kinds for mixed children/nodeset rows (engine LeptrisNodeKind).
#[wasm_bindgen]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum WasmNodeKind {
    Element = 1,
    Text = 2,
    Comment = 3,
    Cdata = 4,
    Pi = 5,
    DocType = 6,
    Attribute = 7,
    Other = 0,
}

/// A node handle into a document living in engine memory. Reads are
/// bounds-checked by the engine; a handle stays valid for its
/// document's lifetime.
#[wasm_bindgen]
#[derive(Clone)]
pub struct WasmNode {
    doc: *mut ffi::LeptrisDocument,
    node: ffi::LeptrisNodeRef,
}

#[wasm_bindgen]
impl WasmNode {
    /// Element name (element-kind nodes only).
    pub fn name(&self) -> Option<String> {
        unsafe {
            let p = ffi::leptris_element_name(self.node as *mut ffi::LeptrisElement);
            if p.is_null() {
                return None;
            }
            /* document-owned: BORROW, never free */
            Some(CStr::from_ptr(p).to_string_lossy().into_owned())
        }
    }

    /// Text content (text-kind nodes read their data; element-kind
    /// read their concatenated text). Document-owned: borrowed.
    pub fn text(&self) -> Option<String> {
        unsafe {
            let p = match self.kind() {
                WasmNodeKind::Text => ffi::leptris_text_node_get_content(self.node),
                _ => ffi::leptris_element_text(self.node as *mut ffi::LeptrisElement),
            };
            if p.is_null() {
                return None;
            }
            Some(CStr::from_ptr(p).to_string_lossy().into_owned())
        }
    }

    /// Engine node kind.
    pub fn kind(&self) -> WasmNodeKind {
        match unsafe { ffi::leptris_node_get_type(self.node) } {
            0 => WasmNodeKind::Element,
            1 => WasmNodeKind::Text,
            2 => WasmNodeKind::Comment,
            3 => WasmNodeKind::Cdata,
            4 => WasmNodeKind::Pi,
            5 => WasmNodeKind::DocType,
            6 => WasmNodeKind::Attribute,
            _ => WasmNodeKind::Other,
        }
    }

    /// Children across every kind the engine serves, document order.
    pub fn children(&self) -> Vec<WasmNode> {
        unsafe {
            let n = ffi::leptris_node_children(self.node, std::ptr::null_mut(), 0);
            if n == 0 {
                return Vec::new();
            }
            let mut nodes: Vec<ffi::LeptrisNodeRef> = vec![std::ptr::null_mut(); n];
            let got = ffi::leptris_node_children(self.node, nodes.as_mut_ptr(), n);
            nodes.truncate(got);
            nodes
                .into_iter()
                .map(|node| WasmNode {
                    doc: self.doc,
                    node,
                })
                .collect()
        }
    }

    /// Set an attribute (element-kind nodes).
    pub fn set_attribute(&self, name: &str, value: &str) -> Result<(), JsError> {
        let cname =
            CString::new(name).map_err(|_| JsError::new("attribute name contains a NUL byte"))?;
        let cvalue =
            CString::new(value).map_err(|_| JsError::new("attribute value contains a NUL byte"))?;
        let st = unsafe {
            ffi::leptris_element_set_attribute(
                self.node as *mut ffi::LeptrisElement,
                cname.as_ptr(),
                cvalue.as_ptr(),
            )
        };
        if st != ffi::LEPTRIS_OK {
            return Err(JsError::new("leptris set_attribute failed"));
        }
        Ok(())
    }

    /// The element's namespace URI (element-kind nodes), or undefined
    /// for a no-namespace element.
    pub fn namespace_uri(&self) -> Option<String> {
        unsafe {
            let ns = ffi::leptris_element_namespace(self.node as *mut ffi::LeptrisElement);
            if ns.is_null() {
                return None;
            }
            let p = ffi::leptris_namespace_uri(ns);
            if p.is_null() {
                return None;
            }
            /* document-owned: BORROW, never free */
            Some(CStr::from_ptr(p).to_string_lossy().into_owned())
        }
    }

    /// The element's namespace prefix as spelled, or undefined.
    pub fn prefix(&self) -> Option<String> {
        unsafe {
            let p = ffi::leptris_element_prefix(self.node as *mut ffi::LeptrisElement);
            if p.is_null() {
                return None;
            }
            Some(CStr::from_ptr(p).to_string_lossy().into_owned())
        }
    }

    /// ALL attribute names, values, and namespace data in ONE
    /// crossing (the engine's batched snapshot, leptris#1689): an
    /// array of {name, value, prefix, uri} — prefix/uri undefined for
    /// no-namespace attributes.
    pub fn attribute_pairs(&self) -> Result<Vec<WasmAttribute>, JsError> {
        let elem = self.node as *mut ffi::LeptrisElement;
        let count = unsafe { ffi::leptris_element_attribute_count(elem) };
        if count == 0 {
            return Ok(Vec::new());
        }
        /* Phase 1: sizing (NULL blobs). */
        let cap = unsafe {
            ffi::leptris_element_attributes_snapshot(
                elem,
                std::ptr::null_mut(),
                0,
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                0,
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                0,
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                0,
                std::ptr::null_mut(),
            )
        };
        if cap == usize::MAX {
            return Err(JsError::new("leptris attribute snapshot sizing failed"));
        }
        /* Phase 2: read. One retry at the phase-1 capacity (the
         * engine's contract for mid-call mutation). */
        for _ in 0..2 {
            let mut names = vec![0u8; cap];
            let mut values = vec![0u8; cap];
            let mut prefixes = vec![0u8; cap];
            let mut uris = vec![0u8; cap];
            let mut name_offsets = vec![0usize; count + 1];
            let mut value_offsets = vec![0usize; count + 1];
            let mut prefix_offsets = vec![0usize; count + 1];
            let mut uri_offsets = vec![0usize; count + 1];
            let st = unsafe {
                ffi::leptris_element_attributes_snapshot(
                    elem,
                    names.as_mut_ptr() as *mut c_char,
                    cap,
                    name_offsets.as_mut_ptr(),
                    values.as_mut_ptr() as *mut c_char,
                    cap,
                    value_offsets.as_mut_ptr(),
                    prefixes.as_mut_ptr() as *mut c_char,
                    cap,
                    prefix_offsets.as_mut_ptr(),
                    uris.as_mut_ptr() as *mut c_char,
                    cap,
                    uri_offsets.as_mut_ptr(),
                )
            };
            if st == 0 {
                let lane = |blob: &[u8], offsets: &[usize], i: usize| -> String {
                    let start = offsets[i];
                    let end = offsets[i + 1];
                    String::from_utf8_lossy(&blob[start..end.max(start)])
                        .trim_end_matches('\0')
                        .to_string()
                };
                let mut out = Vec::with_capacity(count);
                for i in 0..count {
                    let no_ns = uri_offsets[i] == usize::MAX;
                    out.push(WasmAttribute {
                        name: lane(&names, &name_offsets, i),
                        value: lane(&values, &value_offsets, i),
                        prefix: if no_ns {
                            None
                        } else {
                            Some(lane(&prefixes, &prefix_offsets, i))
                        },
                        uri: if no_ns {
                            None
                        } else {
                            Some(lane(&uris, &uri_offsets, i))
                        },
                    });
                }
                return Ok(out);
            }
        }
        Err(JsError::new("leptris attribute snapshot failed"))
    }

    /// Append an owned node (created via WasmDocument::create_* or
    /// moved from another parent of the SAME document). Returns the
    /// installed handle.
    pub fn add_child(&self, child: WasmNode) -> Result<WasmNode, JsError> {
        if !child.doc.eq(&self.doc) {
            return Err(JsError::new(
                "add_child: cross-document adoption is not served by this face",
            ));
        }
        let mut installed: usize = 0;
        let st = unsafe {
            ffi::leptris_element_add_child_addr_installed(
                self.node as usize,
                child.node as usize,
                &mut installed,
            )
        };
        if st != ffi::LEPTRIS_OK || installed == 0 {
            return Err(JsError::new("leptris add_child failed"));
        }
        Ok(WasmNode {
            doc: self.doc,
            node: installed as ffi::LeptrisNodeRef,
        })
    }

    pub fn ptr(&self) -> usize {
        self.node as usize
    }
}

/// One XPath result: the full processing-model shape — the string
/// value plus the typed view, and for node-sets the node handles in
/// document order.
#[wasm_bindgen]
pub struct WasmXPathResult {
    kind: i32,
    string_value: String,
    boolean: bool,
    number: f64,
    nodes: Vec<WasmNode>,
}

#[wasm_bindgen]
impl WasmXPathResult {
    /// 0 nodeset, 1 boolean, 2 number, 3 string, 4 function item
    /// (the engine's LeptrisXPathResultType — 0-based; #19).
    pub fn kind(&self) -> i32 {
        self.kind
    }
    /// The string-value of the result (every kind).
    #[wasm_bindgen(js_name = stringValue)]
    pub fn string_value(&self) -> String {
        self.string_value.clone()
    }
    /// The boolean value (boolean kind; EBV otherwise per spec).
    pub fn boolean(&self) -> bool {
        self.boolean
    }
    /// The numeric value (number kind; NaN outside the numeric space).
    pub fn number(&self) -> f64 {
        self.number
    }
    /// Node handles for node-set results (document order).
    pub fn nodes(&self) -> Vec<WasmNode> {
        self.nodes.clone()
    }
}

#[wasm_bindgen]
impl WasmDocument {
    /// Evaluate an XPath with the FULL result shape.
    pub fn xpath_full(&self, expression: &str) -> Result<WasmXPathResult, JsError> {
        let cexpr =
            CString::new(expression).map_err(|_| JsError::new("xpath contains a NUL byte"))?;
        let result =
            unsafe { ffi::leptris_xpath_eval(self.raw, std::ptr::null_mut(), cexpr.as_ptr()) };
        if result.is_null() {
            return Err(JsError::new("leptris xpath evaluation failed"));
        }
        unsafe {
            let kind = ffi::leptris_xpath_result_type(result);
            let sv = take_string(ffi::leptris_xpath_result_string(result)).unwrap_or_default();
            let boolean = ffi::leptris_xpath_result_boolean(result) != 0;
            let number = ffi::leptris_xpath_result_number(result);
            let mut nodes = Vec::new();
            if kind == ffi::LEPTRIS_XPATH_NODESET {
                let n = ffi::leptris_xpath_result_count(result);
                let mut handles: Vec<ffi::LeptrisNodeRef> = vec![std::ptr::null_mut(); n];
                let got = ffi::leptris_xpath_result_get_nodes_ex(
                    result,
                    handles.as_mut_ptr(),
                    std::ptr::null_mut(),
                    n,
                );
                handles.truncate(got);
                nodes = handles
                    .into_iter()
                    .map(|node| WasmNode {
                        doc: self.raw,
                        node,
                    })
                    .collect();
            }
            ffi::leptris_xpath_result_free(result);
            Ok(WasmXPathResult {
                kind,
                string_value: sv,
                boolean,
                number,
                nodes,
            })
        }
    }

    /// The root element as a node handle.
    pub fn root(&self) -> Option<WasmNode> {
        let root = unsafe { ffi::leptris_document_root(self.raw) };
        if root.is_null() {
            return None;
        }
        Some(WasmNode {
            doc: self.raw,
            node: root as ffi::LeptrisNodeRef,
        })
    }

    /// Create a detached element owned by this document.
    pub fn create_element(&self, name: &str) -> Result<WasmNode, JsError> {
        let cname =
            CString::new(name).map_err(|_| JsError::new("element name contains a NUL byte"))?;
        let elem = unsafe {
            ffi::leptris_element_new_with_attributes(
                self.raw,
                cname.as_ptr(),
                std::ptr::null(),
                std::ptr::null(),
                0,
            )
        };
        if elem.is_null() {
            return Err(JsError::new("leptris create_element failed"));
        }
        Ok(WasmNode {
            doc: self.raw,
            node: elem as ffi::LeptrisNodeRef,
        })
    }

    /// Create a detached text node owned by this document.
    pub fn create_text(&self, text: &str) -> Result<WasmNode, JsError> {
        let ctext = CString::new(text).map_err(|_| JsError::new("text contains a NUL byte"))?;
        let node = unsafe { ffi::leptris_text_node_create(self.raw, ctext.as_ptr()) };
        if node.is_null() {
            return Err(JsError::new("leptris create_text failed"));
        }
        Ok(WasmNode {
            doc: self.raw,
            node,
        })
    }

    /// Set the document's root element (attaches a detached element).
    pub fn set_root(&self, root: WasmNode) -> Result<(), JsError> {
        let st = unsafe {
            ffi::leptris_document_set_root(self.raw, root.node as *mut ffi::LeptrisElement)
        };
        if st != ffi::LEPTRIS_OK {
            return Err(JsError::new("leptris set_root failed"));
        }
        Ok(())
    }
}