@xml-auditfile/auditfile 0.0.0-stage → 0.0.2-alpha.1

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 (83) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +183 -2
  3. package/package.json +62 -4
  4. package/src/auditfile.js +186 -0
  5. package/src/definitions/dialect.js +40 -0
  6. package/src/definitions/element-definition.js +27 -0
  7. package/src/definitions/localized-text.js +41 -0
  8. package/src/definitions/manifest.js +160 -0
  9. package/src/definitions/names.js +42 -0
  10. package/src/definitions/resources.js +29 -0
  11. package/src/definitions/view-definition.js +160 -0
  12. package/src/diagnostics/collector.js +139 -0
  13. package/src/diagnostics/diagnostic.js +53 -0
  14. package/src/diagnostics/report.js +56 -0
  15. package/src/generated/spec.js +74 -0
  16. package/src/index.js +20 -0
  17. package/src/internal/composite-key.js +2 -0
  18. package/src/internal/decimal.js +193 -0
  19. package/src/internal/encoding.js +118 -0
  20. package/src/internal/json.js +106 -0
  21. package/src/internal/sha256.js +147 -0
  22. package/src/internal/streams.js +232 -0
  23. package/src/internal/xml-reader.js +247 -0
  24. package/src/memory/memory-sink.js +68 -0
  25. package/src/reading/mapping-plan.js +91 -0
  26. package/src/reading/read-options.js +136 -0
  27. package/src/reading/read-session.js +446 -0
  28. package/src/reading/row-loader.js +362 -0
  29. package/src/reading/row.js +123 -0
  30. package/src/reading/source.js +146 -0
  31. package/src/reading/value-converter.js +136 -0
  32. package/src/schema/schema.js +256 -0
  33. package/src/sinks/sink.js +53 -0
  34. package/src/validation/reference-checker.js +146 -0
  35. package/src/validation/xaf-rules.js +167 -0
  36. package/src/versioning/version-resolver.js +119 -0
  37. package/src/versioning/version.js +217 -0
  38. package/src/views/view-result.js +20 -0
  39. package/src/views/view-runner.js +449 -0
  40. package/src/xsd/datatypes.js +141 -0
  41. package/src/xsd/regex.js +121 -0
  42. package/src/xsd/schema-set.js +555 -0
  43. package/src/xsd/validator.js +484 -0
  44. package/types/auditfile.d.ts +57 -0
  45. package/types/definitions/dialect.d.ts +27 -0
  46. package/types/definitions/element-definition.d.ts +16 -0
  47. package/types/definitions/localized-text.d.ts +25 -0
  48. package/types/definitions/manifest.d.ts +118 -0
  49. package/types/definitions/names.d.ts +25 -0
  50. package/types/definitions/resources.d.ts +9 -0
  51. package/types/definitions/view-definition.d.ts +85 -0
  52. package/types/diagnostics/collector.d.ts +38 -0
  53. package/types/diagnostics/diagnostic.d.ts +37 -0
  54. package/types/diagnostics/report.d.ts +32 -0
  55. package/types/generated/spec.d.ts +6 -0
  56. package/types/index.d.ts +18 -0
  57. package/types/internal/composite-key.d.ts +2 -0
  58. package/types/internal/decimal.d.ts +55 -0
  59. package/types/internal/encoding.d.ts +43 -0
  60. package/types/internal/json.d.ts +17 -0
  61. package/types/internal/sha256.d.ts +17 -0
  62. package/types/internal/streams.d.ts +35 -0
  63. package/types/internal/xml-reader.d.ts +50 -0
  64. package/types/memory/memory-sink.d.ts +29 -0
  65. package/types/reading/mapping-plan.d.ts +45 -0
  66. package/types/reading/read-options.d.ts +69 -0
  67. package/types/reading/read-session.d.ts +28 -0
  68. package/types/reading/row-loader.d.ts +18 -0
  69. package/types/reading/row.d.ts +53 -0
  70. package/types/reading/source.d.ts +73 -0
  71. package/types/reading/value-converter.d.ts +15 -0
  72. package/types/schema/schema.d.ts +116 -0
  73. package/types/sinks/sink.d.ts +59 -0
  74. package/types/validation/reference-checker.d.ts +11 -0
  75. package/types/validation/xaf-rules.d.ts +13 -0
  76. package/types/versioning/version-resolver.d.ts +25 -0
  77. package/types/versioning/version.d.ts +71 -0
  78. package/types/views/view-result.d.ts +13 -0
  79. package/types/views/view-runner.d.ts +1 -0
  80. package/types/xsd/datatypes.d.ts +40 -0
  81. package/types/xsd/regex.d.ts +6 -0
  82. package/types/xsd/schema-set.d.ts +20 -0
  83. package/types/xsd/validator.d.ts +48 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,184 @@
