cda-schematron-validator 1.0.6 → 1.0.7

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.
@@ -0,0 +1,70 @@
1
+ # For most projects, this workflow file will not need changing; you simply need
2
+ # to commit it to your repository.
3
+ #
4
+ # You may wish to alter this file to override the set of languages analyzed,
5
+ # or to provide custom queries or build logic.
6
+ #
7
+ # ******** NOTE ********
8
+ # We have attempted to detect the languages in your repository. Please check
9
+ # the `language` matrix defined below to confirm you have the correct set of
10
+ # supported CodeQL languages.
11
+ #
12
+ name: "CodeQL"
13
+
14
+ on:
15
+ push:
16
+ branches: [ main ]
17
+ pull_request:
18
+ # The branches below must be a subset of the branches above
19
+ branches: [ main ]
20
+ schedule:
21
+ - cron: '34 18 * * 4'
22
+
23
+ jobs:
24
+ analyze:
25
+ name: Analyze
26
+ runs-on: ubuntu-latest
27
+ permissions:
28
+ actions: read
29
+ contents: read
30
+ security-events: write
31
+
32
+ strategy:
33
+ fail-fast: false
34
+ matrix:
35
+ language: [ 'javascript' ]
36
+ # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]
37
+ # Learn more about CodeQL language support at https://git.io/codeql-language-support
38
+
39
+ steps:
40
+ - name: Checkout repository
41
+ uses: actions/checkout@v3
42
+
43
+ # Initializes the CodeQL tools for scanning.
44
+ - name: Initialize CodeQL
45
+ uses: github/codeql-action/init@v2
46
+ with:
47
+ languages: ${{ matrix.language }}
48
+ # If you wish to specify custom queries, you can do so here or in a config file.
49
+ # By default, queries listed here will override any specified in a config file.
50
+ # Prefix the list here with "+" to use these queries and those in the config file.
51
+ # queries: ./path/to/local/query, your-org/your-repo/queries@main
52
+
53
+ # Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
54
+ # If this step fails, then you should remove it and run the build manually (see below)
55
+ - name: Autobuild
56
+ uses: github/codeql-action/autobuild@v2
57
+
58
+ # ℹ️ Command-line programs to run using the OS shell.
59
+ # 📚 https://git.io/JvXDl
60
+
61
+ # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
62
+ # and modify them (or add more) to build your code if your project
63
+ # uses a compiled language
64
+
65
+ #- run: |
66
+ # make bootstrap
67
+ # make release
68
+
69
+ - name: Perform CodeQL Analysis
70
+ uses: github/codeql-action/analyze@v2
package/README.md CHANGED
@@ -1,4 +1,12 @@
1
- # cda-schematron-validator
1
+ # [cda-schematron-validator](https://github.com/priyaranjan-tokachichu/cda-schematron-validator)
2
+ ## Release History
3
+ Starting release history with 1.0.7
4
+ ### 1.0.7
5
+ - Added async validate function `validateAsync`
6
+ - Added `testsAsync` to test `validateAsync`
7
+ - Plan to use common functions between sync and async methods in the future release
8
+
9
+ ### 1.0.0 to 1.0.6
2
10
  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
11
 
4
12
  This is just a cosmetic change with updated node modules, a couple of minor bugs observed, and esversion 6 changes.
