1use openbim_loin::{
9 Diagnostic, DiagnosticCode, LoinDocument, MigrationError, NamespaceVersion, OutputNamespace,
10 ParseError, ParseErrorKind, Severity,
11};
12use serde::Serialize;
13use wasm_bindgen::prelude::*;
14
15#[wasm_bindgen(start, skip_typescript)]
21fn start() {
22 console_error_panic_hook::set_once();
23}
24
25const 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
56const fn severity_str(severity: Severity) -> &'static str {
58 match severity {
59 Severity::Error => "Error",
60 Severity::Warning => "Warning",
61 }
62}
63
64const 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#[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
104fn 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 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
126fn write_error(message: &str) -> JsValue {
128 let js = js_sys::Error::new(message);
129 js.set_name("LoinWriteError");
130 js.into()
131}
132
133const fn version_str(version: NamespaceVersion) -> &'static str {
135 match version {
136 NamespaceVersion::Draft2022 => "Draft2022",
137 NamespaceVersion::Draft2024 => "Draft2024",
138 }
139}
140
141fn parse_version(value: &str) -> Option<NamespaceVersion> {
146 match value {
147 "Draft2022" => Some(NamespaceVersion::Draft2022),
148 "Draft2024" => Some(NamespaceVersion::Draft2024),
149 _ => None,
150 }
151}
152
153fn 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#[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#[derive(Serialize)]
188pub struct JsMigration {
189 pub xml: String,
190 pub report: JsMigrationReport,
191}
192
193#[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#[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#[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#[wasm_bindgen(js_name = isWellFormed)]
289pub fn is_well_formed(xml: &str) -> bool {
290 LoinDocument::parse(xml).is_ok()
291}
292
293#[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 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}