cda-schematron-validator 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.jshintrc ADDED
@@ -0,0 +1,96 @@
1
+ /*jshint :esversion 6 */
2
+ {
3
+ // JSHint Default Configuration File (as on JSHint website)
4
+ // See http://jshint.com/docs/ for more details
5
+
6
+ "maxerr": 500, // {int} Maximum error before stopping
7
+
8
+ // Enforcing
9
+ "bitwise": true, // true: Prohibit bitwise operators (&, |, ^, etc.)
10
+ "camelcase": false, // true: Identifiers must be in camelCase
11
+ "curly": false, // true: Require {} for every new block or scope
12
+ "eqeqeq": true, // true: Require triple equals (===) for comparison
13
+ "forin": true, // true: Require filtering for..in loops with obj.hasOwnProperty()
14
+ "immed": true, // true: Require immediate invocations to be wrapped in parens e.g. `(function () { } ());`
15
+ "indent": false, // {int} Number of spaces to use for indentation
16
+ "latedef": false, // true: Require variables/functions to be defined before being used
17
+ "newcap": false, // true: Require capitalization of all constructor functions e.g. `new F()`
18
+ "noarg": true, // true: Prohibit use of `arguments.caller` and `arguments.callee`
19
+ "noempty": true, // true: Prohibit use of empty blocks
20
+ "nonew": false, // true: Prohibit use of constructors for side-effects (without assignment)
21
+ "plusplus": false, // true: Prohibit use of `++` & `--`
22
+ "quotmark": "single", // Quotation mark consistency:
23
+ // false : do nothing (default)
24
+ // true : ensure whatever is used is consistent
25
+ // "single" : require single quotes
26
+ // "double" : require double quotes
27
+ "undef": true, // true: Require all non-global variables to be declared (prevents global leaks)
28
+ "unused": true, // true: Require all defined variables be used
29
+ "strict": false, // true: Requires all functions run in ES5 Strict Mode
30
+ "trailing": false, // true: Prohibit trailing whitespaces
31
+ "maxparams": false, // {int} Max number of formal params allowed per function
32
+ "maxdepth": false, // {int} Max depth of nested blocks (within functions)
33
+ "maxstatements": false, // {int} Max number statements per function
34
+ "maxcomplexity": false, // {int} Max cyclomatic complexity per function
35
+ "maxlen": false, // {int} Max number of characters per line
36
+
37
+ // Relaxing
38
+ "asi": false, // true: Tolerate Automatic Semicolon Insertion (no semicolons)
39
+ "boss": false, // true: Tolerate assignments where comparisons would be expected
40
+ "debug": true, // true: Allow debugger statements e.g. browser breakpoints.
41
+ "eqnull": false, // true: Tolerate use of `== null`
42
+ "es5": false, // true: Allow ES5 syntax (ex: getters and setters)
43
+ "esversion": 6,
44
+ "esnext": false, // true: Allow ES.next (ES6) syntax (ex: `const`)
45
+ "moz": false, // true: Allow Mozilla specific syntax (extends and overrides esnext features)
46
+ // (ex: `for each`, multiple try/catch, function expression...)
47
+ "evil": false, // true: Tolerate use of `eval` and `new Function()`
48
+ "expr": true, // true: Tolerate `ExpressionStatement` as Programs
49
+ "funcscope": false, // true: Tolerate defining variables inside control statements"
50
+ "globalstrict": false, // true: Allow global "use strict" (also enables 'strict')
51
+ "iterator": false, // true: Tolerate using the `__iterator__` property
52
+ "lastsemic": false, // true: Tolerate omitting a semicolon for the last statement of a 1-line block
53
+ "laxbreak": true, // true: Tolerate possibly unsafe line breakings
54
+ "laxcomma": true, // true: Tolerate comma-first style coding
55
+ "loopfunc": false, // true: Tolerate functions being defined in loops
56
+ "multistr": false, // true: Tolerate multi-line strings
57
+ "proto": false, // true: Tolerate using the `__proto__` property
58
+ "scripturl": false, // true: Tolerate script-targeted URLs
59
+ "smarttabs": true, // true: Tolerate mixed tabs/spaces when used for alignment
60
+ "shadow": false, // true: Allows re-define variables later in code e.g. `var x=1; x=2;`
61
+ "sub": false, // true: Tolerate using `[]` notation when it can still be expressed in dot notation
62
+ "supernew": false, // true: Tolerate `new function () { ... };` and `new Object;`
63
+ "validthis": false, // true: Tolerate using this in a non-constructor function
64
+
65
+ // Environments
66
+ "browser": true, // Web Browser (window, document, etc)
67
+ "couch": false, // CouchDB
68
+ "devel": true, // Development/debugging (alert, confirm, etc)
69
+ "dojo": false, // Dojo Toolkit
70
+ "jquery": true, // jQuery
71
+ "mootools": false, // MooTools
72
+ "node": false, // Node.js
73
+ "nonstandard": false, // Widely adopted globals (escape, unescape, etc)
74
+ "prototypejs": false, // Prototype and Scriptaculous
75
+ "rhino": false, // Rhino
76
+ "worker": false, // Web Workers
77
+ "wsh": false, // Windows Scripting Host
78
+ "yui": false, // Yahoo User Interface
79
+
80
+ // Legacy
81
+ "nomen": false, // true: Prohibit dangling `_` in variables
82
+ "onevar": false, // true: Allow only one `var` statement per function
83
+ "passfail": false, // true: Stop on first error
84
+ "white": false, // true: Check against strict whitespace and indentation rules
85
+
86
+ // Custom Globals
87
+ "globals": {
88
+ "describe": false,
89
+ "it": false,
90
+ "before": false,
91
+ "beforeEach": false,
92
+ "after": false,
93
+ "afterEach": false,
94
+ "module" : false
95
+ }
96
+ }
@@ -0,0 +1,18 @@
1
+ {
2
+ "version": "0.2.0",
3
+ "configurations": [
4
+ {
5
+ "name": "Mocha (Test single file)",
6
+ "type": "node",
7
+ "request": "launch",
8
+ "runtimeArgs": [
9
+ "${workspaceRoot}/node_modules/.bin/mocha",
10
+ "--inspect-brk",
11
+ "${relativeFile}",
12
+ ],
13
+ "console": "integratedTerminal",
14
+ "internalConsoleOptions": "neverOpen",
15
+ "port": 9229
16
+ }
17
+ ]
18
+ }
package/Gruntfile.js ADDED
@@ -0,0 +1,31 @@
1
+ // jshint node:true
2
+ module.exports = function (grunt) {
3
+ grunt.initConfig({
4
+ jshint: {
5
+ options: {
6
+ jshintrc: '.jshintrc',
7
+ },
8
+ files: {
9
+ src: ['*.js']},
10
+ gruntfile: {
11
+ src: 'Gruntfile.js'
12
+ }
13
+ },
14
+ mochaTest: {
15
+ api: {
16
+ options: {
17
+ reporter: 'spec'
18
+ },
19
+ src: ['test/tests.js']
20
+ }
21
+ }
22
+ });
23
+
24
+ grunt.loadNpmTasks('grunt-contrib-jshint');
25
+ grunt.loadNpmTasks('grunt-mocha-test');
26
+
27
+ grunt.registerTask('default', ['jshint', 'mochaTest']);
28
+ grunt.registerTask('api', ['mochaTest']);
29
+
30
+ };
31
+
package/README.md ADDED
@@ -0,0 +1,132 @@
1
+ # cda-schematron-validator
2
+ A fork to the original cda-schematron. All credit to Eric Wadkins. Visit the github https://github.com/ewadkins/cda-schematron for the original repo.
3
+
4
+ This is just a cosmetic change with updated node modules, a couple of minor bugs observed, and esversion 6 changes.
5
+
6
+ The changes are fully backward compatible. So, leaving the original documentation as is below.
7
+
8
+ ### New option parameter parsedSchematronMap
9
+ In addition to everything that was possible,
10
+ you can now supply a new option parameter `parsedSchematronMap`. You can create a schematron map as follows.
11
+
12
+ ```javascript
13
+ const fs = require('fs');
14
+ const dom = require('@xmldom/xmldom').DOMParser;
15
+ const { parseSchematron, validation } = require('cda-schematron-validator');
16
+ const schematronString = fs.readFileSync('SchematronFilePath', 'utf-8').toString();
17
+ const schematronDoc = new dom().parseFromString(schematronString);
18
+ const schematronMap = parseSchematron(schematronDoc);
19
+ const options = {
20
+ parsedSchematronMap: schematronMap
21
+ };
22
+ const results = validate('xml string or file path', 'schematron sting, file path or null', options);
23
+ ```
24
+ If a schematron map is provided, the schematron string or path will not be read.
25
+
26
+ To install this npm module, it will be
27
+
28
+ ```
29
+ npm install cda-schematron-validator
30
+ ```
31
+ Mocha VS Code configuratin added to directly execute the test file in `test/tests.js` using VS Code.
32
+
33
+
34
+ # Original Documentation of the cda-schematron
35
+ # cda-schematron
36
+
37
+ A javascript implementation of schematron testing for XML documents. This specifically resolves a need for a package that allows a quick, reliable install for validating HL7 clinical documents, such as C-CDA.
38
+
39
+ Check out [cda-schematron-server](https://github.com/ewadkins/cda-schematron-server), a server wrapper of **cda-schematron**, for easy schematron validation.
40
+
41
+ ### Validating xml
42
+ ```javascript
43
+ var validator = require('cda-schematron');
44
+
45
+ var xmlPath = 'someFile.xml';
46
+ var schematronPath = 'someFile.sch';
47
+
48
+ var fs = require('fs');
49
+ var xml = fs.readFileSync(xmlPath).toString();
50
+ var schematron = fs.readFileSync(schematronPath).toString();
51
+
52
+ var results = validator.validate(xml, schematron);
53
+ ```
54
+ File paths can also be passed to the validator directly. The following lines all return the same results:
55
+ ```javascript
56
+ var results = validator.validate(xml, schematronPath);
57
+ ```
58
+ ```javascript
59
+ var results = validator.validate(xmlPath, schematron);
60
+ ```
61
+ ```javascript
62
+ var results = validator.validate(xmlPath, schematronPath);
63
+ ```
64
+
65
+ ### Results
66
+ ```results``` is an object containing arrays ```errors```, ```warnings```, and ```ignoreds```.
67
+
68
+ **Errors** and **warnings** are reported as determined by the schematron and test descriptions. They are of the following form:
69
+ ```javascript
70
+ {
71
+ type: type, // "error" or "warning"
72
+ test: test, // xpath test
73
+ simplifiedTest: simplifiedTest, // xpath test with resource values included, if applicable, null otherwise
74
+ description: description, // schematron description of the test case
75
+ line: line, // line number of the violating context
76
+ path: path, // xpath path of the violating context
77
+ patternId: patternId, // schematron-assigned pattern id
78
+ ruleId: ruleId, // schematron-assigned rule id
79
+ assertionId: assertionId, // schematron-assigned assertion id
80
+ context: context, // xpath context of the rule
81
+ xml: xml // xml snippet of the violating context
82
+ }
83
+ ```
84
+
85
+ **Ignored** tests are those that resulted in an exception while running (eg. the test is invalid xpath and could not be parsed properly) and require manual inspection. They are of the following form:
86
+ ```javascript
87
+ {
88
+ errorMessage: errorMessage, // reason for the exception/ignoring the test
89
+ type: type, // "error" or "warning"
90
+ test: test, // xpath test
91
+ simplifiedTest: simplifiedTest, // xpath test with resource values included, if applicable, null otherwise
92
+ description: description, // schematron description of the test case
93
+ patternId: patternId, // schematron-assigned pattern id
94
+ ruleId: ruleId, // schematron-assigned rule id
95
+ assertionId: assertionId, // schematron-assigned assertion id
96
+ context: context, // xpath context of the rule
97
+ }
98
+ ```
99
+
100
+ ### Options
101
+ The ```validate``` function takes in an ```options``` object as an optional third argument. The three fields that can be included in ```options``` are as follows:
102
+
103
+ * **```includeWarnings```**: ```true``` or ```false```, this determines whether or not warnings should be tested and returned. Defaults to ```true```.
104
+
105
+ * **```resourceDir```**: the path to a directory containing resource files (eg. voc.xml) which may be necessary for some schematron tests. Defaults to ```'./'```, the current directory.
106
+
107
+ * **```xmlSnippetMaxLength```**: an integer, which is the maximum length of the ```xml``` field in validation results. Defaults to ```200```. Set to ```0``` for unlimited length.
108
+
109
+ Here is an example with warnings disabled:
110
+
111
+ ```javascript
112
+ var results = validator.validate(xml, schematron, { includeWarnings: false });
113
+ ```
114
+
115
+ ### Cache
116
+ The validator uses a cache to store parsed schematrons, an intermediate data structure used to store revelant schematron information. This reduces the runtime of the validator when validating against the same schematron multiple times. You can clear the cache at any time with:
117
+ ```javascript
118
+ validator.clearCache();
119
+ ```
120
+
121
+ ---
122
+ ## License (MIT)
123
+
124
+ Copyright © 2017 [Eric Wadkins](http://www.ericwadkins.com/)
125
+
126
+ Copyright © 2022 [Priyaranjan (Raj) Tokachichu](https://github.com/priyaranjan-tokachichu)
127
+
128
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
129
+
130
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
131
+
132
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,109 @@
1
+ // jshint node:true
2
+ // jshint shadow:true
3
+ module.exports = modifyTest;
4
+
5
+ const fs = require('fs');
6
+ const xpath = require('xpath');
7
+ const dom = require('@xmldom/xmldom').DOMParser;
8
+ const path_module = require('path');
9
+
10
+ let loadedExternalDocuments = Object.create({});
11
+
12
+ function modifyTest(test, resourceDir) {
13
+
14
+ let matches = /=document\((\'[-_.A-Za-z0-9]+\'|\"[-_.A-Za-z0-9]+\")\)/.exec(test);
15
+ while (matches) {
16
+
17
+ // String processing to select the non-regular predicate expression
18
+ let equalInd = test.indexOf(matches[0]);
19
+ let start = equalInd;
20
+ let bracketDepth = 0;
21
+ for (let i = equalInd; i >= 0; i--) {
22
+ if (!bracketDepth && (test[i] === '[' || test[i] === ' ')) {
23
+ start = i + 1;
24
+ break;
25
+ }
26
+ if (test[i] === ']') {
27
+ bracketDepth++;
28
+ }
29
+ else if (test[i] === '[') {
30
+ bracketDepth--;
31
+ }
32
+ }
33
+
34
+ let end = test.length;
35
+ bracketDepth = 0;
36
+ for (let i = start + matches[0].length; i < test.length; i++) {
37
+ if (!bracketDepth && (test[i] === ']' || test[i] === ' ')) {
38
+ end = i;
39
+ break;
40
+ }
41
+ if (test[i] === '[') {
42
+ bracketDepth++;
43
+ }
44
+ else if (test[i] === ']') {
45
+ bracketDepth--;
46
+ }
47
+ }
48
+
49
+ let predicate = test.slice(start, end);
50
+
51
+ // Load external doc (load from "cache" if already loaded)
52
+ let filepath = matches[1].slice(1, -1);
53
+ let externalDoc;
54
+ if (!loadedExternalDocuments[filepath]) {
55
+ let externalXml = null;
56
+ try {
57
+ externalXml = fs.readFileSync(path_module.join(resourceDir, filepath), 'utf-8').toString();
58
+ }
59
+ catch (err) {
60
+ throw new Error('No such file \'' + filepath + '\'');
61
+ }
62
+ externalDoc = new dom().parseFromString(externalXml);
63
+ loadedExternalDocuments[filepath] = externalDoc;
64
+ }
65
+ else {
66
+ externalDoc = loadedExternalDocuments[filepath];
67
+ }
68
+
69
+ let externalXpath = test.slice(equalInd + matches[0].length, end);
70
+
71
+ // Extract namespaces
72
+ let defaultNamespaceKey = /([^(<>.\/)]+):[^(<>.\/)]+/.exec(externalXpath)[1];
73
+ let externalNamespaceMap = externalDoc.lastChild._nsMap;
74
+ let namespaceMap = {};
75
+ for (let key in externalNamespaceMap) {
76
+ if (externalNamespaceMap.hasOwnProperty(key)) {
77
+ if (key) {
78
+ namespaceMap[key] = externalNamespaceMap[key];
79
+ }
80
+ }
81
+ }
82
+ namespaceMap[defaultNamespaceKey] = externalNamespaceMap[''];
83
+
84
+ let externalSelect = xpath.useNamespaces(namespaceMap);
85
+
86
+ // Create new predicate from extract values
87
+ let values = [];
88
+ let externalResults = externalSelect(externalXpath, externalDoc);
89
+ for (let i = 0; i < externalResults.length; i++) {
90
+ values.push(externalResults[i].value);
91
+ }
92
+ let lhv = predicate.slice(0, predicate.indexOf('=document('));
93
+ let newPredicate = '(';
94
+ for (let i = 0; i < values.length; i++) {
95
+ newPredicate += lhv + '=\'' + values[i] + '\'';
96
+ if (i < values.length - 1) {
97
+ newPredicate += ' or ';
98
+ }
99
+ }
100
+ newPredicate += ')';
101
+
102
+ // Replace test
103
+ test = test.slice(0, start) + newPredicate + test.slice(end);
104
+
105
+ matches = /@[^\[\]]+=document\((\'[-_.A-Za-z0-9]+\'|\"[-_.A-Za-z0-9]+\")\)/.exec(test);
106
+ }
107
+
108
+ return test;
109
+ }
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "cda-schematron-validator",
3
+ "version": "1.0.0",
4
+ "description": "Fork of Eric Wadkins' javascript implementation of schematron testing for C-CDA XML documents. This includes bug fixes and some house keeping.",
5
+ "main": "validator.js",
6
+ "scripts": {
7
+ "test": "grunt"
8
+ },
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/priyaranjan-tokachichu/cda-schematron-validator.git"
12
+ },
13
+ "author": "Eric Wadkins",
14
+ "contributors": [
15
+ {
16
+ "name" : "Priyaranjan (Raj) Tokachichu",
17
+ "email" : "priyaranjan@priyaranjan.com",
18
+ "url" : "https://github.com/priyaranjan-tokachichu"
19
+ }
20
+ ],
21
+ "license": "MIT",
22
+ "bugs": {
23
+ "url": "https://github.com/priyaranjan-tokachichu/cda-schematron-validator/issues"
24
+ },
25
+ "homepage": "https://github.com/priyaranjan-tokachichu/cda-schematron-validator#readme",
26
+ "devDependencies": {
27
+ "chai": "~4.3.6",
28
+ "grunt": "~1.4.1",
29
+ "grunt-contrib-jshint": "~3.2.0",
30
+ "grunt-mocha-test": "~0.13.3",
31
+ "mocha": "~9.2.2"
32
+ },
33
+ "dependencies": {
34
+ "@xmldom/xmldom": "~0.7.2",
35
+ "xpath": "~0.0.32"
36
+ },
37
+ "directories": {
38
+ "test": "test"
39
+ },
40
+ "keywords": [
41
+ "C-CDA",
42
+ "HL7",
43
+ "Schematron",
44
+ "CCD",
45
+ "XML"
46
+ ]
47
+ }
@@ -0,0 +1,122 @@
1
+ // jshint node:true
2
+ // jshint shadow:true
3
+ module.exports = parseSchematron;
4
+
5
+ const xpath = require('xpath');
6
+
7
+ function parseSchematron(doc) {
8
+ // Extract data from schematron
9
+ let schematronData = extract(doc);
10
+
11
+ return schematronData;
12
+ }
13
+
14
+ function extract(doc) {
15
+ let namespaceMap = Object.create({});
16
+ let patternLevelMap = Object.create({});
17
+ let patternRuleMap = Object.create({});
18
+ let ruleAssertionMap = Object.create({});
19
+
20
+ //// Namespace mapping
21
+ let namespaces = xpath.select('//*[local-name()="ns"]', doc);
22
+ for (let i = 0; i < namespaces.length; i++) {
23
+ namespaceMap[namespaces[i].getAttribute('prefix')] = namespaces[i].getAttribute('uri');
24
+ }
25
+
26
+ //// Pattern to level mapping
27
+
28
+ // Find errors phases
29
+ let errorPhase = xpath.select('//*[local-name()="phase" and @id="errors"]', doc);
30
+
31
+ // Store error patterns
32
+ if (errorPhase.length) {
33
+ for (let i = 0; i < errorPhase[0].childNodes.length; i++) {
34
+ if (errorPhase[0].childNodes[i].localName === 'active') {
35
+ patternLevelMap[errorPhase[0].childNodes[i].getAttribute('pattern')] = 'error';
36
+ }
37
+ }
38
+ }
39
+
40
+ // Find errors phases
41
+ let warningPhase = xpath.select('//*[local-name()="phase" and @id="warnings"]', doc);
42
+
43
+ // Store warning patterns
44
+ if (warningPhase.length) {
45
+ for (let i = 0; i < warningPhase[0].childNodes.length; i++) {
46
+ if (warningPhase[0].childNodes[i].localName === 'active') {
47
+ patternLevelMap[warningPhase[0].childNodes[i].getAttribute('pattern')] = 'warning';
48
+ }
49
+ }
50
+ }
51
+
52
+ //// Pattern to rule and rule to assertion mapping
53
+
54
+ // Find patterns
55
+ let patterns = xpath.select('//*[local-name()="pattern"]', doc);
56
+
57
+ // Map patterns to rules
58
+ for (let i = 0; i < patterns.length; i++) {
59
+ let patternId = patterns[i].getAttribute('id');
60
+ let defaultLevel = patternLevelMap[patternId] || 'warning';
61
+ patternRuleMap[patternId] = [];
62
+ let rules = xpath.select('./*[local-name()="rule"]', patterns[i]);
63
+ for (let j = 0; j < rules.length; j++) {
64
+ patternRuleMap[patternId].push(rules[j].getAttribute('id'));
65
+ ruleAssertionMap[rules[j].getAttribute('id')] = {
66
+ abstract: parseAbstract(rules[j].getAttribute('abstract')),
67
+ context: parseContext(rules[j].getAttribute('context')),
68
+ assertionsAndExtensions: getAssertionsAndExtensions(rules[j], defaultLevel)
69
+ };
70
+ }
71
+ }
72
+
73
+ return {
74
+ namespaceMap: namespaceMap,
75
+ patternRuleMap: patternRuleMap,
76
+ ruleAssertionMap: ruleAssertionMap
77
+ };
78
+ }
79
+
80
+ function getAssertionsAndExtensions(rule, defaultLevel) {
81
+ let assertionsAndExtensions = [];
82
+
83
+ // Find and store assertions
84
+ let assertions = xpath.select('./*[local-name()="assert"]', rule);
85
+ for (let i = 0; i < assertions.length; i++) {
86
+ let description = assertions[i].childNodes[0] ? assertions[i].childNodes[0].data : '';
87
+ let level = defaultLevel;
88
+ if (description.indexOf('SHALL') !== -1
89
+ && (description.indexOf('SHOULD') === -1 || description.indexOf('SHALL') < description.indexOf('SHOULD'))) {
90
+ level = 'error';
91
+ }
92
+ assertionsAndExtensions.push({
93
+ type: 'assertion',
94
+ level: level,
95
+ id: assertions[i].getAttribute('id'),
96
+ test: assertions[i].getAttribute('test'),
97
+ description: description
98
+ });
99
+ }
100
+
101
+ // Find and store extensions
102
+ let extensions = xpath.select('./*[local-name()="extends"]', rule);
103
+ for (let i = 0; i < extensions.length; i++) {
104
+ assertionsAndExtensions.push({
105
+ type: 'extension',
106
+ rule: extensions[i].getAttribute('rule'),
107
+ });
108
+ }
109
+
110
+ return assertionsAndExtensions;
111
+ }
112
+
113
+ function parseAbstract(str) {
114
+ if (str === 'true' || str === 'yes') {
115
+ return true;
116
+ }
117
+ return false;
118
+ }
119
+
120
+ function parseContext(str) {
121
+ return str || null;
122
+ }
package/test/test.sch ADDED
@@ -0,0 +1,47 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <sch:schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:sch="http://purl.oclc.org/dsdl/schematron">
3
+ <sch:ns prefix="dh" uri="urn:dh" />
4
+ <sch:phase id="errors">
5
+ <sch:active pattern="A" />
6
+ <sch:active pattern="B" />
7
+ <sch:active pattern="C" />
8
+ <sch:active pattern="E" />
9
+ </sch:phase>
10
+ <sch:phase id="warnings">
11
+ <sch:active pattern="D" />
12
+ </sch:phase>
13
+ <sch:pattern id="A">
14
+ <sch:rule id="A-rule" context="dh:test[@root='A']">
15
+ <sch:assert id="A-assert" test="count(dh:element)=1">Should only have one element</sch:assert>
16
+ </sch:rule>
17
+ </sch:pattern>
18
+ <sch:pattern id="B">
19
+ <sch:rule id="B-rule-1" context="dh:test[@root]">
20
+ <sch:assert id="B-assert-2" test="count(dh:element)=1">Each section should have 1 element</sch:assert>
21
+ </sch:rule>
22
+ <sch:rule id="B-rule-2">
23
+ <sch:assert id="B-assert-1" test="count(//dh:element)=18">Should have 18 elements total element</sch:assert>
24
+ </sch:rule>
25
+ </sch:pattern>
26
+ <sch:pattern id="C">
27
+ <sch:rule id="C-rule-1">
28
+ <sch:assert id="C-assert-1" test="//dh:element[@attribute]">Each element should have the attribute attribute</sch:assert>
29
+ </sch:rule>
30
+ <sch:rule id="C-rule-2" context="dh:test[@root]">
31
+ <sch:assert id="C-assert-2" test="dh:element[@attribute]">Each element should have the attribute attribute</sch:assert>
32
+ </sch:rule>
33
+ </sch:pattern>
34
+ <sch:pattern id="D">
35
+ <sch:rule id="D-rule-1">
36
+ <sch:assert id="D-assert-1" test="//dh:element[count(dh:child)=1]">Each element should have the attribute attribute</sch:assert>
37
+ </sch:rule>
38
+ <sch:rule id="D-rule-2" context="dh:test[@root]">
39
+ <sch:assert id="D-assert-2" test="dh:element[count(dh:child)=1]">Each element should have the attribute attribute</sch:assert>
40
+ </sch:rule>
41
+ </sch:pattern>
42
+ <sch:pattern id="E">
43
+ <sch:rule id="E-rule-1">
44
+ <sch:assert id="E-assert-1" test="not (dh:element[count(dh:child)=1])">This is an invalid test</sch:assert>
45
+ </sch:rule>
46
+ </sch:pattern>
47
+ </sch:schema>
package/test/test.xml ADDED
@@ -0,0 +1,80 @@
1
+ <xml xmlns="urn:dh">
2
+ <!-- count of elements -->
3
+ <test root="A">
4
+ <element>true</element>
5
+ </test>
6
+ <test root="A">
7
+ <element>false</element>
8
+ <element>false</element>
9
+ </test>
10
+ <!-- attibute equivalence -->
11
+ <test root="B">
12
+ <element atttribute="ok">true</element>
13
+ </test>
14
+ <test root="B">
15
+ <element atttribute="notok">false</element>
16
+ </test>
17
+ <!-- child presence -->
18
+ <test root="C">
19
+ <element>
20
+ <child>true</child>
21
+ </element>
22
+ </test>
23
+ <test root="C">
24
+ <element>
25
+ <notchild>false</notchild>
26
+ </element>
27
+ </test>
28
+ <!-- conditional child presence -->
29
+ <test root="D">
30
+ <element attribute="needChild">
31
+ <child>true</child>
32
+ </element>
33
+ </test>
34
+ <test root="D">
35
+ <element attribute="needNoChild">true</element>
36
+ </test>
37
+ <test root="D">
38
+ <element attribute="needChild">false</element>
39
+ </test>
40
+ <!-- OR presence -->
41
+ <test root="E">
42
+ <element>
43
+ <firstChild>true</firstChild>
44
+ </element>
45
+ </test>
46
+ <test root="E">
47
+ <element>
48
+ <secondChild>true</secondChild>
49
+ </element>
50
+ </test>
51
+ <test root="E">
52
+ <element>
53
+ <notChild>false</notChild>
54
+ </element>
55
+ </test>
56
+ <!-- AND presence -->
57
+ <test root="F">
58
+ <element>
59
+ <firstChild>true</firstChild>
60
+ <secondChild>true</secondChild>
61
+ </element>
62
+ </test>
63
+ <test root="F">
64
+ <element>
65
+ <secondChild>false</secondChild>
66
+ </element>
67
+ </test>
68
+ <test root="F">
69
+ <element>
70
+ <notChild>false</notChild>
71
+ </element>
72
+ </test>
73
+ <!-- Element value -->
74
+ <test root="G">
75
+ <element>true</element>
76
+ </test>
77
+ <test root="G">
78
+ <element>false</element>
79
+ </test>
80
+ </xml>
package/test/tests.js ADDED
@@ -0,0 +1,141 @@
1
+ const fs = require('fs');
2
+ const expect = require('chai').expect;
3
+
4
+ const validator = require('../validator');
5
+
6
+ // Which xml file to test
7
+ const xmlPath = './test/test.xml';
8
+ // Which schematron to test against
9
+ const schematronPath = './test/test.sch';
10
+
11
+ const xml = fs.readFileSync(xmlPath, 'utf-8').toString();
12
+ const schematron = fs.readFileSync(schematronPath, 'utf-8').toString();
13
+
14
+ describe('Validator should', function() {
15
+ let results;
16
+ it('return results', function(done) {
17
+ results = validator.validate(xml, schematron);
18
+ expect(results).to.be.an('object');
19
+ done();
20
+ });
21
+ it('return errorCount', function(done) {
22
+ expect(results.errorCount).to.be.a('number');
23
+ done();
24
+ });
25
+ it('return warningCount', function(done) {
26
+ expect(results.warningCount).to.be.a('number');
27
+ done();
28
+ });
29
+ it('return ignoredCount', function(done) {
30
+ expect(results.ignoredCount).to.be.a('number');
31
+ done();
32
+ });
33
+ it('return errors array', function(done) {
34
+ expect(results.errors).to.be.a('array');
35
+ done();
36
+ });
37
+ it('return warnings array', function(done) {
38
+ expect(results.warnings).to.be.a('array');
39
+ done();
40
+ });
41
+ it('return ignored array', function(done) {
42
+ expect(results.ignored).to.be.a('array');
43
+ done();
44
+ });
45
+ it('return matching errorCount', function(done) {
46
+ expect(results.errorCount).to.be.equal(results.errors.length);
47
+ done();
48
+ });
49
+ it('return matching warningCount', function(done) {
50
+ expect(results.warningCount).to.be.equal(results.warnings.length);
51
+ done();
52
+ });
53
+ it('return matching ignoredCount', function(done) {
54
+ expect(results.ignoredCount).to.be.equal(results.ignored.length);
55
+ done();
56
+ });
57
+ it('return correct number of errors', function(done) {
58
+ expect(results.errorCount).to.be.equal(16);
59
+ done();
60
+ });
61
+ it('return correct number of warnings', function(done) {
62
+ expect(results.warningCount).to.be.equal(15);
63
+ done();
64
+ });
65
+ it('return correct number of ignored', function(done) {
66
+ expect(results.ignoredCount).to.be.equal(1);
67
+ done();
68
+ });
69
+
70
+ it('return similar results without warnings', function(done) {
71
+ results = validator.validate(xml, schematron, { includeWarnings: false });
72
+ expect(results).to.be.an('object');
73
+ expect(results.errorCount).to.be.a('number');
74
+ expect(results.warningCount).to.be.a('number');
75
+ expect(results.ignoredCount).to.be.a('number');
76
+ expect(results.errors).to.be.a('array');
77
+ expect(results.warnings).to.be.a('array');
78
+ expect(results.ignored).to.be.a('array');
79
+ expect(results.errorCount).to.be.equal(results.errors.length);
80
+ expect(results.warningCount).to.be.equal(results.warnings.length);
81
+ expect(results.ignoredCount).to.be.equal(results.ignored.length);
82
+ expect(results.errorCount).to.be.equal(16);
83
+ expect(results.warningCount).to.be.equal(0);
84
+ expect(results.ignoredCount).to.be.equal(1);
85
+ done();
86
+ });
87
+
88
+ it('return similar results given xml filepath', function(done) {
89
+ results = validator.validate(xmlPath, schematron);
90
+ expect(results).to.be.an('object');
91
+ expect(results.errorCount).to.be.a('number');
92
+ expect(results.warningCount).to.be.a('number');
93
+ expect(results.ignoredCount).to.be.a('number');
94
+ expect(results.errors).to.be.a('array');
95
+ expect(results.warnings).to.be.a('array');
96
+ expect(results.ignored).to.be.a('array');
97
+ expect(results.errorCount).to.be.equal(results.errors.length);
98
+ expect(results.warningCount).to.be.equal(results.warnings.length);
99
+ expect(results.ignoredCount).to.be.equal(results.ignored.length);
100
+ expect(results.errorCount).to.be.equal(16);
101
+ expect(results.warningCount).to.be.equal(15);
102
+ expect(results.ignoredCount).to.be.equal(1);
103
+ done();
104
+ });
105
+
106
+ it('return similar results given schematron filepath', function(done) {
107
+ results = validator.validate(xml, schematronPath);
108
+ expect(results).to.be.an('object');
109
+ expect(results.errorCount).to.be.a('number');
110
+ expect(results.warningCount).to.be.a('number');
111
+ expect(results.ignoredCount).to.be.a('number');
112
+ expect(results.errors).to.be.a('array');
113
+ expect(results.warnings).to.be.a('array');
114
+ expect(results.ignored).to.be.a('array');
115
+ expect(results.errorCount).to.be.equal(results.errors.length);
116
+ expect(results.warningCount).to.be.equal(results.warnings.length);
117
+ expect(results.ignoredCount).to.be.equal(results.ignored.length);
118
+ expect(results.errorCount).to.be.equal(16);
119
+ expect(results.warningCount).to.be.equal(15);
120
+ expect(results.ignoredCount).to.be.equal(1);
121
+ done();
122
+ });
123
+
124
+ it('return similar results given xml filepath and schematron filepath', function(done) {
125
+ results = validator.validate(xmlPath, schematronPath);
126
+ expect(results).to.be.an('object');
127
+ expect(results.errorCount).to.be.a('number');
128
+ expect(results.warningCount).to.be.a('number');
129
+ expect(results.ignoredCount).to.be.a('number');
130
+ expect(results.errors).to.be.a('array');
131
+ expect(results.warnings).to.be.a('array');
132
+ expect(results.ignored).to.be.a('array');
133
+ expect(results.errorCount).to.be.equal(results.errors.length);
134
+ expect(results.warningCount).to.be.equal(results.warnings.length);
135
+ expect(results.ignoredCount).to.be.equal(results.ignored.length);
136
+ expect(results.errorCount).to.be.equal(16);
137
+ expect(results.warningCount).to.be.equal(15);
138
+ expect(results.ignoredCount).to.be.equal(1);
139
+ done();
140
+ });
141
+ });
@@ -0,0 +1,73 @@
1
+ // jshint node:true
2
+ // jshint shadow:true
3
+ module.exports = testAssertion;
4
+
5
+ function testAssertion(test, selected, select, xmlDoc, resourceDir, xmlSnippetMaxLength) {
6
+ let results = [];
7
+
8
+ for (let i = 0; i < selected.length; i++) {
9
+ try {
10
+ let result = select('boolean(' + test + ')', selected[i]);
11
+ let lineNumber = null;
12
+ let xmlSnippet = null;
13
+ if (selected[i].lineNumber) {
14
+ lineNumber = selected[i].lineNumber;
15
+ xmlSnippet = selected[i].toString();
16
+ }
17
+ let maxLength = (xmlSnippetMaxLength || 1e308);
18
+ if (xmlSnippet && xmlSnippet.length > maxLength) {
19
+ xmlSnippet = xmlSnippet.slice(0, maxLength) + '...';
20
+ }
21
+ results.push({ result: result, line: lineNumber, path: getXPath(selected[i]), xml: xmlSnippet });
22
+ }
23
+ catch (err) {
24
+ return { ignored: true, errorMessage: err.message };
25
+ }
26
+ }
27
+
28
+ for (let i = 0; i < results.length; i++) {
29
+ if (results[i].result !== true && results[i].result !== false) {
30
+ return { ignored: true, errorMessage: 'Test returned non-boolean result' };
31
+ }
32
+ }
33
+ return results;
34
+ }
35
+
36
+ function getXPath(node, path) {
37
+ let top = !path ? true : false;
38
+ path = path || [];
39
+ if (node.parentNode) {
40
+ path = getXPath(node.parentNode, path);
41
+ }
42
+
43
+ let count = 1;
44
+ if (node.previousSibling) {
45
+ let sibling = node.previousSibling;
46
+ do {
47
+ if (sibling.nodeType === 1 && sibling.nodeName === node.nodeName) {
48
+ count++;
49
+ }
50
+ sibling = sibling.previousSibling;
51
+ } while (sibling);
52
+ if (count === 1) {
53
+ count = null;
54
+ }
55
+ }
56
+ else if (node.nextSibling) {
57
+ let sibling = node.nextSibling;
58
+ do {
59
+ if (sibling.nodeType === 1 && sibling.nodeName === node.nodeName) {
60
+ count = 1;
61
+ sibling = null;
62
+ } else {
63
+ count = null;
64
+ sibling = sibling.previousSibling;
65
+ }
66
+ } while (sibling);
67
+ }
68
+
69
+ if (node.nodeType === 1) {
70
+ path.push(node.nodeName + ('[' + (count || 1) + ']'));
71
+ }
72
+ return top ? '/' + path.join('/') : path;
73
+ }
package/validator.js ADDED
@@ -0,0 +1,228 @@
1
+ // jshint node:true
2
+ // jshint shadow:true
3
+
4
+ module.exports = {
5
+ validate: validate,
6
+ clearCache: clearCache,
7
+ parseSchematron: require('./parseSchematron')
8
+ };
9
+
10
+ const fs = require('fs');
11
+ const xpath = require('xpath');
12
+ const dom = require('@xmldom/xmldom').DOMParser;
13
+ // crypto is now built-in node
14
+ const crypto = require('crypto');
15
+
16
+ const parseSchematron = require('./parseSchematron');
17
+ const testAssertion = require('./testAssertion');
18
+ const includeExternalDocument = require('./includeExternalDocument');
19
+
20
+ // Parsed object cache
21
+ let parsedMap = Object.create({});
22
+ let contextMap = Object.create({});
23
+
24
+ function clearCache() {
25
+ parsedMap = Object.create({});
26
+ contextMap = Object.create({});
27
+ }
28
+
29
+ function validate(xml, schematron, options = {}) {
30
+ // If not valid xml, it might be a filepath
31
+ // Adding explicit check to make it clear
32
+ if (xml.trim().indexOf('<') === -1) {
33
+ try {
34
+ xml = fs.readFileSync(xml, 'utf-8').toString();
35
+ }
36
+ catch (err) {
37
+ // If no valid xml found, inform user, and return immediately
38
+ console.log('No valid xml could be found');
39
+ return;
40
+ }
41
+ }
42
+
43
+ let schematronMap;
44
+ // Load xml doc
45
+ let xmlDoc = new dom().parseFromString(xml);
46
+ // Allowing users to send a parsed schematron map if testing multiple xml files with the same schematron
47
+ if (options.parsedSchematronMap) {
48
+ schematronMap = options.parsedSchematronMap;
49
+ }
50
+ else {
51
+ // If not valid schematron (xml), it might be a filepath
52
+ // Adding explicit check to make it clear
53
+ if (schematron.trim().indexOf('<') === -1) {
54
+ try {
55
+ schematron = fs.readFileSync(schematron, 'utf-8').toString();
56
+ }
57
+ catch (err) {
58
+ // If no valid schematron found, inform user, and return immediately
59
+ console.log('No valid schematron could be found');
60
+ return;
61
+ }
62
+ }
63
+ let hash = crypto
64
+ .createHash('md5')
65
+ .update(schematron)
66
+ .digest('hex');
67
+ schematronMap = parsedMap[hash];
68
+ // If not in cache
69
+ if (!schematronMap) {
70
+ // Load schematron doc
71
+ let schematronDoc = new dom().parseFromString(schematron);
72
+
73
+ // Parse schematron
74
+ schematronMap = parseSchematron(schematronDoc);
75
+
76
+ // Cache parsed schematron
77
+ parsedMap[hash] = schematronMap;
78
+ }
79
+ }
80
+
81
+ // Extract data from parsed schematron object
82
+ let namespaceMap = schematronMap.namespaceMap;
83
+ let patternRuleMap = schematronMap.patternRuleMap;
84
+ let ruleAssertionMap = schematronMap.ruleAssertionMap;
85
+
86
+ // Create selector object, initialized with namespaces
87
+ // Avoid using 'select' as a variable name as it is overused
88
+ const xpathSelect = xpath.useNamespaces(namespaceMap);
89
+
90
+ let errors = [];
91
+ let warnings = [];
92
+ let ignored = [];
93
+ for (let pattern in patternRuleMap) {
94
+ if (!patternRuleMap.hasOwnProperty(pattern)) {
95
+ continue;
96
+ }
97
+ let patternId = pattern;
98
+ let rules = patternRuleMap[pattern];
99
+ for (let i = 0; i < rules.length; i++) {
100
+ if (ruleAssertionMap[rules[i]].abstract) {
101
+ continue;
102
+ }
103
+ let ruleId = rules[i];
104
+ let context = ruleAssertionMap[rules[i]].context;
105
+ let assertionsAndExtensions = ruleAssertionMap[rules[i]].assertionsAndExtensions || [];
106
+ let assertionResults = checkRule(xmlDoc, xpathSelect, context, assertionsAndExtensions, options);
107
+ for (let j = 0; j < assertionResults.length; j++) {
108
+ let type = assertionResults[j].type;
109
+ let assertionId = assertionResults[j].assertionId;
110
+ let test = assertionResults[j].test;
111
+ let simplifiedTest = assertionResults[j].simplifiedTest;
112
+ let description = assertionResults[j].description;
113
+ let errorMessage = assertionResults[j].errorMessage;
114
+ let results = assertionResults[j].results;
115
+ if (!results.ignored) {
116
+ for (let k = 0; k < results.length; k++) {
117
+ let result = results[k].result;
118
+ let line = results[k].line;
119
+ let path = results[k].path;
120
+ let xmlSnippet = results[k].xml;
121
+ if (!result) {
122
+ let obj = {
123
+ type: type,
124
+ test: test,
125
+ simplifiedTest: simplifiedTest,
126
+ description: description,
127
+ line: line,
128
+ path: path,
129
+ patternId: patternId,
130
+ ruleId: ruleId,
131
+ assertionId: assertionId,
132
+ context: context,
133
+ xml: xmlSnippet
134
+ };
135
+ if (type === 'error') {
136
+ errors.push(obj);
137
+ }
138
+ else {
139
+ warnings.push(obj);
140
+ }
141
+ }
142
+ }
143
+ }
144
+ else {
145
+ let obj = {
146
+ errorMessage: errorMessage,
147
+ type: type,
148
+ test: test,
149
+ simplifiedTest: simplifiedTest,
150
+ description: description,
151
+ patternId: patternId,
152
+ ruleId: ruleId,
153
+ assertionId: assertionId,
154
+ context: context
155
+ };
156
+ ignored.push(obj);
157
+ }
158
+ }
159
+ }
160
+ }
161
+
162
+ return {
163
+ errorCount: errors.length,
164
+ warningCount: warnings.length,
165
+ ignoredCount: ignored ? ignored.length : 0,
166
+ errors: errors,
167
+ warnings: warnings,
168
+ ignored: ignored
169
+ };
170
+ }
171
+
172
+ // Take the checkRule function out of validate function, and pass on the variable needed as parameters and options
173
+ function checkRule(xmlDoc, xpathSelect, originalContext, assertionsAndExtensions, options) {
174
+ // Context cache
175
+ let includeWarnings = options.includeWarnings === undefined ? true : options.includeWarnings;
176
+ let resourceDir = options.resourceDir || './';
177
+ let xmlSnippetMaxLength = options.xmlSnippetMaxLength === undefined ? 200 : options.xmlSnippetMaxLength;
178
+ let results = [];
179
+ let context = options.contextOverride || originalContext;
180
+ // Determine the sections within context, load selected section from cache if possible
181
+ let selected = contextMap[context];
182
+ let contextModified = context;
183
+ if (!selected) {
184
+ if (context) {
185
+ if (context.indexOf('/')) {
186
+ contextModified = '//' + context;
187
+ }
188
+ selected = xpathSelect(contextModified, xmlDoc);
189
+ }
190
+ else {
191
+ selected = [xmlDoc];
192
+ }
193
+ contextMap[context] = selected;
194
+ }
195
+
196
+ for (let i = 0; i < assertionsAndExtensions.length; i++) {
197
+ if (assertionsAndExtensions[i].type === 'assertion') {
198
+ let type = assertionsAndExtensions[i].level;
199
+ let test = assertionsAndExtensions[i].test;
200
+
201
+ // Extract values from external document and modify test if a document call is made
202
+ let originalTest = test;
203
+ try {
204
+ test = includeExternalDocument(test, resourceDir);
205
+ }
206
+ catch (err) {
207
+ return { ignored: true, errorMessage: err.message };
208
+ }
209
+
210
+ let simplifiedTest = null;
211
+ if (originalTest !== test) {
212
+ simplifiedTest = test;
213
+ }
214
+ if (type === 'error' || includeWarnings) {
215
+ results.push({
216
+ type: type,
217
+ assertionId: assertionsAndExtensions[i].id,
218
+ test: originalTest,
219
+ simplifiedTest: simplifiedTest,
220
+ description: assertionsAndExtensions[i].description,
221
+ results: testAssertion(test, selected, xpathSelect, xmlDoc, resourceDir, xmlSnippetMaxLength)
222
+ });
223
+ }
224
+ }
225
+ // removed recursive call to checkRule as it just returns an emptry array
226
+ }
227
+ return results;
228
+ }