@@ -32,7 +40,7 @@ Mocha VS Code configuratin added to directly execute the test file in `test/test
32
40
 
33
41
 
34
42
  # Original Documentation of the cda-schematron
35
- # cda-schematron
43
+ ## [cda-schematron](https://github.com/ewadkins/cda-schematron)
36
44
 
37
45
  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
46
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cda-schematron-validator",
3
- "version": "1.0.6",
3
+ "version": "1.0.7",
4
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
5
  "main": "validator.js",
6
6
  "scripts": {
@@ -0,0 +1,124 @@
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', async function() {
17
+ results = await validator.validateAsync(xml, schematron);
18
+ expect(results).to.be.an('object');
19
+ });
20
+ it('return errorCount', function() {
21
+ expect(results.errorCount).to.be.a('number');
22
+ });
23
+ it('return warningCount', function() {
24
+ expect(results.warningCount).to.be.a('number');
25
+ });
26
+ it('return ignoredCount', function() {
27
+ expect(results.ignoredCount).to.be.a('number');
28
+ });
29
+ it('return errors array', function() {
30
+ expect(results.errors).to.be.a('array');
31
+ });
32
+ it('return warnings array', function() {
33
+ expect(results.warnings).to.be.a('array');
34
+ });
35
+ it('return ignored array', function() {
36
+ expect(results.ignored).to.be.a('array');
37
+ });
38
+ it('return matching errorCount', function() {
39
+ expect(results.errorCount).to.be.equal(results.errors.length);
40
+ });
41
+ it('return matching warningCount', function() {
42
+ expect(results.warningCount).to.be.equal(results.warnings.length);
43
+ });
44
+ it('return matching ignoredCount', function() {
45
+ expect(results.ignoredCount).to.be.equal(results.ignored.length);
46
+ });
47
+ it('return correct number of errors', function() {
48
+ expect(results.errorCount).to.be.equal(16);
49
+ });
50
+ it('return correct number of warnings', function() {
51
+ expect(results.warningCount).to.be.equal(15);
52
+ });
53
+ it('return correct number of ignored', function() {
54
+ expect(results.ignoredCount).to.be.equal(1);
55
+ });
56
+
57
+ it('return similar results without warnings', async function() {
58
+ results = await validator.validateAsync(xml, schematron, { includeWarnings: false });
59
+ expect(results).to.be.an('object');
60
+ expect(results.errorCount).to.be.a('number');
61
+ expect(results.warningCount).to.be.a('number');
62
+ expect(results.ignoredCount).to.be.a('number');
63
+ expect(results.errors).to.be.a('array');
64
+ expect(results.warnings).to.be.a('array');
65
+ expect(results.ignored).to.be.a('array');
66
+ expect(results.errorCount).to.be.equal(results.errors.length);
67
+ expect(results.warningCount).to.be.equal(results.warnings.length);
68
+ expect(results.ignoredCount).to.be.equal(results.ignored.length);
69
+ expect(results.errorCount).to.be.equal(16);
70
+ expect(results.warningCount).to.be.equal(0);
71
+ expect(results.ignoredCount).to.be.equal(1);
72
+ });
73
+
74
+ it('return similar results given xml filepath', async function() {
75
+ results = await validator.validateAsync(xmlPath, schematron);
76
+ expect(results).to.be.an('object');
77
+ expect(results.errorCount).to.be.a('number');
78
+ expect(results.warningCount).to.be.a('number');
79
+ expect(results.ignoredCount).to.be.a('number');
80
+ expect(results.errors).to.be.a('array');
81
+ expect(results.warnings).to.be.a('array');
82
+ expect(results.ignored).to.be.a('array');
83
+ expect(results.errorCount).to.be.equal(results.errors.length);
84
+ expect(results.warningCount).to.be.equal(results.warnings.length);
85
+ expect(results.ignoredCount).to.be.equal(results.ignored.length);
86
+ expect(results.errorCount).to.be.equal(16);
87
+ expect(results.warningCount).to.be.equal(15);
88
+ expect(results.ignoredCount).to.be.equal(1);
89
+ });
90
+
91
+ it('return similar results given schematron filepath', async function() {
92
+ results = await validator.validateAsync(xml, schematronPath);
93
+ expect(results).to.be.an('object');
94
+ expect(results.errorCount).to.be.a('number');
95
+ expect(results.warningCount).to.be.a('number');
96
+ expect(results.ignoredCount).to.be.a('number');
97
+ expect(results.errors).to.be.a('array');
98
+ expect(results.warnings).to.be.a('array');
99
+ expect(results.ignored).to.be.a('array');
100
+ expect(results.errorCount).to.be.equal(results.errors.length);
101
+ expect(results.warningCount).to.be.equal(results.warnings.length);
102
+ expect(results.ignoredCount).to.be.equal(results.ignored.length);
103
+ expect(results.errorCount).to.be.equal(16);
104
+ expect(results.warningCount).to.be.equal(15);
105
+ expect(results.ignoredCount).to.be.equal(1);
106
+ });
107
+
108
+ it('return similar results given xml filepath and schematron filepath', async function() {
109
+ results = await validator.validateAsync(xmlPath, schematronPath);
110
+ expect(results).to.be.an('object');
111
+ expect(results.errorCount).to.be.a('number');
112
+ expect(results.warningCount).to.be.a('number');
113
+ expect(results.ignoredCount).to.be.a('number');
114
+ expect(results.errors).to.be.a('array');
115
+ expect(results.warnings).to.be.a('array');
116
+ expect(results.ignored).to.be.a('array');
117
+ expect(results.errorCount).to.be.equal(results.errors.length);
118
+ expect(results.warningCount).to.be.equal(results.warnings.length);
119
+ expect(results.ignoredCount).to.be.equal(results.ignored.length);
120
+ expect(results.errorCount).to.be.equal(16);
121
+ expect(results.warningCount).to.be.equal(15);
122
+ expect(results.ignoredCount).to.be.equal(1);
123
+ });
124
+ });
package/validator.js CHANGED
@@ -3,6 +3,7 @@
3
3
 
4
4
  module.exports = {
5
5
  validate: validate,
6
+ validateAsync: validateAsync,
6
7
  clearCache: clearCache,
7
8
  parseSchematron: require('./parseSchematron')
8
9
  };
@@ -231,3 +232,224 @@ function checkRule(xmlDoc, originalContext, assertionsAndExtensions, options) {
231
232
  }
232
233
  return results;
233
234
  }
235
+
236
+ async function validateAsync(xml, schematron, options = {}) {
237
+ // If not valid xml, it might be a filepath
238
+ // Adding explicit check to make it clear
239
+ if (xml.trim().indexOf('<') === -1) {
240
+ try {
241
+ xml = fs.readFileSync(xml, 'utf-8').toString();
242
+ }
243
+ catch (err) {
244
+ // If no valid xml found, inform user, and return immediately
245
+ console.log('No valid xml could be found');
246
+ return;
247
+ }
248
+ }
249
+
250
+ let schematronMap;
251
+ // Load xml doc
252
+ let xmlDoc = new dom().parseFromString(xml);
253
+ // Allowing users to send a parsed schematron map if testing multiple xml files with the same schematron
254
+ if (options.parsedSchematronMap) {
255
+ schematronMap = options.parsedSchematronMap;
256
+ }
257
+ else {
258
+ // If not valid schematron (xml), it might be a filepath
259
+ // Adding explicit check to make it clear
260
+ if (schematron.trim().indexOf('<') === -1) {
261
+ try {
262
+ schematron = fs.readFileSync(schematron, 'utf-8').toString();
263
+ }
264
+ catch (err) {
265
+ // If no valid schematron found, inform user, and return immediately
266
+ console.log('No valid schematron could be found');
267
+ return;
268
+ }
269
+ }
270
+ let hash = crypto
271
+ .createHash('md5')
272
+ .update(schematron)
273
+ .digest('hex');
274
+ schematronMap = parsedMap[hash];
275
+ // If not in cache
276
+ if (!schematronMap) {
277
+ // Load schematron doc
278
+ let schematronDoc = new dom().parseFromString(schematron);
279
+
280
+ // Parse schematron
281
+ schematronMap = parseSchematron(schematronDoc);
282
+
283
+ // Cache parsed schematron
284
+ parsedMap[hash] = schematronMap;
285
+ }
286
+ }
287
+
288
+ // Extract data from parsed schematron object
289
+ namespaceMap = schematronMap.namespaceMap;
290
+ patternRuleMap = schematronMap.patternRuleMap;
291
+ ruleAssertionMap = schematronMap.ruleAssertionMap;
292
+
293
+ // Create selector object, initialized with namespaces
294
+ // Avoid using 'select' as a variable name as it is overused
295
+ xpathSelect = xpath.useNamespaces(namespaceMap);
296
+
297
+ let errors = [];
298
+ let warnings = [];
299
+ let ignored = [];
300
+ for (let patternId in patternRuleMap) {
301
+ if (!patternRuleMap.hasOwnProperty(patternId)) {
302
+ continue;
303
+ }
304
+ const rules = patternRuleMap[patternId];
305
+ for (let i = 0; i < rules.length; i++) {
306
+ const ruleId = rules[i];
307
+ const ruleObject = ruleAssertionMap[ruleId];
308
+ if (_get(ruleObject, 'abstract')) {
309
+ continue;
310
+ }
311
+ const context = _get(ruleObject, 'context');
312
+ const assertionsAndExtensions = _get(ruleObject, 'assertionsAndExtensions') || [];
313
+ let failedAssertions;
314
+ try {
315
+ failedAssertions = await checkRulePromise(xmlDoc, context, assertionsAndExtensions, options);
316
+ }
317
+ catch (errorInRuleCheck) {
318
+ console.log(errorInRuleCheck);
319
+ continue;
320
+ }
321
+ for (let j = 0; j < failedAssertions.length; j++) {
322
+ const assertionObject = failedAssertions[j];
323
+ const { type, assertionId, test, simplifiedTest, description, errorMessage, results } = assertionObject;
324
+ if (!results.ignored) {
325
+ for (let k = 0; k < results.length; k++) {
326
+ const resultObject = results[k];
327
+ const { result, line, path, xml } = resultObject;
328
+ if (!result) {
329
+ let obj = {
330
+ type: type,
331
+ test: test,
332
+ simplifiedTest: simplifiedTest,
333
+ description: description,
334
+ line: line,
335
+ path: path,
336
+ patternId: patternId,
337
+ ruleId: ruleId,
338
+ assertionId: assertionId,
339
+ context: context,
340
+ xml: xml
341
+ };
342
+ if (type === 'error') {
343
+ errors.push(obj);
344
+ }
345
+ else {
346
+ warnings.push(obj);
347
+ }
348
+ }
349
+ }
350
+ }
351
+ else {
352
+ let obj = {
353
+ errorMessage: errorMessage,
354
+ type: type,
355
+ test: test,
356
+ simplifiedTest: simplifiedTest,
357
+ description: description,
358
+ patternId: patternId,
359
+ ruleId: ruleId,
360
+ assertionId: assertionId,
361
+ context: context
362
+ };
363
+ ignored.push(obj);
364
+ }
365
+ }
366
+ }
367
+ }
368
+
369
+ return {
370
+ errorCount: errors.length,
371
+ warningCount: warnings.length,
372
+ ignoredCount: ignored.length,
373
+ errors: errors,
374
+ warnings: warnings,
375
+ ignored: ignored
376
+ };
377
+ }
378
+
379
+ // Take the checkRule function out of validate function, and pass on the variable needed as parameters and options
380
+ function checkRulePromise(xmlDoc, originalContext, assertionsAndExtensions, options) {
381
+ // Context cache
382
+ const resultCapture = new Promise((resolve, reject) => {
383
+ try {
384
+ const includeWarnings = options.includeWarnings === undefined ? true : options.includeWarnings;
385
+ const resourceDir = options.resourceDir || './';
386
+ const xmlSnippetMaxLength = options.xmlSnippetMaxLength === undefined ? 200 : options.xmlSnippetMaxLength;
387
+ let results = [];
388
+ const context = options.contextOverride || originalContext;
389
+ // Determine the sections within context, load selected section from cache if possible
390
+ let selected = contextMap[context];
391
+ let contextModified = context;
392
+ if (!selected) {
393
+ if (context) {
394
+ if (context.indexOf('/')) {
395
+ contextModified = '//' + context;
396
+ }
397
+ selected = xpathSelect(contextModified, xmlDoc);
398
+ }
399
+ else {
400
+ selected = [xmlDoc];
401
+ }
402
+ contextMap[context] = selected;
403
+ }
404
+
405
+ for (let i = 0; i < assertionsAndExtensions.length; i++) {
406
+ const assertionAndExtensionObject = assertionsAndExtensions[i];
407
+ if (assertionAndExtensionObject.type === 'assertion') {
408
+ let { level, test, id, description } = assertionAndExtensionObject;
409
+
410
+ // Extract values from external document and modify test if a document call is made
411
+ let originalTest = test;
412
+ try {
413
+ test = includeExternalDocument(test, resourceDir);
414
+ }
415
+ catch (err) {
416
+ return { ignored: true, errorMessage: err.message };
417
+ }
418
+
419
+ let simplifiedTest = null;
420
+ if (originalTest !== test) {
421
+ simplifiedTest = test;
422
+ }
423
+ if (level === 'error' || includeWarnings) {
424
+ results.push({
425
+ type: level,
426
+ assertionId: id,
427
+ test: originalTest,
428
+ simplifiedTest: simplifiedTest,
429
+ description: description,
430
+ results: testAssertion(test, selected, xpathSelect, xmlDoc, resourceDir, xmlSnippetMaxLength)
431
+ });
432
+ }
433
+ }
434
+ else {
435
+ const extensionRule = assertionAndExtensionObject.rule;
436
+ if (!extensionRule) {
437
+ continue;
438
+ }
439
+ const subAssertionsAndExtensions = ruleAssertionMap[extensionRule] ? ruleAssertionMap[extensionRule].assertionsAndExtensions : null;
440
+ if (!subAssertionsAndExtensions) {
441
+ continue;
442
+ }
443
+ const newRuleObject = ruleAssertionMap[extensionRule];
444
+ const newContext = newRuleObject.context;
445
+ results = results.concat(checkRulePromise(xmlDoc, newContext, subAssertionsAndExtensions, options));
446
+ }
447
+ }
448
+ resolve (results);
449
+ }
450
+ catch (promiseError) {
451
+ reject (new Error (`Promise Error: ${promiseError}`));
452
+ }
453
+ });
454
+ return resultCapture;
455
+ }