|
| 1 | +/*! |
| 2 | +This file is part of CycloneDX JavaScript Library. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +
|
| 16 | +SPDX-License-Identifier: Apache-2.0 |
| 17 | +Copyright (c) OWASP Foundation. All Rights Reserved. |
| 18 | +*/ |
| 19 | + |
| 20 | +import { readFile } from 'fs/promises'; |
| 21 | +import { ParseOption, XmlDocument, XsdValidator } from 'libxml2-wasm'; |
| 22 | +import { pathToFileURL } from 'url'; |
| 23 | + |
| 24 | +import type { ValidationError } from '../../validation/types'; |
| 25 | +import type { Functionality, Validator } from '../xmlValidator'; |
| 26 | + |
| 27 | +/** @internal */ |
| 28 | +export default (async function (schemaPath: string): Promise<Validator> { |
| 29 | + const schema = XmlDocument.fromString( |
| 30 | + await readFile(schemaPath, 'utf-8'), |
| 31 | + { |
| 32 | + option: ParseOption.XML_PARSE_NONET | ParseOption.XML_PARSE_COMPACT, |
| 33 | + url: pathToFileURL(schemaPath).toString() |
| 34 | + }); |
| 35 | + const validator = XsdValidator.fromDoc(schema); |
| 36 | + |
| 37 | + return function (data: string): null | ValidationError { |
| 38 | + const doc = XmlDocument.fromString(data, { option: ParseOption.XML_PARSE_NONET | ParseOption.XML_PARSE_COMPACT }); |
| 39 | + let errors = null; |
| 40 | + try { |
| 41 | + validator.validate(doc); |
| 42 | + } |
| 43 | + catch (validationErrors) { |
| 44 | + errors = validationErrors; |
| 45 | + } |
| 46 | + |
| 47 | + doc.dispose(); |
| 48 | + validator.dispose(); |
| 49 | + schema.dispose(); |
| 50 | + |
| 51 | + return errors; |
| 52 | + } |
| 53 | +}) satisfies Functionality |
0 commit comments