cda-schematron-validator 1.1.4 → 1.1.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.
package/validator.js CHANGED
@@ -1,461 +1,16 @@
1
1
  // jshint node:true
2
2
  // jshint shadow:true
3
3
 
4
+ /**
5
+ * Export all the main methods
6
+ */
7
+
4
8
  module.exports = {
5
- validate: validate,
6
- validateAsync: validateAsync,
7
- clearCache: clearCache,
9
+ validate: require('./validateSync').validateSync,
10
+ validateAsync: require('./validateAsync').validateAsync,
11
+ validateFileListAsync: require('./validateAsync').validateFileListAsync,
12
+ validateFileObjectAsync: require('./validateAsync').validateFileObjectAsync,
13
+ clearCache: require('./validateSync').clearCache,
14
+ clearCacheAsync: require('./validateAsync').clearCache,
8
15
  parseSchematron: require('./parseSchematron')
9
16
  };
10
-
11
- const fs = require('fs');
12
- const xpath = require('xpath');
13
- const Dom = require('@xmldom/xmldom').DOMParser;
14
- // crypto is now built-in node
15
- const crypto = require('crypto');
16
- const _get = require('lodash.get');
17
- const parseSchematron = require('./parseSchematron');
18
- const testAssertion = require('./testAssertion');
19
- const includeExternalDocument = require('./includeExternalDocument');
20
-
21
- // Parsed object cache
22
- let parsedMap = Object.create({});
23
- let contextMap = Object.create({});
24
-
25
- function clearCache() {
26
- parsedMap = Object.create({});
27
- contextMap = Object.create({});
28
- }
29
- let namespaceMap;
30
- let patternRuleMap;
31
- let ruleAssertionMap;
32
- let xpathSelect;
33
- function validate(xml, schematron, options = {}) {
34
- // If not valid xml, it might be a filepath
35
- // Adding explicit check to make it clear
36
- if (xml.trim().indexOf('<') === -1) {
37
- try {
38
- xml = fs.readFileSync(xml, 'utf-8').toString();
39
- }
40
- catch (err) {
41
- // If no valid xml found, inform user, and return immediately
42
- console.log('No valid xml could be found');
43
- return;
44
- }
45
- }
46
-
47
- let schematronMap;
48
- // Load xml doc
49
- const xmlDoc = new Dom().parseFromString(xml);
50
- // Allowing users to send a parsed schematron map if testing multiple xml files with the same schematron
51
- if (options.parsedSchematronMap) {
52
- schematronMap = options.parsedSchematronMap;
53
- }
54
- else {
55
- // If not valid schematron (xml), it might be a filepath
56
- // Adding explicit check to make it clear
57
- if (schematron.trim().indexOf('<') === -1) {
58
- try {
59
- schematron = fs.readFileSync(schematron, 'utf-8').toString();
60
- }
61
- catch (err) {
62
- // If no valid schematron found, inform user, and return immediately
63
- console.log('No valid schematron could be found');
64
- return;
65
- }
66
- }
67
- const hash = crypto
68
- .createHash('md5')
69
- .update(schematron)
70
- .digest('hex');
71
- schematronMap = parsedMap[hash];
72
- // If not in cache
73
- if (!schematronMap) {
74
- // Load schematron doc
75
- const schematronDoc = new Dom().parseFromString(schematron);
76
-
77
- // Parse schematron
78
- schematronMap = parseSchematron(schematronDoc, options);
79
-
80
- // Cache parsed schematron
81
- parsedMap[hash] = schematronMap;
82
- }
83
- }
84
- // Extract data from parsed schematron object
85
- namespaceMap = schematronMap.namespaceMap;
86
- patternRuleMap = schematronMap.patternRuleMap;
87
- ruleAssertionMap = schematronMap.ruleAssertionMap;
88
-
89
- // Create selector object, initialized with namespaces
90
- // Avoid using 'select' as a variable name as it is overused
91
- xpathSelect = xpath.useNamespaces(namespaceMap);
92
-
93
- const errors = [];
94
- const warnings = [];
95
- const ignored = [];
96
- for (const patternId in patternRuleMap) {
97
- if (!patternRuleMap.hasOwnProperty(patternId)) {
98
- continue;
99
- }
100
- const rules = patternRuleMap[patternId];
101
- for (let i = 0; i < rules.length; i++) {
102
- const ruleId = rules[i];
103
- const ruleObject = ruleAssertionMap[ruleId];
104
- if (_get(ruleObject, 'abstract')) {
105
- continue;
106
- }
107
- const context = _get(ruleObject, 'context');
108
- const assertionsAndExtensions = _get(ruleObject, 'assertionsAndExtensions') || [];
109
- const failedAssertions = checkRule(xmlDoc, context, assertionsAndExtensions, options);
110
- for (let j = 0; j < failedAssertions.length; j++) {
111
- const assertionObject = failedAssertions[j];
112
- const { type, assertionId, test, simplifiedTest, description, errorMessage, results } = assertionObject;
113
- if (Array.isArray(results)) {
114
- for (let k = 0; k < results.length; k++) {
115
- const resultObject = results[k];
116
- const { result, line, path, xml } = resultObject;
117
- if (!result) {
118
- const obj = {
119
- type: type,
120
- test: test,
121
- simplifiedTest: simplifiedTest,
122
- description: description,
123
- line: line,
124
- path: path,
125
- patternId: patternId,
126
- ruleId: ruleId,
127
- assertionId: assertionId,
128
- context: context,
129
- xml: xml
130
- };
131
- if (type === 'error') {
132
- errors.push(obj);
133
- }
134
- else {
135
- warnings.push(obj);
136
- }
137
- }
138
- }
139
- }
140
- else if (results.ignored) {
141
- const obj = {
142
- errorMessage: errorMessage,
143
- type: type,
144
- test: test,
145
- simplifiedTest: simplifiedTest,
146
- description: description,
147
- patternId: patternId,
148
- ruleId: ruleId,
149
- assertionId: assertionId,
150
- context: context
151
- };
152
- ignored.push(obj);
153
- }
154
- }
155
- }
156
- }
157
-
158
- return {
159
- errorCount: errors.length,
160
- warningCount: warnings.length,
161
- ignoredCount: ignored.length,
162
- errors: errors,
163
- warnings: warnings,
164
- ignored: ignored
165
- };
166
- }
167
-
168
- // Take the checkRule function out of validate function, and pass on the variable needed as parameters and options
169
- function checkRule(xmlDoc, originalContext, assertionsAndExtensions, options) {
170
- // Context cache
171
- const resourceDir = options.resourceDir || './';
172
- const xmlSnippetMaxLength = options.xmlSnippetMaxLength === undefined ? 200 : options.xmlSnippetMaxLength;
173
- const failedAssertions = [];
174
- const context = options.contextOverride || originalContext;
175
- // Determine the sections within context, load selected section from cache if possible
176
- let selected = contextMap[context];
177
- let contextModified = context;
178
- if (!selected) {
179
- if (context) {
180
- if (context.indexOf('/')) {
181
- contextModified = '//' + context;
182
- }
183
- selected = xpathSelect(contextModified, xmlDoc);
184
- }
185
- else {
186
- selected = [xmlDoc];
187
- }
188
- contextMap[context] = selected;
189
- }
190
-
191
- for (let i = 0; i < assertionsAndExtensions.length; i++) {
192
- const assertionAndExtensionObject = assertionsAndExtensions[i];
193
- if (assertionAndExtensionObject.type === 'assertion') {
194
- let { level, test, id, description } = assertionAndExtensionObject;
195
- // Extract values from external document and modify test if a document call is made
196
- const originalTest = test;
197
- let simplifiedTest = null;
198
- try {
199
- test = includeExternalDocument(test, resourceDir);
200
- }
201
- catch (err) {
202
- failedAssertions.push({
203
- type: level,
204
- assertionId: id,
205
- test: originalTest,
206
- simplifiedTest: simplifiedTest,
207
- description: description,
208
- results: { ignored: true, errorMessage: err.message }
209
- });
210
- continue;
211
- }
212
- if (originalTest !== test) {
213
- simplifiedTest = test;
214
- }
215
- if (level === 'error' || _get(options, 'includeWarnings')) {
216
- failedAssertions.push({
217
- type: level,
218
- assertionId: id,
219
- test: originalTest,
220
- simplifiedTest: simplifiedTest,
221
- description: description,
222
- results: testAssertion(test, selected, xpathSelect, xmlDoc, resourceDir, xmlSnippetMaxLength)
223
- });
224
- }
225
- }
226
- else {
227
- const extensionRule = assertionAndExtensionObject.rule;
228
- if (!extensionRule) {
229
- continue;
230
- }
231
- const newRuleObject = ruleAssertionMap[extensionRule];
232
- const subAssertionsAndExtensions = newRuleObject ? newRuleObject.assertionsAndExtensions : null;
233
- if (!subAssertionsAndExtensions) {
234
- continue;
235
- }
236
- const failedSubAssertions = checkRule(xmlDoc, context, subAssertionsAndExtensions, options);
237
- failedAssertions.push(...failedSubAssertions);
238
- }
239
- }
240
- return failedAssertions;
241
- }
242
-
243
- async function validateAsync(xml, schematron, options = {}) {
244
- // If not valid xml, it might be a filepath
245
- // Adding explicit check to make it clear
246
- if (xml.trim().indexOf('<') === -1) {
247
- try {
248
- xml = fs.readFileSync(xml, 'utf-8').toString();
249
- }
250
- catch (err) {
251
- // If no valid xml found, inform user, and return immediately
252
- console.log('No valid xml could be found');
253
- return;
254
- }
255
- }
256
-
257
- let schematronMap;
258
- // Load xml doc
259
- const xmlDoc = new Dom().parseFromString(xml);
260
- // Allowing users to send a parsed schematron map if testing multiple xml files with the same schematron
261
- if (options.parsedSchematronMap) {
262
- schematronMap = options.parsedSchematronMap;
263
- }
264
- else {
265
- // If not valid schematron (xml), it might be a filepath
266
- // Adding explicit check to make it clear
267
- if (schematron.trim().indexOf('<') === -1) {
268
- try {
269
- schematron = fs.readFileSync(schematron, 'utf-8').toString();
270
- }
271
- catch (err) {
272
- // If no valid schematron found, inform user, and return immediately
273
- console.log('No valid schematron could be found');
274
- return;
275
- }
276
- }
277
- const hash = crypto
278
- .createHash('md5')
279
- .update(schematron)
280
- .digest('hex');
281
- schematronMap = parsedMap[hash];
282
- // If not in cache
283
- if (!schematronMap) {
284
- // Load schematron doc
285
- const schematronDoc = new Dom().parseFromString(schematron);
286
-
287
- // Parse schematron
288
- schematronMap = parseSchematron(schematronDoc, options);
289
-
290
- // Cache parsed schematron
291
- parsedMap[hash] = schematronMap;
292
- }
293
- }
294
-
295
- // Extract data from parsed schematron object
296
- namespaceMap = schematronMap.namespaceMap;
297
- patternRuleMap = schematronMap.patternRuleMap;
298
- ruleAssertionMap = schematronMap.ruleAssertionMap;
299
-
300
- // Create selector object, initialized with namespaces
301
- // Avoid using 'select' as a variable name as it is overused
302
- xpathSelect = xpath.useNamespaces(namespaceMap);
303
-
304
- const errors = [];
305
- const warnings = [];
306
- const ignored = [];
307
- for (const patternId in patternRuleMap) {
308
- if (!patternRuleMap.hasOwnProperty(patternId)) {
309
- continue;
310
- }
311
- const rules = patternRuleMap[patternId];
312
- for (let i = 0; i < rules.length; i++) {
313
- const ruleId = rules[i];
314
- const ruleObject = ruleAssertionMap[ruleId];
315
- if (_get(ruleObject, 'abstract')) {
316
- continue;
317
- }
318
- const context = _get(ruleObject, 'context');
319
- const assertionsAndExtensions = _get(ruleObject, 'assertionsAndExtensions') || [];
320
- const failedAssertions = await checkRulePromise(xmlDoc, context, assertionsAndExtensions, options);
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 (Array.isArray(results)) {
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
- const 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 if (results.ignored) {
352
- const 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
- // Context cache
385
- const resourceDir = options.resourceDir || './';
386
- const xmlSnippetMaxLength = options.xmlSnippetMaxLength === undefined ? 200 : options.xmlSnippetMaxLength;
387
- const failedAssertions = [];
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
- // Extract values from external document and modify test if a document call is made
410
- const originalTest = test;
411
- let simplifiedTest = null;
412
- try {
413
- test = includeExternalDocument(test, resourceDir);
414
- }
415
- catch (err) {
416
- failedAssertions.push({
417
- type: level,
418
- assertionId: id,
419
- test: originalTest,
420
- simplifiedTest: simplifiedTest,
421
- description: description,
422
- results: { ignored: true, errorMessage: err.message }
423
- });
424
- continue;
425
- }
426
- if (originalTest !== test) {
427
- simplifiedTest = test;
428
- }
429
- if (level === 'error' || _get(options, 'includeWarnings')) {
430
- failedAssertions.push({
431
- type: level,
432
- assertionId: id,
433
- test: originalTest,
434
- simplifiedTest: simplifiedTest,
435
- description: description,
436
- results: testAssertion(test, selected, xpathSelect, xmlDoc, resourceDir, xmlSnippetMaxLength)
437
- });
438
- }
439
- }
440
- else {
441
- const extensionRule = assertionAndExtensionObject.rule;
442
- if (!extensionRule) {
443
- continue;
444
- }
445
- const newRuleObject = ruleAssertionMap[extensionRule];
446
- const subAssertionsAndExtensions = newRuleObject ? newRuleObject.assertionsAndExtensions : null;
447
- if (!subAssertionsAndExtensions) {
448
- continue;
449
- }
450
- const failedSubAssertions = checkRule(xmlDoc, context, subAssertionsAndExtensions, options);
451
- failedAssertions.push(...failedSubAssertions);
452
- }
453
- }
454
- resolve (failedAssertions);
455
- }
456
- catch (promiseError) {
457
- reject (new Error (`Promise Error: ${promiseError}`));
458
- }
459
- });
460
- return resultCapture;
461
- }