1
- # Temporary Holding Version
1
+ # auditfile-js
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Streaming reader for Dutch tax audit files (XAF and related), following
4
+ [auditfile-spec](https://github.com/XML-auditfile/auditfile-spec). The JavaScript counterpart of
5
+ [auditfile-dotnet](https://github.com/XML-auditfile/auditfile-dotnet), with the same API in JavaScript style.
6
+
7
+ > Status: draft (0.x).
8
+ > Not affiliated with the Belastingdienst, SRA or any software vendor.
9
+
10
+ ```
11
+ npm install @xml-auditfile/auditfile
12
+ ```
13
+
14
+ The package ships TypeScript declarations, generated from the JSDoc. Every version is published from GitHub Actions with
15
+ [provenance](https://docs.npmjs.com/generating-provenance-statements): `npm audit signatures` verifies that it was built
16
+ from this repository.
17
+
18
+ ```js
19
+ import { createReadStream } from 'node:fs';
20
+ import { Auditfile, AuditfileSource, MemorySink } from '@xml-auditfile/auditfile';
21
+
22
+ const sink = new MemorySink();
23
+ const source = AuditfileSource.fromFactory(() => createReadStream('administratie.xaf'), 'administratie.xaf');
24
+ const report = await Auditfile.read(source, sink);
25
+
26
+ for (const diagnostic of report.diagnostics) {
27
+ console.log(String(diagnostic));
28
+ }
29
+
30
+ for (const line of sink.rows('tr_line')) {
31
+ console.log(`${line.getString('acc_id')} ${line.getDecimal('amnt')} ${line.getString('amnt_tp')}`);
32
+ }
33
+ ```
34
+
35
+ Rows have typed accessors (`getString`, `getDecimal`, `getInteger`, `getDate`, `getDateTime`, `getTime`, `getBoolean`) that check
36
+ the column type and name the problem; `has()` tells whether a column exists in this version. `getDecimal` also reads an integer
37
+ column, since a column can be integer in one version and decimal in another. In a loop over many rows, look the column up once
38
+ (`table.findColumn('amnt')`) and pass it instead of the name.
39
+
40
+ Values are read in XSD notation only: a date-time such as `03/01/2017 10:00:00` is refused (XAF-S004) rather than guessed.
41
+
42
+ ## What it does
43
+
44
+ - **Determines the version**: forced in code, official namespace or alias from the registry, optionally
45
+ derived from the namespace (`useResolver`). Anything else stops with a clear diagnostic.
46
+ - **Reads in two phases**: scan (validate against the built-in XSD, count rows per table) and load
47
+ (stream rows in batches to a sink). Verified mode loads only a valid file.
48
+ - **Turns every repeating element into a table** following the manifest generated by auditfile-spec.
49
+ Rows know their id, parent, position and source part; values are typed.
50
+ - **Checks** required and expected tables, keys, references and the XAF business rules
51
+ (balanced transactions, header counts and totals).
52
+ - **Reads split audit files** (`audit.xaf`, `audit-2.xaf`, ...) as one file; you pass the parts in order.
53
+ - **Reports** everything as diagnostics with stable codes, in Dutch or English.
54
+
55
+ ## Entry points
56
+
57
+ | Call | Use |
58
+ | ---- | --- |
59
+ | `await Auditfile.read(source, sink, options)` | Read into a sink: `MemorySink` or your own sink |
60
+ | `await Auditfile.validate(source, options)` | Validate without storing anything; `mode: 'unverified'` skips the XSD |
61
+ | `await Auditfile.scan(source, options)` | Version, XSD validation and row counts only |
62
+ | `(await Auditfile.open(source, options)).readRows()` | Stream rows yourself (`for await`); the rows can be iterated once |
63
+ | `AuditfileVersion.Financial.V3_2` | Manifest, XSD, definitions, dialects and views of a version |
64
+ | `schema.toJson()` / `AuditfileSchema.fromJson()` | Store and restore the schema of an import |
65
+
66
+ Sources: the reader never opens files; you supply the streams. A stream is a Node `Readable`, a web
67
+ `ReadableStream`, a `Blob`, a `Uint8Array`/`ArrayBuffer`, or any (async) iterable of `Uint8Array` chunks.
68
+
69
+ | Call | Use |
70
+ | ---- | --- |
71
+ | `AuditfileSource.fromFactory(open, name)` | Fresh stream per call: can be read twice (scan, then load) |
72
+ | `AuditfileSource.fromFactories([name, open], ...)` | Same, for the parts of a split audit file |
73
+ | `AuditfileSource.fromStream(stream, name)` | Read once; validation then happens during loading. The stream is not destroyed |
74
+ | `AuditfileSource.fromStreams([name, stream], ...)` | Same, for the parts of a split audit file |
75
+
76
+ Options are a plain object: `version` (an `AuditfileVersion` or `"xaf/3.2"`), `mode` (`'verified'` or
77
+ `'unverified'`), `useResolver`, `xsd`, `applyDialects`, `batchSize`, `language` (`'nl'` or `'en'`),
78
+ `maxDiagnostics`, `maxDepth`, `maxCharactersInDocument`, `maxValueLength`, `onProgress` and `signal` (an `AbortSignal`,
79
+ checked in the scan phase as well as the load phase). Unknown names and values out of range are refused.
80
+ When a sink fails and its `abort` fails too, the read rejects with an `AggregateError` holding both errors.
81
+
82
+ A sink is any object with `begin(context)`, `write(table, rows)`, `complete(report)` and `abort(report)`;
83
+ each may return a promise. Set `capabilities = SinkCapabilities.NeedsRowCounts` to get row counts before the first row.
84
+
85
+ ## Values
86
+
87
+ | Column type | JavaScript value |
88
+ | ----------- | ---------------- |
89
+ | `string` | `string` |
90
+ | `decimal` | `Decimal`: exact, with the scale as written (`'100.00'`); never a floating-point number |
91
+ | `integer` | `number`; values outside the safe integer range are reported (XAF-S004), never rounded |
92
+ | `date` | `Date` at midnight UTC; a time zone in the file is ignored |
93
+ | `datetime` | `Date`; a value without time zone is taken as UTC |
94
+ | `time` | `string` `"HH:MM:SS"` |
95
+ | `boolean` | `boolean` |
96
+
97
+ ## Security
98
+
99
+ The reader is built for files from untrusted sources:
100
+
101
+ - DTDs are refused, so there is no entity expansion and nothing is fetched (XXE, billion laughs).
102
+ - XSD imports resolve only to the definitions embedded in the package; never to disk or network.
103
+ - Nesting deeper than `maxDepth` (64) stops reading; the root element must appear within the first megabyte.
104
+ - Memory grows with the number of keys (accounts, customers and suppliers, ...), not with the number of lines:
105
+ only open elements, key values, unresolved references (at most 100,000 per reference, XAF-R017 beyond that) and
106
+ the totals of transactions being read are kept, and the diagnostics list is capped at `maxDiagnostics`.
107
+ - Text from the file is never interpreted: messages are filled without replacement patterns,
108
+ and lookups use `Map`, not plain objects.
109
+ - A stream you pass with `fromStream` is never destroyed; streams from a factory are closed when reading stops.
110
+
111
+ ## Diagnostics
112
+
113
+ Every finding is a diagnostic with a stable code from `diagnostics.json` of auditfile-spec. The report lists at most
114
+ `maxDiagnostics` (default 1000), followed by XAF-X900 when more were found. A full list makes room for errors by
115
+ leaving out infos and warnings, and fatal diagnostics are always included. `isValid`, `hasErrors`, `hasFatal` and
116
+ `count(severity)` count every diagnostic, also the ones left out; `isTruncated` says whether some were.
117
+
118
+ | Layer | Codes this reader reports |
119
+ | ----- | ------------------------- |
120
+ | XML | X001–X004 (X004 also for a part of a split file in another encoding than the first part), X900 |
121
+ | Version | V001–V006 |
122
+ | Structure | S001–S005, S008; S006 in unverified mode (in verified mode the XSD reports a missing field as D001) |
123
+ | XSD | D001, D002 |
124
+ | Rules | R001–R004, R017 |
125
+ | Dialect | C001–C003, when a dialect applies |
126
+ | Views | Q001, Q002 |
127
+
128
+ Defined in the spec but not checked yet: S007 and S009 (in verified mode the XSD reports too many occurrences and
129
+ values outside a code list as D001), R005–R016 (ascending numbers, periods, eleven test, IBAN, personal data),
130
+ X005 (the XML parser reports an invalid character as X001) and E001–E004 (envelopes).
131
+
132
+ ## XSD validation
133
+
134
+ Validation uses a streaming validator for the XSD subset that auditfile-spec uses: global and local elements,
135
+ sequences with occurrence bounds, attributes, simple types with facets (enumeration, pattern, length, digits, ranges,
136
+ white space) and `key`/`keyref`/`unique`. Every XSD of the registry compiles; a custom XSD (`xsd` option) that uses
137
+ anything else (such as `xs:choice` or `xs:any`) is refused when it is compiled, never validated halfway.
138
+ Like the .NET reader, identity constraints follow XPath 1.0: an unprefixed step selects elements without namespace.
139
+
140
+ ## Platforms
141
+
142
+ Node 20 or later. The library itself uses no file system and no Node built-ins (SHA-256 uses Node's implementation
143
+ when present, its own otherwise), so it also runs in the browser through a bundler. Its one dependency is
144
+ [saxes](https://github.com/lddubeau/saxes), a strict, well-formedness-checking XML parser.
145
+
146
+ ## Layout
147
+
148
+ | Path | Contents |
149
+ | ---- | -------- |
150
+ | `src/` | The reader; `src/memory/` holds `MemorySink` (also exported as `@xml-auditfile/auditfile/memory`) |
151
+ | `src/xsd/` | The streaming XSD validator |
152
+ | `test/` | Tests, using the XAF 3.2 sample in `test/data/xaf-3.2-sample.xaf` (two intended findings: XAF-R001, XAF-R003) |
153
+ | `spec.lock.json` | The pinned auditfile-spec release |
154
+ | `tools/` | `fetch-spec.ps1` (copies `generated/` of the pinned spec into `spec/generated/`) and `embed-spec.mjs` |
155
+
156
+ Example programs live in [auditfile-js-samples](https://github.com/XML-auditfile/auditfile-js-samples).
157
+
158
+ ## Definitions
159
+
160
+ Everything in `generated/` of a pinned auditfile-spec release (XSD, manifests, definitions, dialects, registry,
161
+ diagnostics, views) is embedded in the package as `src/generated/spec.js`. The spec is not committed:
162
+ `spec.lock.json` pins a commit, `tools/fetch-spec.ps1` copies only
163
+ `generated/` of that commit into `spec/generated/` (git-ignored; a plain folder, not a git checkout), and
164
+ `npm test` / `npm pack` embed it.
165
+
166
+ ```
167
+ pwsh tools/fetch-spec.ps1 # after cloning and whenever spec.lock.json changes
168
+ npm install
169
+ npm test
170
+ ```
171
+
172
+ To use a local spec checkout instead: `SPEC_ROOT=../auditfile-spec npm test`.
173
+
174
+ ## Workflows
175
+
176
+ | Workflow | What it does |
177
+ | -------- | ------------ |
178
+ | `ci.yml` | Push to main and pull requests: fetch the pinned spec, install, test on Node 20, 22 and 24, pack (dry run), audit dependencies |
179
+ | `release.yml` | Manual, with a version such as `1.0.1`. From `main` the version must be higher than every release; from `release/X.Y` (maintenance of an older line) it must be in line X.Y and higher than the latest release in that line. Then it fetches the pinned spec, tests, packs, creates the tag and GitHub release, and publishes to npm through Trusted Publishing when the `NPM_PUBLISH` variable is `true` (environment `npm`). Dist-tags: `latest` for the highest stable release, `next` for a pre-release, `release-X.Y` for maintenance |
180
+ | `dependabot.yml` | Weekly updates of npm packages and GitHub Actions |
181
+
182
+ ## License
183
+
184
+ Apache License 2.0.
package/package.json CHANGED
@@ -1,6 +1,64 @@
1
1
  {
2
2
  "name": "@xml-auditfile/auditfile",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.2-alpha.1",
4
+ "description": "Streaming reader for Dutch tax audit files (XAF and related), following auditfile-spec.",
5
+ "keywords": [
6
+ "xaf",
7
+ "auditfile",
8
+ "auditfile-financieel",
9
+ "xml-auditfile",
10
+ "belastingdienst",
11
+ "audit",
12
+ "accounting",
13
+ "xml"
14
+ ],
15
+ "license": "Apache-2.0",
16
+ "author": "XML-auditfile",
17
+ "homepage": "https://github.com/XML-auditfile/auditfile-js#readme",
18
+ "bugs": {
19
+ "url": "https://github.com/XML-auditfile/auditfile-js/issues"
20
+ },
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/XML-auditfile/auditfile-js.git"
24
+ },
25
+ "type": "module",
26
+ "types": "./types/index.d.ts",
27
+ "exports": {
28
+ ".": {
29
+ "types": "./types/index.d.ts",
30
+ "default": "./src/index.js"
31
+ },
32
+ "./memory": {
33
+ "types": "./types/memory/memory-sink.d.ts",
34
+ "default": "./src/memory/memory-sink.js"
35
+ }
36
+ },
37
+ "files": [
38
+ "src/",
39
+ "types/",
40
+ "LICENSE",
41
+ "README.md"
42
+ ],
43
+ "engines": {
44
+ "node": ">=20"
45
+ },
46
+ "sideEffects": false,
47
+ "publishConfig": {
48
+ "access": "public",
49
+ "provenance": true
50
+ },
51
+ "scripts": {
52
+ "spec": "node tools/embed-spec.mjs",
53
+ "types": "tsc -p tsconfig.types.json",
54
+ "pretest": "node tools/embed-spec.mjs",
55
+ "test": "node --test",
56
+ "prepack": "node tools/embed-spec.mjs && tsc -p tsconfig.types.json"
57
+ },
58
+ "dependencies": {
59
+ "saxes": "6.0.0"
60
+ },
61
+ "devDependencies": {
62
+ "typescript": "7.0.2"
63
+ }
64
+ }
@@ -0,0 +1,186 @@
1
+ import { normalizeOptions, ReadProgress } from './reading/read-options.js';
2
+ import { ReadSession } from './reading/read-session.js';
3
+ import { AuditfileSource } from './reading/source.js';
4
+ import { checkSink, ImportContext, NULL_SINK, SinkCapabilities } from './sinks/sink.js';
5
+
6
+ function checkSource(source) {
7
+ if (!(source instanceof AuditfileSource)) {
8
+ throw new TypeError('source must be an AuditfileSource.');
9
+ }
10
+
11
+ return source;
12
+ }
13
+
14
+ /**
15
+ * Entry point. Read an audit file into a sink, validate it, scan it, or stream its rows yourself.
16
+ * @example
17
+ * const sink = new MemorySink();
18
+ * const report = await Auditfile.read(AuditfileSource.fromFactory(() => fs.createReadStream('admin.xaf'), 'admin.xaf'), sink);
19
+ */
20
+ export class Auditfile {
21
+ /**
22
+ * Reads an audit file into a sink. Verified mode (default) validates against the XSD first and loads only a valid file.
23
+ * @param {AuditfileSource} source
24
+ * @param {import('./sinks/sink.js').Sink} sink
25
+ * @param {import('./reading/read-options.js').ReadOptions} [options]
26
+ * @returns {Promise<import('./diagnostics/report.js').AuditfileReport>}
27
+ */
28
+ static async read(source, sink, options = undefined) {
29
+ checkSource(source);
30
+ checkSink(sink);
31
+ const settings = normalizeOptions(options);
32
+
33
+ const session = new ReadSession(source, settings);
34
+ if (!await session.prepare(((sink.capabilities ?? 0) & SinkCapabilities.NeedsRowCounts) !== 0)) {
35
+ await session.dispose();
36
+ return session.createReport(false);
37
+ }
38
+
39
+ const schema = session.schema;
40
+ const batches = new Map();
41
+ const total = schema.hasRowCounts ? schema.tables.reduce((sum, t) => sum + (t.rowCount ?? 0), 0) : null;
42
+ let rows = 0;
43
+
44
+ try {
45
+ settings.signal?.throwIfAborted();
46
+ await sink.begin(new ImportContext(schema, session.parts));
47
+ for await (const row of session.load()) {
48
+ let batch = batches.get(row.table);
49
+ if (batch === undefined) {
50
+ batch = [];
51
+ batches.set(row.table, batch);
52
+ }
53
+
54
+ batch.push(row);
55
+ rows++;
56
+ if (batch.length >= settings.batchSize) {
57
+ settings.signal?.throwIfAborted();
58
+ batches.set(row.table, []);
59
+ await sink.write(row.table, batch);
60
+ settings.onProgress?.(new ReadProgress(rows, total));
61
+ }
62
+ }
63
+
64
+ for (const [table, batch] of [...batches].sort(([a], [b]) => a.index - b.index)) {
65
+ if (batch.length > 0) {
66
+ await sink.write(table, batch);
67
+ }
68
+ }
69
+
70
+ settings.onProgress?.(new ReadProgress(rows, total));
71
+ } catch (error) {
72
+ await session.dispose();
73
+ try {
74
+ await sink.abort(session.createReport(false));
75
+ } catch (abortError) {
76
+ // A failing rollback must not hide why the import failed: the caller gets both.
77
+ throw new AggregateError([error, abortError], 'The import failed, and aborting the sink failed too.');
78
+ }
79
+
80
+ throw error;
81
+ }
82
+
83
+ const failed = session.diagnostics.hasFatal || (session.validateDuringLoad && session.diagnostics.hasErrors);
84
+ const report = session.createReport(!failed);
85
+ if (failed) {
86
+ await sink.abort(report);
87
+ } else {
88
+ await sink.complete(report);
89
+ }
90
+
91
+ return report;
92
+ }
93
+
94
+ /**
95
+ * Validates an audit file (structure, keys, business rules) without storing anything.
96
+ * In verified mode (the default) the XSD is checked first and the rest only for a valid file;
97
+ * unverified mode skips the XSD and checks everything else, which is faster but reports fewer deviations
98
+ * (e.g. XAF-S004 instead of XAF-D001 for an invalid value).
99
+ * @param {AuditfileSource} source
100
+ * @param {import('./reading/read-options.js').ReadOptions} [options]
101
+ */
102
+ static validate(source, options = undefined) {
103
+ return Auditfile.read(source, NULL_SINK, options);
104
+ }
105
+
106
+ /**
107
+ * The scan phase only: determines the version, validates against the XSD in verified mode,
108
+ * and counts rows per table. The report's schema contains the row counts.
109
+ * @param {AuditfileSource} source
110
+ * @param {import('./reading/read-options.js').ReadOptions} [options]
111
+ */
112
+ static async scan(source, options = undefined) {
113
+ const session = new ReadSession(checkSource(source), normalizeOptions(options));
114
+ await session.prepare(true, true);
115
+ await session.dispose();
116
+ return session.createReport(false);
117
+ }
118
+
119
+ /**
120
+ * Opens an audit file for reading rows yourself, without a sink.
121
+ * @param {AuditfileSource} source
122
+ * @param {import('./reading/read-options.js').ReadOptions} [options]
123
+ */
124
+ static async open(source, options = undefined) {
125
+ const session = new ReadSession(checkSource(source), normalizeOptions(options));
126
+ const ready = await session.prepare(false);
127
+ if (!ready) {
128
+ await session.dispose();
129
+ }
130
+
131
+ return new AuditfileReader(session, ready);
132
+ }
133
+ }
134
+
135
+ /** Reads rows one by one. Check {@link AuditfileReader#schema} for null before reading: null means the file cannot be read. */
136
+ export class AuditfileReader {
137
+ #session;
138
+ #ready;
139
+ #started = false;
140
+ #report = null;
141
+
142
+ /** @internal */
143
+ constructor(session, ready) {
144
+ this.#session = session;
145
+ this.#ready = ready;
146
+ }
147
+
148
+ /** @type {import('./schema/schema.js').AuditfileSchema | null} The import schema, or null when the file cannot be read (see {@link AuditfileReader#report}). */
149
+ get schema() {
150
+ return this.#ready ? this.#session.schema : null;
151
+ }
152
+
153
+ /**
154
+ * Rows in document order; a row is returned when its element closes. The rows are read while you iterate,
155
+ * and can be iterated only once: collect them in an array when you need them twice.
156
+ * @returns {AsyncGenerator<import('./reading/row.js').AuditfileRow>}
157
+ * @throws {Error} The rows are iterated a second time.
158
+ */
159
+ async *readRows() {
160
+ if (this.#started) {
161
+ throw new Error('The rows of an audit file can be iterated only once; collect them in an array to use them twice.');
162
+ }
163
+
164
+ this.#started = true;
165
+ if (this.#ready) {
166
+ yield* this.#session.load();
167
+ }
168
+ }
169
+
170
+ /**
171
+ * The report; complete after {@link AuditfileReader#readRows} has been iterated to the end. Until then every call gives
172
+ * the report so far; the complete report is made once and kept.
173
+ */
174
+ get report() {
175
+ if (this.#report !== null) {
176
+ return this.#report;
177
+ }
178
+
179
+ const report = this.#session.createReport(false);
180
+ if (!this.#ready || this.#session.loaded) {
181
+ this.#report = report;
182
+ }
183
+
184
+ return report;
185
+ }
186
+ }