cda-schematron-validator 1.1.12 → 2.0.0-preview.2

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.
Files changed (49) hide show
  1. package/LICENSE.md +9 -9
  2. package/README.md +222 -243
  3. package/bin/cda-validate.js +36 -0
  4. package/docs/api.md +134 -0
  5. package/docs/architecture.md +102 -0
  6. package/docs/coverage.md +124 -0
  7. package/docs/deployment.md +126 -0
  8. package/docs/history.md +245 -0
  9. package/docs/legacy-api.md +70 -0
  10. package/docs/terminology.md +75 -0
  11. package/lib/checkIfFileOrPath.js +27 -28
  12. package/lib/checkRule.js +97 -98
  13. package/lib/createClient.js +35 -0
  14. package/lib/getAssertionObject.js +23 -23
  15. package/lib/getErrorsAndWarnings.js +41 -41
  16. package/lib/getFailedAssertions.js +24 -25
  17. package/lib/getIgnored.js +27 -27
  18. package/lib/getResults.js +22 -22
  19. package/lib/getReturnObject.js +20 -20
  20. package/lib/getSchematronMap.js +34 -31
  21. package/lib/getSelectXmlChunk.js +27 -27
  22. package/lib/includeExternalDocument.js +113 -107
  23. package/lib/initializeProcess.js +34 -40
  24. package/lib/parseSchematron.js +122 -122
  25. package/lib/processFailedAssertions.js +17 -17
  26. package/lib/processRules.js +20 -20
  27. package/lib/processRulesAsync.js +18 -30
  28. package/lib/testAssertion.js +74 -74
  29. package/package.json +67 -59
  30. package/validateAsync.js +103 -117
  31. package/validateSync.js +51 -55
  32. package/validator.d.ts +89 -0
  33. package/validator.js +17 -16
  34. package/.eslintrc.js +0 -30
  35. package/.github/workflows/codeql-analysis.yml +0 -70
  36. package/.husky/pre-commit +0 -5
  37. package/.jshintrc +0 -96
  38. package/.vscode/launch.json +0 -37
  39. package/Gruntfile.js +0 -28
  40. package/SECURITY.md +0 -21
  41. package/test/CDAR2_IG_CCDA_CLINNOTES_R1_DSTU2.1_2015AUG_Vol2_2019JUNwith_errata.sch +0 -71
  42. package/test/VitalSigns.xml +0 -856
  43. package/test/async.test.js +0 -124
  44. package/test/asyncFileList.test.js +0 -61
  45. package/test/test.sch +0 -47
  46. package/test/test.xml +0 -80
  47. package/test/tests.js +0 -140
  48. package/test/vitalSigns.test.js +0 -34
  49. package/test/voc.xml +0 -44
