Skip to main content

einvoice_validator/
lib.rs

1//! Validate EN 16931 and Peppol BIS Billing 3.0 e-invoices against the official
2//! validation artefacts, in pure Rust: no JVM, no C library, no FFI.
3//!
4//! A [`Validator`] is built once from a rule set: the XML schema it names is loaded and
5//! its official compiled XSLT stylesheets are prepared. It then validates any number of
6//! documents, from any number of threads ([`Validator`] is `Send + Sync`). Each
7//! validation runs, in order:
8//!
9//! 1. the XML check: UTF-8, well-formed, namespace-well-formed, no document type
10//!    declaration ([`Error::NotXml`], [`Error::Unsupported`]);
11//! 2. the XML schema of the rule set, if any (UBL 2.1 for the UBL rule sets), with
12//!    [`einvoice_xsd`]: every validity error, with its line and column;
13//! 3. every stylesheet of the rule set, with [`einvoice_xslt_exec`], which executes the
14//!    official compiled Schematron with the behaviour of the reference engine
15//!    (Saxon-HE 12.10) and writes its SVRL report.
16//!
17//! The [`Report`] holds the schema errors, then, for each stylesheet, its raw SVRL
18//! report, its findings (failed asserts and successful reports, with their id, flag,
19//! location, rule context, test and message) and the canonical form of the SVRL. The
20//! verdict is [`Verdict::Valid`] when there is no schema error and no finding with flag
21//! `fatal`.
22//!
23//! ```
24//! # #[cfg(feature = "cen-ubl")] {
25//! use einvoice_validator::{Validator, Verdict};
26//!
27//! let validator = Validator::cen_ubl()?;
28//! let invoice = br#"<Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"/>"#;
29//! let report = validator.validate(invoice)?;
30//! assert_eq!(report.verdict(), Verdict::Invalid);
31//! // The schema wants the mandatory elements; the CEN rules report what is missing.
32//! assert!(!report.schema_errors.is_empty());
33//! assert!(report.findings().any(|f| f.id.as_deref() == Some("BR-01")));
34//! assert_eq!(report.rule_set.version, "1.3.17");
35//! # }
36//! # Ok::<(), einvoice_validator::Error>(())
37//! ```
38//!
39//! # Rule sets and bundles
40//!
41//! A rule set is described by a bundle: a manifest and the files it names. The
42//! manifest gives the rule set's name, title and version, the XML schema to validate
43//! against first, and the stylesheets to run, each with the SHA-256 of its file, which
44//! is checked when the bundle is loaded. [`RuleSet`] is the manifest, parsed.
45//!
46//! - Built in ([`BUILTIN_RULE_SETS`], [`Validator::builtin`]): `cen-ubl`, the CEN
47//!   EN 16931 validation artefacts for UBL, release 1.3.17, embedded unmodified (feature
48//!   `cen-ubl`, on by default; the artefacts are under the EUPL-1.2).
49//! - From a directory ([`Validator::from_bundle_dir`]): the manifest is
50//!   `<dir>/bundle.toml` ([`MANIFEST_FILE`]), and the paths it gives are relative to
51//!   `<dir>`. This is how rule sets whose artefacts cannot be redistributed are used:
52//!   fetch them into a directory, add the manifest.
53//! - From memory ([`Validator::from_bundle`]).
54//!
55//! The manifest is TOML, restricted to the subset below; anything else is refused with
56//! the line concerned (unknown keys included).
57//!
58//! ```toml
59//! format = 1                   # the manifest format, MANIFEST_FORMAT
60//! name = "cen-ubl"             # ASCII letters, digits, '-', '.', '_'
61//! title = "CEN EN 16931 UBL"
62//! version = "1.3.17"           # the version of the official artefacts
63//! schema = "ubl-2.1"           # optional: the XML schema validated first
64//!
65//! [[stylesheet]]               # one or more, run in this order
66//! name = "EN16931-UBL"         # unique in the bundle
67//! path = "ubl/xslt/EN16931-UBL-validation.xslt"   # relative, '/'-separated, no '..'
68//! sha256 = "fc4e6cfa8596bba0c2abd19038a98960c6ee9fc1f44566787c115efd4f4aca7c"
69//! # version = "..."            # optional: when it differs from the bundle's
70//! ```
71//!
72//! Accepted syntax: comments, `key = value` lines with a bare key, values that are
73//! basic strings (escapes `\"` and `\\` only), literal strings or non-negative integers,
74//! and `[[stylesheet]]` headers.
75//!
76//! # WebAssembly
77//!
78//! The crate builds for `wasm32-unknown-unknown` and needs nothing from the host there:
79//! the built-in rule set is embedded, and a bundle can be given from memory. That target
80//! has no system clock, so the caller gives the one the stylesheets read with
81//! [`ValidateOptions::clock`] (for instance [`Clock::from_unix_millis`] with
82//! JavaScript's `Date.now()`); without it, a validation fails with
83//! [`Error::Unsupported`]. The `wasm-validate` example validates two embedded documents
84//! that way and runs under wasmtime.
85//!
86//! # Licences
87//!
88//! The code is MIT. The built-in rule set `cen-ubl` embeds the CEN stylesheet, under the
89//! EUPL-1.2, and [`einvoice_xsd`] embeds the OASIS UBL 2.1 schemas, which keep their own
90//! terms (OASIS, UN/CEFACT, W3C). [`licences()`] returns the full text of every licence
91//! of what this build embeds, for programs that must show them to their users.
92//!
93//! # Errors
94//!
95//! A schema error or a failed assert is not an error: it is in the [`Report`]. An
96//! [`Error`] means no complete verdict could be given: a bundle that cannot be loaded,
97//! a document that is not XML, a construct the engine refuses rather than evaluating it
98//! differently from the reference engine, a dynamic error raised by a stylesheet, or a
99//! bug.
100
101mod builtin;
102mod error;
103mod licences;
104mod manifest;
105mod report;
106mod validator;
107
108pub use builtin::BUILTIN_RULE_SETS;
109pub use error::{Error, ErrorKind};
110pub use licences::{Licence, licences};
111pub use manifest::{MANIFEST_FILE, MANIFEST_FORMAT, RuleSet, SchemaId, StylesheetEntry};
112pub use report::{
113    Finding, FindingKind, Report, RuleSetVersion, SchemaError, SchemaErrorKind, Severity,
114    StylesheetFailure, StylesheetReport, Verdict,
115};
116pub use validator::{ValidateOptions, Validator, file_uri};
117
118/// The clock of a validation ([`ValidateOptions::clock`]): the implicit timezone and the
119/// value of `fn:current-dateTime()`.
120pub use einvoice_xpath_eval::Clock;
121
122/// The version of this crate, as published.
123pub const VERSION: &str = env!("CARGO_PKG_VERSION");
124
125#[cfg(test)]
126mod tests {
127    use super::VERSION;
128
129    #[test]
130    fn version_is_major_minor_patch() {
131        let parts: Vec<&str> = VERSION.split('.').collect();
132        assert_eq!(parts.len(), 3, "{VERSION}");
133        for part in parts {
134            assert!(
135                !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit()),
136                "{VERSION}"
137            );
138        }
139    }
140}