Skip to main content

openbim_loin_wasm/
lib.rs

1//! Browser bindings for `openbim-loin`.
2//!
3//! The core crate carries no wasm or JS dependency; this crate is the only
4//! place `wasm-bindgen` appears. Diagnostics *and* errors cross the boundary
5//! as structured JS objects rather than formatted strings, so callers branch
6//! on `code`, `severity` and `kind` instead of parsing message text.
7
8use openbim_loin::{
9    Diagnostic, DiagnosticCode, LoinDocument, MigrationError, NamespaceVersion, OutputNamespace,
10    ParseError, ParseErrorKind, Severity,
11};
12use serde::Serialize;
13use wasm_bindgen::prelude::*;
14
15/// Installs a panic hook so a Rust panic reaches the JS console with a stack
16/// trace instead of surfacing as a bare `unreachable executed`.
17///
18/// `skip_typescript` keeps this internal detail out of the published `.d.ts`;
19/// wasm-bindgen still invokes it automatically on module init.
20#[wasm_bindgen(start, skip_typescript)]
21fn start() {
22    console_error_panic_hook::set_once();
23}
24
25/// Stable JS-facing spelling of a diagnostic code.
26///
27/// Written out rather than derived from `Debug`: the strings are public API
28/// for every JS consumer, and deriving them would let a Rust-side rename
29/// silently break them. The match is exhaustive on purpose, so adding a
30/// variant upstream fails this crate's build and forces a decision here.
31const fn code_str(code: DiagnosticCode) -> &'static str {
32    match code {
33        DiagnosticCode::UnexpectedNamespace => "UnexpectedNamespace",
34        DiagnosticCode::UnknownElement => "UnknownElement",
35        DiagnosticCode::UnexpectedAttribute => "UnexpectedAttribute",
36        DiagnosticCode::MissingRequiredAttribute => "MissingRequiredAttribute",
37        DiagnosticCode::MissingRequiredChild => "MissingRequiredChild",
38        DiagnosticCode::TooManyChildren => "TooManyChildren",
39        DiagnosticCode::ChildOutOfOrder => "ChildOutOfOrder",
40        DiagnosticCode::UnexpectedText => "UnexpectedText",
41        DiagnosticCode::InvalidGuid => "InvalidGuid",
42        DiagnosticCode::InvalidAnyUri => "InvalidAnyUri",
43        DiagnosticCode::MissingLanguage => "MissingLanguage",
44        DiagnosticCode::InvalidLanguage => "InvalidLanguage",
45        DiagnosticCode::InvalidDateTime => "InvalidDateTime",
46        DiagnosticCode::InvalidBoolean => "InvalidBoolean",
47        DiagnosticCode::InvalidDecimal => "InvalidDecimal",
48        DiagnosticCode::InvalidDouble => "InvalidDouble",
49        DiagnosticCode::InvalidEnumeration => "InvalidEnumeration",
50        DiagnosticCode::NilledContent => "NilledContent",
51        DiagnosticCode::UnsupportedXsiType => "UnsupportedXsiType",
52        DiagnosticCode::CompatibilityProfile => "CompatibilityProfile",
53    }
54}
55
56/// Stable JS-facing spelling of a severity. See [`code_str`].
57const fn severity_str(severity: Severity) -> &'static str {
58    match severity {
59        Severity::Error => "Error",
60        Severity::Warning => "Warning",
61    }
62}
63
64/// Stable JS-facing spelling of a parse-failure category. See [`code_str`].
65const fn kind_str(kind: ParseErrorKind) -> &'static str {
66    match kind {
67        ParseErrorKind::InputTooLarge => "InputTooLarge",
68        ParseErrorKind::DepthLimit => "DepthLimit",
69        ParseErrorKind::NodeLimit => "NodeLimit",
70        ParseErrorKind::AttributeLimit => "AttributeLimit",
71        ParseErrorKind::DoctypeForbidden => "DoctypeForbidden",
72        ParseErrorKind::UnsupportedXmlVersion => "UnsupportedXmlVersion",
73        ParseErrorKind::DuplicateExpandedAttribute => "DuplicateExpandedAttribute",
74        ParseErrorKind::UnknownEntity => "UnknownEntity",
75        ParseErrorKind::UndeclaredPrefix => "UndeclaredPrefix",
76        ParseErrorKind::MalformedQName => "MalformedQName",
77        ParseErrorKind::MissingRoot => "MissingRoot",
78        ParseErrorKind::MultipleRoots => "MultipleRoots",
79        ParseErrorKind::UnexpectedRoot => "UnexpectedRoot",
80        ParseErrorKind::UnsupportedNamespace => "UnsupportedNamespace",
81        ParseErrorKind::MalformedXml => "MalformedXml",
82        ParseErrorKind::InvalidEncoding => "InvalidEncoding",
83    }
84}
85
86/// One validation finding, shaped for JS consumption.
87#[derive(Serialize)]
88pub struct JsDiagnostic {
89    pub severity: String,
90    pub code: String,
91    pub path: String,
92    pub message: String,
93}
94
95fn to_js(d: &Diagnostic) -> JsDiagnostic {
96    JsDiagnostic {
97        severity: severity_str(d.severity()).to_owned(),
98        code: code_str(d.code()).to_owned(),
99        path: d.path().to_owned(),
100        message: d.message().to_owned(),
101    }
102}
103
104/// Builds a JS `Error` that keeps the parse failure machine-readable.
105///
106/// `kind` and `position` are attached as own properties, so a browser editor
107/// can place a marker at the byte offset instead of regexing the message.
108fn parse_error(error: &ParseError) -> JsValue {
109    let js = js_sys::Error::new(&error.to_string());
110    js.set_name("LoinParseError");
111    let value: JsValue = js.into();
112    // Reflect::set only fails for a non-object target; `value` is an Error.
113    let _ = js_sys::Reflect::set(
114        &value,
115        &JsValue::from_str("kind"),
116        &JsValue::from_str(kind_str(error.kind())),
117    );
118    let _ = js_sys::Reflect::set(
119        &value,
120        &JsValue::from_str("position"),
121        &JsValue::from_f64(error.position() as f64),
122    );
123    value
124}
125
126/// Builds a JS `Error` for a write failure.
127fn write_error(message: &str) -> JsValue {
128    let js = js_sys::Error::new(message);
129    js.set_name("LoinWriteError");
130    js.into()
131}
132
133/// Stable JS-facing spelling of a namespace version. See [`code_str`].
134const fn version_str(version: NamespaceVersion) -> &'static str {
135    match version {
136        NamespaceVersion::Draft2022 => "Draft2022",
137        NamespaceVersion::Draft2024 => "Draft2024",
138    }
139}
140
141/// Parses the JS-facing namespace-version spelling.
142///
143/// Returns `None` for anything unrecognised so the caller can throw rather
144/// than silently migrating to a default.
145fn parse_version(value: &str) -> Option<NamespaceVersion> {
146    match value {
147        "Draft2022" => Some(NamespaceVersion::Draft2022),
148        "Draft2024" => Some(NamespaceVersion::Draft2024),
149        _ => None,
150    }
151}
152
153/// Builds a JS `Error` for a refused migration.
154///
155/// `element` and `local_name` are attached as own properties for the same
156/// reason parse errors carry `kind` and `position`: the caller should be able
157/// to point at the offending attribute without parsing prose.
158fn migration_error(error: &MigrationError) -> JsValue {
159    let js = js_sys::Error::new(&error.to_string());
160    js.set_name("LoinMigrationError");
161    let value: JsValue = js.into();
162    let _ = js_sys::Reflect::set(
163        &value,
164        &JsValue::from_str("element"),
165        &JsValue::from_str(error.element()),
166    );
167    let _ = js_sys::Reflect::set(
168        &value,
169        &JsValue::from_str("localName"),
170        &JsValue::from_str(error.local_name()),
171    );
172    value
173}
174
175/// Counts describing what a migration changed.
176#[derive(Serialize)]
177pub struct JsMigrationReport {
178    pub source: String,
179    pub target: String,
180    #[serde(rename = "changedNames")]
181    pub changed_names: usize,
182    #[serde(rename = "changedDeclarations")]
183    pub changed_declarations: usize,
184}
185
186/// Migrated document plus the report describing what changed.
187#[derive(Serialize)]
188pub struct JsMigration {
189    pub xml: String,
190    pub report: JsMigrationReport,
191}
192
193// Hand-written declarations: wasm-bindgen types a `JsValue` return as `any`,
194// which would leave the whole point of structured diagnostics untyped.
195#[wasm_bindgen(typescript_custom_section)]
196const TS_TYPES: &'static str = r#"
197/** Severity of a validation finding. */
198export type Severity = "Error" | "Warning";
199
200/** One validation finding. `code` is stable across releases. */
201export interface Diagnostic {
202    severity: Severity;
203    code: string;
204    /** Element path, e.g. `/LevelOfInformationNeed/Specification[1]`. */
205    path: string;
206    message: string;
207}
208
209/** Error thrown when input is not a well-formed LOIN document. */
210export interface LoinParseError extends Error {
211    name: "LoinParseError";
212    /** Stable failure category, e.g. `MalformedXml`. */
213    kind: string;
214    /** Byte offset into the input. */
215    position: number;
216}
217
218/**
219 * Validates a LOIN document.
220 *
221 * @throws {LoinParseError} when the input is not a well-formed LOIN document.
222 */
223export function validate(xml: string): Diagnostic[];
224
225/** A LOIN namespace version. */
226export type NamespaceVersion = "Draft2022" | "Draft2024";
227
228/** Counts describing what a migration changed. */
229export interface MigrationReport {
230    source: NamespaceVersion;
231    target: NamespaceVersion;
232    /** Element and attribute names moved to the target namespace. */
233    changedNames: number;
234    /** Namespace declarations rewritten. */
235    changedDeclarations: number;
236}
237
238/** Migrated document plus a report of what changed. */
239export interface Migration {
240    xml: string;
241    report: MigrationReport;
242}
243
244/** Error thrown when a migration would collide two attribute names. */
245export interface LoinMigrationError extends Error {
246    name: "LoinMigrationError";
247    /** Element carrying the colliding attribute. */
248    element: string;
249    /** Local name that would be duplicated. */
250    localName: string;
251}
252
253/**
254 * Migrates a document to a target LOIN namespace version.
255 *
256 * Migrating to the version already in use is a no-op that still returns a
257 * report, with both counts zero.
258 *
259 * @throws {LoinParseError} when the input is not a well-formed LOIN document.
260 * @throws {LoinMigrationError} when the migration would collide attributes.
261 * @throws {TypeError} when `target` is not a known namespace version.
262 */
263export function migrate(xml: string, target: NamespaceVersion): Migration;
264"#;
265
266/// Validates a LOIN document, returning an array of diagnostics.
267///
268/// Throws a JS `LoinParseError` carrying `kind` and `position` when the input
269/// is not a well-formed LOIN document.
270#[wasm_bindgen(skip_typescript)]
271pub fn validate(xml: &str) -> Result<JsValue, JsValue> {
272    let doc = LoinDocument::parse(xml).map_err(|e| parse_error(&e))?;
273    let out: Vec<JsDiagnostic> = doc.validate().iter().map(to_js).collect();
274    serde_wasm_bindgen::to_value(&out).map_err(JsValue::from)
275}
276
277/// Parses and re-serialises a document, preserving its observed namespace.
278///
279/// Use this to confirm an editor round-trip is lossless.
280#[wasm_bindgen]
281pub fn rewrite(xml: &str) -> Result<String, JsValue> {
282    let doc = LoinDocument::parse(xml).map_err(|e| parse_error(&e))?;
283    doc.to_xml_string(OutputNamespace::Preserve)
284        .map_err(|e| write_error(&e.to_string()))
285}
286
287/// True when the input parses as a LOIN document at all.
288#[wasm_bindgen(js_name = isWellFormed)]
289pub fn is_well_formed(xml: &str) -> bool {
290    LoinDocument::parse(xml).is_ok()
291}
292
293/// Migrates a document to a target LOIN namespace version.
294///
295/// Returns the migrated XML together with a report of what changed. Throws a
296/// JS `LoinMigrationError` when the migration would make two attributes share
297/// one expanded name, and a `TypeError` for an unknown target version rather
298/// than quietly falling back to a default.
299#[wasm_bindgen(skip_typescript)]
300pub fn migrate(xml: &str, target: &str) -> Result<JsValue, JsValue> {
301    let target = parse_version(target).ok_or_else(|| {
302        JsValue::from(js_sys::TypeError::new(
303            "unknown namespace version: expected \"Draft2022\" or \"Draft2024\"",
304        ))
305    })?;
306    let doc = LoinDocument::parse(xml).map_err(|e| parse_error(&e))?;
307    let (migrated, report) = doc.migrated(target).map_err(|e| migration_error(&e))?;
308    // `migrated()` already advances `current_namespace`, so `Preserve` would
309    // serialise identically. Naming the target is equivalent but states the
310    // intent, and keeps this correct if that internal behaviour ever changes.
311    let out = migrated
312        .to_xml_string(OutputNamespace::Version(target))
313        .map_err(|e| write_error(&e.to_string()))?;
314    let value = JsMigration {
315        xml: out,
316        report: JsMigrationReport {
317            source: version_str(report.source()).to_owned(),
318            target: version_str(report.target()).to_owned(),
319            changed_names: report.changed_names(),
320            changed_declarations: report.changed_declarations(),
321        },
322    };
323    serde_wasm_bindgen::to_value(&value).map_err(JsValue::from)
324}