@@ -0,0 +1,245 @@
1
+ # Historical release notes and inherited documentation
2
+
3
+ > This archive preserves the original release history, examples, and attribution. Some examples use the parent package name or older defaults. Use the [current legacy API guide](legacy-api.md) and [project README](../README.md) for version 2. Paths in the archived text were relative to the repository root.
4
+
5
+ ## Release History
6
+
7
+ ### 1.1.12
8
+
9
+ - Update xmldom to the latest version
10
+
11
+ ### 1.1.11
12
+
13
+ - License file added
14
+
15
+ ### 1.1.10
16
+
17
+ - Fix grunt race condition reported by github
18
+
19
+ "file.copy operations in GruntJS are vulnerable to a TOCTOU race condition leading to arbitrary file write in GitHub repository gruntjs/grunt prior to 1.5.3. This vulnerability is capable of arbitrary file writes which can lead to local privilege escalation to the GruntJS user if a lower-privileged user has write access to both source and destination directories as the lower-privileged user can create a symlink to the GruntJS user's .bashrc file or replace /etc/shadow file if the GruntJS user is root."
20
+
21
+ ### 1.1.9
22
+
23
+ - Fix grunt vulnerability
24
+
25
+ ### 1.1.8
26
+
27
+ - jsdoc module added
28
+ - parseSchematron.js moved to lib
29
+
30
+ ### 1.1.7
31
+
32
+ - Introduced a new method called `validateFileObjectAsync` which allows to supply an object with key, value pairs where key represents the identifier of the xml, and the value represents xml file content or path to validate
33
+ - An array of results will be returned from the `validateFileObjectAsync` method
34
+ - Test file `test/asyncFileList.test.js` has the example usage
35
+ - The result object has the property `fileInfo` that would return the `key` the identifier of the xml to identify and debug issues
36
+ - The result object of the array result from the method `validateFileListAsync` now has the property `fileIndex` that will give an indication of which xml file the result belongs to for debugging purposes
37
+
38
+ ### 1.1.6
39
+
40
+ - Methods have been moved to js files and relocated to lib directory
41
+ - Introduced a new method called `validateFileListAsync` which allows to supply an array of xml file content or paths to validate
42
+ - An array of results will be returned from the `validateFileListAsync` method
43
+ - Test file `test/asyncFileList.test.js` has the example usage
44
+ - Started to make use of Promise.all for async methods
45
+ - Documentation of the methods completed by 40%
46
+
47
+ ### 1.1.5
48
+
49
+ - Major methods have been divided into multiple small methods to avoid redundancy across sync and async methods, and reduce maintenance
50
+
51
+ ### 1.1.4 (Stable Release)
52
+
53
+ - Major deviations from the source repository
54
+
55
+ - By default the warning will be turned off in contrast to the parent repository
56
+
57
+ - To get warnings, users have to explicitly specify the option `includeWarnings` with value boolean `true`
58
+
59
+ - We also deviate from the previous behavior where all the checks for warnings were done at the assertion
60
+ level just before testing the xpath. We now would not even parse the phase with @id="warnings" which should
61
+ improve the performance.
62
+
63
+ - Minor cosmetic changes to the code
64
+
65
+ ### 1.1.1 to 1.1.3
66
+
67
+ - Only keeping the necessary data in the test files taken from HL7 C-CDA schematron repository to avoid bloating the module
68
+
69
+ - Added pre-commit hooks with husky
70
+
71
+ - Added code standardization with prettier, ESLint, and lint-staged
72
+
73
+ ### 1.1.0
74
+
75
+ - Fix the issue with the rule check which was working in the original repository, but not in the fork
76
+ - Added HL7 C-CDA schematron file and resource file from <https://github.com/HL7/CDA-ccda-2.1/releases/tag/2019JUN>
77
+ - Added a test case vitalSigns.test.js that tests the resource file and sub assertions
78
+ - Used resources <https://github.com/jddamore/ccda-samples> and <https://github.com/HL7/C-CDA-Examples/tree/master/Vital%20Signs> to create the test file vitalSigns.xml
79
+
80
+ ### 1.0.10
81
+
82
+ - Fix null context issue associated with assertions within assertions
83
+ - Skip abstract rules associated with assertions within assertions
84
+
85
+ ### 1.0.9
86
+
87
+ - Fixed the bug introduced in 1.0.8 trying to adjust to different data types of the return value
88
+ - Changed variable names to improve understanding of the process
89
+
90
+ ### 1.0.8
91
+
92
+ - Bug fix identifying the ignored errors
93
+
94
+ ### 1.0.7
95
+
96
+ - Added async validate function `validateAsync`
97
+ - Added `testsAsync` to test `validateAsync`
98
+ - Plan to use common functions between sync and async methods in the future release
99
+
100
+ ### 1.0.0 to 1.0.6
101
+
102
+ 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.
103
+
104
+ This is just a cosmetic change with updated node modules, a couple of minor bugs observed, and esversion 6 changes.
105
+
106
+ The changes are fully backward compatible. So, leaving the original documentation as is below.
107
+
108
+ ### New option parameter parsedSchematronMap
109
+
110
+ In addition to everything that was possible,
111
+ you can now supply a new option parameter `parsedSchematronMap`. You can create a schematron map as follows.
112
+
113
+ ```javascript
114
+ const fs = require('fs');
115
+ const dom = require('@xmldom/xmldom').DOMParser;
116
+ const { parseSchematron, validate } = require('cda-schematron-validator');
117
+ const schematronString = fs.readFileSync('SchematronFilePath', 'utf-8').toString();
118
+ const schematronDoc = new dom().parseFromString(schematronString);
119
+ const schematronMap = parseSchematron(schematronDoc);
120
+ const options = {
121
+ parsedSchematronMap: schematronMap
122
+ };
123
+ const results = validate('xml string or file path', 'schematron sting, file path or null', options);
124
+ ```
125
+
126
+ If a schematron map is provided, the schematron string or path will not be read.
127
+
128
+ To install this npm module, it will be
129
+
130
+ ```javascript
131
+ npm i cda-schematron-validator
132
+ ```
133
+
134
+ Mocha VS Code configuratin added to directly execute the test file in `test/tests.js` using VS Code.
135
+
136
+ ## Documentation of the parent repo [cda-schematron](https://github.com/ewadkins/cda-schematron)
137
+
138
+ 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.
139
+
140
+ Check out [cda-schematron-server](https://github.com/ewadkins/cda-schematron-server), a server wrapper of **cda-schematron**, for easy schematron validation.
141
+
142
+ ### Validating xml
143
+
144
+ ```javascript
145
+ var validator = require('cda-schematron');
146
+
147
+ var xmlPath = 'someFile.xml';
148
+ var schematronPath = 'someFile.sch';
149
+
150
+ var fs = require('fs');
151
+ var xml = fs.readFileSync(xmlPath).toString();
152
+ var schematron = fs.readFileSync(schematronPath).toString();
153
+
154
+ var results = validator.validate(xml, schematron);
155
+ ```
156
+
157
+ File paths can also be passed to the validator directly. The following lines all return the same results:
158
+
159
+ ```javascript
160
+ var results = validator.validate(xml, schematronPath);
161
+ ```
162
+
163
+ ```javascript
164
+ var results = validator.validate(xmlPath, schematron);
165
+ ```
166
+
167
+ ```javascript
168
+ var results = validator.validate(xmlPath, schematronPath);
169
+ ```
170
+
171
+ ### Results
172
+
173
+ ```results``` is an object containing arrays ```errors```, ```warnings```, and ```ignoreds```.
174
+
175
+ **Errors** and **warnings** are reported as determined by the schematron and test descriptions. They are of the following form:
176
+
177
+ ```javascript
178
+ {
179
+ type: type, // "error" or "warning"
180
+ test: test, // xpath test
181
+ simplifiedTest: simplifiedTest, // xpath test with resource values included, if applicable, null otherwise
182
+ description: description, // schematron description of the test case
183
+ line: line, // line number of the violating context
184
+ path: path, // xpath path of the violating context
185
+ patternId: patternId, // schematron-assigned pattern id
186
+ ruleId: ruleId, // schematron-assigned rule id
187
+ assertionId: assertionId, // schematron-assigned assertion id
188
+ context: context, // xpath context of the rule
189
+ xml: xml // xml snippet of the violating context
190
+ }
191
+ ```
192
+
193
+ **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:
194
+
195
+ ```javascript
196
+ {
197
+ errorMessage: errorMessage, // reason for the exception/ignoring the test
198
+ type: type, // "error" or "warning"
199
+ test: test, // xpath test
200
+ simplifiedTest: simplifiedTest, // xpath test with resource values included, if applicable, null otherwise
201
+ description: description, // schematron description of the test case
202
+ patternId: patternId, // schematron-assigned pattern id
203
+ ruleId: ruleId, // schematron-assigned rule id
204
+ assertionId: assertionId, // schematron-assigned assertion id
205
+ context: context, // xpath context of the rule
206
+ }
207
+ ```
208
+
209
+ ### Options
210
+
211
+ 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:
212
+
213
+ - **```includeWarnings```**: ```true``` or ```false```, this determines whether or not warnings should be tested and returned. Defaults to ```true```.
214
+
215
+ - **```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.
216
+
217
+ - **```xmlSnippetMaxLength```**: an integer, which is the maximum length of the ```xml``` field in validation results. Defaults to ```200```. Set to ```0``` for unlimited length.
218
+
219
+ Here is an example with warnings disabled:
220
+
221
+ ```javascript
222
+ var results = validator.validate(xml, schematron, { includeWarnings: false });
223
+ ```
224
+
225
+ ### Cache
226
+
227
+ 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:
228
+
229
+ ```javascript
230
+ validator.clearCache();
231
+ ```
232
+
233
+ ---
234
+
235
+ ## License (MIT)
236
+
237
+ Copyright &copy; 2017 [Eric Wadkins](http://www.ericwadkins.com/)
238
+
239
+ Copyright &copy; 2022 [Priyaranjan (Raj) Tokachichu](https://github.com/priyaranjan-tokachichu)
240
+
241
+ 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:
242
+
243
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
244
+
245
+ 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,70 @@
1
+ # Legacy JavaScript API and migration
2
+
3
+ [← Project home](../README.md) · [Modern API](api.md) · [Historical documentation](history.md)
4
+
5
+ The original JavaScript APIs remain local and retain their result shape and synchronous/Promise contracts. They do not require the Java service or Docker. The version 2 package targets Node **22.12+**; older runtimes should retain a compatible earlier release.
6
+
7
+ > [!IMPORTANT]
8
+ > The legacy implementation is a **partial Schematron interpreter**, with no XSD validation. Installing the modern package does not turn `validate()` into the full service engine. Use `createClient()` for the modern pipeline.
9
+
10
+ ## Exports preserved
11
+
12
+ | Export | Behavior |
13
+ | --- | --- |
14
+ | `validate(xml, schematron, options)` | Synchronous validation |
15
+ | `validateAsync(xml, schematron, options)` | Promise returning one legacy result |
16
+ | `validateFileListAsync(documents, schematron, options)` | Ordered results with `fileIndex` |
17
+ | `validateFileObjectAsync(documents, schematron, options)` | Results with `fileInfo` |
18
+ | `parseSchematron(document, options)` | Parse a DOM Schematron document into a reusable map |
19
+ | `clearCache()` | Clear synchronous validator caches |
20
+ | `clearCacheAsync()` | Clear asynchronous validator caches |
21
+
22
+ The additional `createClient()` export connects to the HTTP service. Existing exports were not replaced with network calls.
23
+
24
+ ## Synchronous example
25
+
26
+ ```javascript
27
+ const { readFileSync } = require('node:fs');
28
+ const { validate } = require('cda-schematron-validator');
29
+
30
+ const result = validate(
31
+ readFileSync('document.xml', 'utf8'),
32
+ readFileSync('rules.sch', 'utf8'),
33
+ { includeWarnings: true }
34
+ );
35
+ console.log(result.errorCount, result.errors);
36
+ ```
37
+
38
+ Legacy calls accept XML/Schematron strings or file paths. `schematron` may be `null` when `options.parsedSchematronMap` is supplied. Unlike the modern service, legacy findings may include XML snippets.
39
+
40
+ ## Results and options
41
+
42
+ Results retain `errorCount`, `warningCount`, `ignoredCount`, `errors`, `warnings`, and `ignored`. Ignored findings should be reviewed when assessing interpreter coverage; a zero error count does not establish full CDA conformance.
43
+
44
+ | Option | Purpose |
45
+ | --- | --- |
46
+ | `includeWarnings` | Default **false** for legacy calls; modern API default is true |
47
+ | `resourceDir` | Resolve legacy external vocabulary/document resources |
48
+ | `xmlSnippetMaxLength` | Bound snippets in legacy findings |
49
+ | `parsedSchematronMap` | Reuse a parsed Schematron map |
50
+
51
+ [Type declarations](../validator.d.ts) describe result/finding fields and batch signatures. The [archived documentation](history.md) preserves inherited examples, including the parent package name; use `cda-schematron-validator` for this package.
52
+
53
+ ## Correctness fixes in version 2
54
+
55
+ Document context caches are isolated, caller options are not mutated, asynchronous empty patterns settle, batches retain input ordering, and rules without IDs receive generated identifiers. Resource caches distinguish absolute paths and file versions, with a bounded parsed-map cache. Missing files and empty input fail explicitly.
56
+
57
+ These fixes correct previously incorrect results. They do not preserve false passes as compatibility behavior.
58
+
59
+ ## Move to the modern pipeline
60
+
61
+ 1. Run the container service.
62
+ 2. Replace local validation calls with `createClient().validate(xml, { profile })` where full XSD/official-package execution is needed.
63
+ 3. Consume modern `findings` and both completeness flags; do not assume legacy result fields on the new response.
64
+ 4. Keep existing legacy calls for integrations that still require their established contract.
65
+
66
+ The modern service accepts installed profile IDs and XML text; it does not accept your arbitrary Schematron, resource directory, file path, or parsed legacy map.
67
+
68
+ ## Release boundary
69
+
70
+ Preview `2.0.0-preview.1` preserves the seven legacy exports and adds the HTTP client and CLI. It requires Node 22.12+. Version `1.1.12` remains available for older integrations; the stable default remains `1.1.12`, and the preview is selected explicitly with `@next`. The Java service is distributed separately as a container. Merging alone does not publish either artifact.
@@ -0,0 +1,75 @@
1
+ # Local terminology snapshots
2
+
3
+ [← Coverage inventory](coverage.md) · [Deployment](deployment.md)
4
+
5
+ This is development work following `2.0.0-preview.1`; the published preview.1 image does not contain this adapter. The public distribution does not include the operator's licensed terminology exports.
6
+
7
+ ## What this adapter checks
8
+
9
+ When a reviewed Procedure expansion is installed, the service restores the omitted `1198-8487` and `1198-8511` checks at the operative-note and procedure-note service-event code locations. It preserves the invariant's ICD-9-CM procedure, ICD-10-PCS, and CPT alternatives, and the additional HCPCS alternative for procedure notes. SNOMED CT membership uses an exact code-system/code pair, with no substring matching.
10
+
11
+ The supplied expansion is a frozen local snapshot. Its code-system versions, definition revision, source status, retrieval time, original export checksum, normalized checksum, and concept count appear in `terminologySnapshots`. Only the Procedure index currently has `activeForValidation: true`; other imported snapshots are verified and disclosed without being represented as implemented binding coverage. Their indexes are not retained in memory.
12
+
13
+ The person-name supplement separately reapplies the pinned patient-name constraints at person-name locations, preserving the allowed plain-text alternative. `supplementalChecks` identifies the added checks. The original upstream report and counts are retained. **C-CDA 5.0 completeness remains false:** remaining date, location, generation, and terminology gaps have not been cleared.
14
+
15
+ ## Prepare a local pack
16
+
17
+ 1. Export the required expansions as XML from an authorized [VSAC session](https://vsac.nlm.nih.gov/). Include retired sets only when the pinned guide references them, and retain their status for review.
18
+ 2. Record each displayed full code count in a local JSON checklist. For example:
19
+
20
+ ```json
21
+ [
22
+ { "oid": "2.16.840.1.113883.3.88.12.80.28", "expectedCount": 62110 }
23
+ ]
24
+ ```
25
+
26
+ This is the count observed for the downloaded snapshot, not a permanent count to assume for future exports. Record and review the actual count for your selected version.
27
+
28
+ 3. Import the checked exports after preparing the standard assets:
29
+
30
+ ```sh
31
+ npm run assets
32
+ python3 scripts/import-svs.py \
33
+ --input-glob '/private/path/RetrieveMultipleValueSets*.xml' \
34
+ --expected /private/path/expected-counts.json \
35
+ --output service/assets/terminology
36
+ ```
37
+
38
+ The importer rejects empty, duplicate, conflicting, entity-bearing, incomplete, and count-mismatched exports. All reviewed OIDs must be present. It validates all inputs before changing the manifest and uses content-addressed data filenames. Original XML files are not copied into the public package.
39
+
40
+ `service/assets/` and `.cache/` are ignored by Git and excluded from the Docker build context. The normal multi-stage image prepares only the pinned public validation assets; it does not copy this local pack. Keep exports outside Git and apply the terms of each terminology source to any redistribution.
41
+
42
+ ## Run the development image with the local pack
43
+
44
+ Build the reviewed development checkout, then use a read-only asset mount. The following uses a separate local port so an installed release can remain running:
45
+
46
+ ```sh
47
+ docker build -t cda-validator:coverage-review .
48
+ docker run -d --name cda-validator-coverage \
49
+ --memory=1536m --cpus=2 --pids-limit=128 \
50
+ --read-only --tmpfs /tmp:size=64m,noexec,nosuid \
51
+ --cap-drop=ALL --security-opt=no-new-privileges \
52
+ -e JAVA_TOOL_OPTIONS=-Xmx1g \
53
+ -p 127.0.0.1:17644:17643 \
54
+ --mount "type=bind,source=$PWD/service/assets,target=/app/assets,readonly" \
55
+ cda-validator:coverage-review
56
+ ```
57
+
58
+ Open `http://localhost:17644`. The service verifies the normalized file hashes and exact counts before accepting the pack. The parser is strict, paths must remain inside the trusted asset directory, total normalized files are bounded to 64 MiB, and the pack is bounded to 1,000,000 concept entries. Loading additional data alone does not turn completeness into a pass. There are no terminology network calls during validation and submitted clinical documents never enter a download request.
59
+
60
+ More heap/container memory can support larger deployments; use the existing [capacity guidance](deployment.md#increase-concurrent-large-upload-capacity). The constrained-heap regression can also exercise a local pack:
61
+
62
+ ```sh
63
+ python3 scripts/check-upload-memory.py \
64
+ --image cda-validator:coverage-review \
65
+ --assets-dir service/assets \
66
+ --output .cache/upload-memory-with-terminology.json
67
+ ```
68
+
69
+ ## Data recovered during this work
70
+
71
+ The authorized local VSAC exports contain 20 expansions and 383,629 total membership entries. Nineteen match VSAC canonicals in the upstream omission report; the additional occupational candidate is kept distinct from the PHINVADS canonical. These data are local and are not committed or published. Two exported sets are marked retired, and remain inactive in the adapter.
72
+
73
+ The published C-CDA 5.0 FHIR package declares dependencies on `us.cdc.phinvads#0.12.0`, `hl7.fhir.us.core#9.0.0`, and `hl7.terminology.r5#7.1.0`. The CDC package includes the explicit occupational lists of 19,254 and 59,583 concepts that the generator excluded. Those definitions were recovered separately; their PHINVADS identities are not silently replaced with similarly numbered VSAC data. A downloaded UMLS archive is a resource for further source-specific work, not an executable complete value-set validator by itself.
74
+
75
+ Further binding integration, grammar-based language/UCUM checks, source-system mappings, and independent validation comparisons remain necessary. This adapter currently enables only the two procedure invariants described above.
@@ -1,28 +1,27 @@
1
- const fs = require('fs');
2
- /**
3
- * @method checkIfFileOrPath Checks if a given xml string is xml content or file path to the xml, and extracts the content and
4
- * assigns it back to the variable. If no data could be found or there is an issue to access the file, an error will be returned.
5
- * @param {string} givenString xml string or a path to the xml file (the xml can be an xml file or schematron file which is basically an xml)
6
- * @returns If it is a valid xml, returns it. If it is a file path, extracts the content and returns it. Otherwise throws appropriate error.
7
- */
8
-
9
- function checkIfFileOrPath(givenString) {
10
- // If not valid xml, it might be a filepath
11
- // Adding explicit check to make it clear
12
- if (!givenString) {
13
- return new Error('No data found in the xml or schematron');
14
- }
15
- if (givenString.trim().indexOf('<') === -1) {
16
- try {
17
- givenString = fs.readFileSync(givenString, 'utf-8').toString();
18
- }
19
- catch (err) {
20
- // If no valid xml found, inform user, and return immediately
21
- console.log('No valid xml or schematron could be found');
22
- return err;
23
- }
24
- }
25
- return givenString;
26
- }
27
-
28
- module.exports = checkIfFileOrPath;
1
+ const fs = require('fs');
2
+ /**
3
+ * @method checkIfFileOrPath Checks if a given xml string is xml content or file path to the xml, and extracts the content and
4
+ * assigns it back to the variable. If no data could be found or there is an issue to access the file, an error will be returned.
5
+ * @param {string} givenString xml string or a path to the xml file (the xml can be an xml file or schematron file which is basically an xml)
6
+ * @returns If it is a valid xml, returns it. If it is a file path, extracts the content and returns it. Otherwise throws appropriate error.
7
+ */
8
+
9
+ function checkIfFileOrPath(givenString) {
10
+ // If not valid xml, it might be a filepath
11
+ // Adding explicit check to make it clear
12
+ if (typeof givenString !== 'string' || !givenString.trim()) {
13
+ throw new TypeError('Expected XML content or a file path');
14
+ }
15
+ if (givenString.trim().indexOf('<') === -1) {
16
+ try {
17
+ givenString = fs.readFileSync(givenString, 'utf-8').toString();
18
+ }
19
+ catch (err) {
20
+ // If no valid xml found, inform user, and return immediately
21
+ throw err;
22
+ }
23
+ }
24
+ return givenString;
25
+ }
26
+
27
+ module.exports = checkIfFileOrPath;