xml-event-parser 0.2.0 → 0.2.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 (2) hide show
  1. package/README.md +69 -177
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -2,18 +2,14 @@ xml-event-parser
2
2
  ================
3
3
 
4
4
  **Stream XML without loading it.** A tiny parser that gives you a document tree
5
- and path-based events in one pass: constant heap on a 240 MB CI report, 2.2 KiB
6
- gzipped, zero dependencies, and no `node:*` imports in the core entry.
7
-
8
- - **Bounded memory**: `retain: 'none'` plus a path subscription keeps only the
9
- element being read. 240 MB in, 81 MiB of RSS.
10
- - **Fast**: ~3.7x `sax` and ~4x `fast-xml-parser` on the same report, and faster
11
- than `txml` on every shape we benchmark ([numbers](bench/RESULTS.md)).
12
- - **Two views, one pass**: a tree node and an `open`/`close` event per element -
13
- no second traversal, no DOM.
14
- - **Small and portable**: 6.4 KiB minified / 2.2 KiB gzipped, zero dependencies,
15
- no `eval`, works in Node, browsers and edge runtimes (the Node adapter is a
16
- separate `xml-event-parser/stream` entry).
5
+ and path-based events in one pass.
6
+
7
+ - **Bounded memory**: keep only the element you are reading. A 240 MB report
8
+ parses in 81 MiB of RSS.
9
+ - **Fast**: ~3.7x `sax` and ~4x `fast-xml-parser` on the same report.
10
+ - **Portable**: 6.4 KiB minified / 2.2 KiB gzipped, zero dependencies, no
11
+ `node:*` imports in the core entry, no `eval`.
12
+ - **One pass, two views**: a tree node and an `open`/`close` event per element.
17
13
 
18
14
  ## When to use this
19
15
 
@@ -21,15 +17,14 @@ gzipped, zero dependencies, and no `node:*` imports in the core entry.
21
17
  | --- | --- |
22
18
  | Read a file bigger than memory: CI/test reports (JUnit, SARIF, coverage), sitemaps, GPX/KML tracks, OSM extracts | **this**, `xml-event-parser/stream` |
23
19
  | Pick elements while streaming without writing a SAX state machine | **this**, path events |
24
- | Parse occasionally in a browser or Worker where a 20 KiB parser is too much | **this**, core entry (2.2 KiB) |
25
- | Turn a small config XML into a plain object | `fast-xml-parser` or `xml2js` (richer object mapping) |
20
+ | Parse occasionally in a browser or Worker where a 20 KiB parser is too much | **this**, core entry |
21
+ | Turn a small config XML into a plain object | `fast-xml-parser` or `xml2js` |
26
22
  | DOM semantics: namespaces, XPath, mutation | `@xmldom/xmldom` |
27
- | Zero allocation, hand-tuned callbacks, no tree at all | `sax` (slightly less memory than ours, ~3.7x slower here) |
23
+ | Hand-tuned callbacks with no tree at all | `sax` |
28
24
 
29
25
  ## 240 MB in one second
30
26
 
31
- A generated JUnit report, each parser in its own process capped at 512 MB of
32
- heap - a typical CI container ([reproduce it](#development)):
27
+ Generated JUnit reports, each parser in its own process capped at 512 MB of heap:
33
28
 
34
29
  | parser | 60 MB report | 240 MB report |
35
30
  | --- | --- | --- |
@@ -37,25 +32,26 @@ heap - a typical CI container ([reproduce it](#development)):
37
32
  | sax | 0.96 s, 67 MiB | 3.80 s, 79 MiB |
38
33
  | fast-xml-parser | 1.52 s, 637 MiB | **out of memory** |
39
34
 
40
- The file grows 4x; the heap does not. `fast-xml-parser` builds a tree, so it
41
- needs roughly 7-11x the file size and dies on the larger report.
35
+ The file grows 4x; the heap does not.
42
36
 
43
- ## Quick start
37
+ ## Install
44
38
 
45
39
  ```sh
46
40
  npm install xml-event-parser
47
41
  ```
48
42
 
49
- Tree, when the document fits:
43
+ ## Quick start
44
+
45
+ ### Tree
50
46
 
51
47
  ```js
52
48
  import { XmlParser } from 'xml-event-parser';
53
49
 
54
50
  const roots = new XmlParser().parse(xml);
55
- // roots[0].tagName, roots[0].children, roots[0].text, attributes are flat
51
+ console.log(roots[0].tagName, roots[0].children);
56
52
  ```
57
53
 
58
- Stream, when it does not:
54
+ ### Stream (Node)
59
55
 
60
56
  ```js
61
57
  import { createReadStream } from 'node:fs';
@@ -69,7 +65,7 @@ await pipeline(
69
65
  new Writable({
70
66
  objectMode: true,
71
67
  write(testcase, _encoding, done) {
72
- // complete element: attributes + <failure>/<system-out> children
68
+ // testcase is complete: attributes plus <failure>/<system-out> children
73
69
  if (testcase.children?.some((child) => child.tagName === 'failure')) {
74
70
  console.log(testcase.name);
75
71
  }
@@ -79,63 +75,48 @@ await pipeline(
79
75
  );
80
76
  ```
81
77
 
82
- Without Node streams, `write()`/`end()` work anywhere:
78
+ ### Anywhere (no Node built-ins)
83
79
 
84
80
  ```js
85
- const parser = new XmlParser({ progressive: true, retain: 'none', keep: ['testsuites.testsuite.testcase'] });
81
+ const parser = new XmlParser({
82
+ progressive: true,
83
+ retain: 'none',
84
+ keep: ['testsuites.testsuite.testcase'],
85
+ });
86
+
86
87
  parser.on('</testsuites.testsuite.testcase>', (testcase) => { /* ... */ });
87
- for await (const chunk of response.body) parser.write(chunk); // no node: imports
88
+
89
+ for await (const chunk of stream) {
90
+ parser.write(chunk);
91
+ }
88
92
  parser.end();
89
93
  ```
90
94
 
91
95
  Runnable examples: [`examples/junit.mjs`](examples/junit.mjs),
92
96
  [`examples/sitemap.mjs`](examples/sitemap.mjs),
93
- [`examples/gpx.mjs`](examples/gpx.mjs) - `node examples/junit.mjs`.
97
+ [`examples/gpx.mjs`](examples/gpx.mjs).
98
+
99
+ ## API
94
100
 
95
- ## Node shape
101
+ ### Node shape
96
102
 
97
103
  ```ts
98
104
  interface XmlNode {
99
- tagName: string; // element name, e.g. 'way'
105
+ tagName: string; // element name
100
106
  children?: XmlNode[]; // present only when the element has child elements
101
107
  text?: string; // present only for text-only elements
102
- [attribute: string]: any; // attributes, copied flat onto the node
108
+ [attribute: string]: any; // attributes, flat on the node
103
109
  }
104
110
  ```
105
111
 
106
- Attributes are flat rather than nested in an `attributes` object on purpose: one
107
- object per element keeps a parsed document small (see the heap column in
108
- [`bench/RESULTS.md`](bench/RESULTS.md)). Names that collide with `tagName`,
109
- `children` or `text` are shadowed by the element's own values; if that matters
110
- for your vocabulary, read attributes off the source XML instead.
111
-
112
- An element with nested tags is emitted on close **after** its children are
113
- attached, so `node.children` is complete inside a close listener.
114
-
115
- ## Streaming
116
-
117
- ```js
118
- import { createReadStream } from 'node:fs';
119
- import { XmlParser } from 'xml-event-parser';
120
-
121
- const parser = new XmlParser({ progressive: true, retain: 'none' });
122
- parser.on('</osm.way>', (way) => {
123
- // one complete element; `way` is released after this returns
124
- });
125
-
126
- for await (const chunk of createReadStream('planet.osm.xml', 'utf8')) {
127
- parser.write(chunk);
128
- }
129
- parser.end();
130
- ```
112
+ An element is emitted on close after its children are attached, so
113
+ `node.children` is complete inside a close listener. Attributes whose names
114
+ collide with `tagName`, `children` or `text` are shadowed by those fields.
131
115
 
132
- `write()` consumes everything complete in the buffer and keeps the rest for the
133
- next call, so a chunk boundary can fall inside a tag, an attribute value, a text
134
- run, a comment or a `]]>` terminator without changing the result: parsing a
135
- document whole or in 1-byte chunks produces the same tree (the suite checks every
136
- split point).
116
+ ### Streaming and retention
137
117
 
138
- `retain` is what makes streaming bounded:
118
+ `write(chunk)` accepts a document in pieces; chunks may split anywhere, and
119
+ `end()` closes whatever is still open and returns the roots.
139
120
 
140
121
  | `retain` | keeps | `end()` returns | memory |
141
122
  | --- | --- | --- | --- |
@@ -143,159 +124,70 @@ split point).
143
124
  | `'root'` | the root being built | `[]`; a finished root is emitted and dropped | largest root |
144
125
  | `'none'` | nothing | `[]`; every element is emitted and dropped | nesting depth |
145
126
 
146
- Measured on a 60 MiB document (ten concatenated extracts, 327k elements):
147
- `retain: 'all'` holds 302 MiB, `retain: 'none'` holds ~0 MiB, both emit the same
148
- 327k elements. Without listeners, `retain: 'none'` still parses - it just throws
149
- the result away.
150
-
151
- Under `retain: 'none'`, `keep` restores the subtree of the elements you actually
152
- want, so a streamed element is complete rather than a bare tag:
127
+ With `retain: 'none'`, `keep` restores the subtree of the elements you want, so
128
+ a streamed element arrives complete rather than as a bare tag:
153
129
 
154
130
  ```js
155
131
  new XmlParser({
156
132
  progressive: true,
157
133
  retain: 'none',
158
- keep: ['testsuites.testsuite.testcase'], // 'testsuites.testsuite.testcase' or '</testsuites.testsuite.testcase>'
134
+ keep: ['testsuites.testsuite.testcase'],
159
135
  });
160
136
  ```
161
137
 
162
- Memory is then the largest matched element, not the document. `createStream`
163
- sets this up for you from its `event` path.
138
+ `createStream` applies `keep` for you from its `event` path.
164
139
 
165
- ## Events
140
+ ### Events
166
141
 
167
142
  | form | fires |
168
143
  | --- | --- |
169
144
  | `'<osm.way>'` | when a `<way>` inside `<osm>` opens |
170
145
  | `'</osm.way>'` | when it closes, with `children` populated |
171
146
 
172
- The path is the dotted chain of ancestors. Event names are only built for paths
173
- that have a listener, so subscribing to one path costs nothing for the elements
174
- you ignore. Filter inside the listener:
147
+ The path is the dotted chain of ancestors. Filter inside the listener:
175
148
 
176
149
  ```js
177
150
  parser.on('</osm.way>', (way) => {
178
- if (!way.tags) return; // or any other predicate
151
+ if (!way.tags) return;
179
152
  });
180
153
  ```
181
154
 
182
- ## Options
155
+ ### Options
183
156
 
184
157
  | option | default | meaning |
185
158
  | --- | --- | --- |
186
- | `progressive` | `false` | emit events. Without it, `parse()` only builds the tree |
187
- | `queryParent` | `false` | track parents so `parser.getParent(node)` works (costs a `WeakMap`) |
188
- | `retain` | `'all'` | what survives an element: `'all'`, `'root'` or `'none'` (see [Streaming](#streaming)) |
189
- | `keep` | `[]` | under `retain: 'none'`, dotted paths whose elements keep their subtree |
190
-
191
- `parse(xml, parent?, dir?)` also accepts an existing node to attach the parsed
192
- roots to, and a dotted path prefix used when building event names.
159
+ | `progressive` | `false` | emit events; without it `parse()` only builds the tree |
160
+ | `queryParent` | `false` | track parents for `parser.getParent(node)` |
161
+ | `retain` | `'all'` | `'all'`, `'root'` or `'none'` (see [Streaming and retention](#streaming-and-retention)) |
162
+ | `keep` | `[]` | under `retain: 'none'`, paths whose elements keep their subtree |
193
163
 
194
- The parser is non-validating and never throws on malformed input: unterminated
195
- tags, comments, processing instructions and doctypes are skipped, and elements
196
- still open at end of input are closed so a truncated download yields the
197
- document parsed so far (`'<r><a>text'` returns `r` with an `a` child whose
198
- `text` is `'text'`).
164
+ `parse(xml, parent?, dir?)` can attach the parsed roots to an existing node and
165
+ prefix event paths.
199
166
 
200
- CDATA sections are content, not markup: their text is kept verbatim and is not
201
- entity-decoded, while text outside them is decoded (the five predefined
202
- entities and numeric character references).
167
+ Malformed input never throws: comments, processing instructions and doctypes
168
+ are skipped, and elements still open at end of input are closed, so a truncated
169
+ download yields the document parsed so far. CDATA content is kept verbatim and
170
+ not entity-decoded; text outside CDATA is.
203
171
 
204
172
  ## Benchmarks
205
173
 
206
- Six generated shapes, each isolating one cost (per-element, per-child, text,
207
- nesting). Methodology, per-shape tables and caveats live in
208
- [`bench/RESULTS.md`](bench/RESULTS.md); rerun with `npm run bench:data && npm run bench`.
209
-
210
- Realistic Overpass-style document, 6.0 MiB, Apple M4 Pro / Node 26:
174
+ Speed on six generated shapes (Overpass-style documents, children-heavy, text,
175
+ nesting), against `txml`, `fast-xml-parser`, `sax` and `htmlparser2`:
211
176
 
212
177
  | workload | xml-event-parser | txml | fast-xml-parser | sax | htmlparser2 |
213
178
  | --- | --- | --- | --- | --- | --- |
214
179
  | tree (parse + walk) | **26.0 ms, 230 MB/s** | 50.6 ms, 118 MB/s | 167.8 ms, 36 MB/s | — | — |
215
- | tree, retained heap | **30.0 MiB** | 42.5 MiB | 35.2 MiB | — | — |
216
180
  | element callbacks | **27.8 ms, 215 MB/s** | — | — | 100.0 ms, 60 MB/s | 44.9 ms, 133 MB/s |
217
181
  | streamed, 64 KiB chunks | **27.3 ms, 219 MB/s** | 77.4 ms, 77 MB/s | — | 103.3 ms, 58 MB/s | 50.8 ms, 118 MB/s |
218
182
 
219
- Notes on reading the table:
220
-
221
- - The callback and streamed rows for `xml-event-parser` use `retain: 'none'`, so
222
- they do not build a document either; the tree row is the only one that holds
223
- memory. `txml`'s streaming API is a Node stream (`transformStream`), measured
224
- separately and asynchronously.
225
- - Text-heavy documents with many entities and CDATA used to be the weak shape;
226
- replacing the regex decoder with a manual scan took it from 325 to 442 MB/s,
227
- ahead of `txml` (382 MB/s).
228
-
229
- ## Status
230
-
231
- Extracted from [osm2geojson-lite](https://github.com/tibetty/osm2geojson-lite),
232
- where this parser served until 2.2.0 and was then replaced by a purpose-built
233
- OSM scanner. The code and its original unit tests are unchanged apart from the
234
- public naming (`children`/`tagName`/`text` instead of `$innerNodes`/`$tag`/
235
- `$innerText`) and the removal of the `new Function`-based conditioned-path
236
- events.
237
-
238
- Published as `xml-event-parser` (current version on npm). Releases are cut by
239
- changing `version` on `main`: `release.yml` publishes through npm trusted
240
- publishing (OIDC, with provenance), tags `v<version>` and creates the GitHub
241
- release. The job runs only when the repository variable
242
- `NPM_TRUSTED_PUBLISHER` is `true`.
243
-
244
- ## Development
245
-
246
- ```sh
247
- npm ci
248
- npm test # unit tests
249
- npm run typecheck
250
- npm run build # dist/index.mjs, dist/index.cjs, dist/index.d.ts
251
- npm run bench:data # generate ~27 MiB benchmark corpus (gitignored)
252
- npm run bench:memory # JUnit memory/time table under a 512 MB heap cap
253
- npm run bench # compare against txml / sax / htmlparser2 / fast-xml-parser
254
- ```
255
-
256
- ## Releasing
257
-
258
- `release.yml` publishes with npm trusted publishing (OIDC) and is gated on the
259
- repository variable `NPM_TRUSTED_PUBLISHER`, which stays unset until a trusted
260
- publisher exists.
261
-
262
- One-time bootstrap, because npm cannot attach a trusted publisher to a package
263
- that does not exist yet:
264
-
265
- 1. Publish the first version locally:
266
-
267
- ```sh
268
- npm login
269
- npm publish --access public
270
- ```
271
-
272
- 2. npmjs.com -> Packages -> `xml-event-parser` -> Settings -> **Trusted
273
- publishing** -> GitHub Actions:
274
-
275
- | field | value |
276
- | --- | --- |
277
- | Organization or user | `tibetty` |
278
- | Repository | `xml-event-parser` |
279
- | Workflow filename | `release.yml` (filename only, case-sensitive) |
280
- | Environment name | leave empty |
281
- | Allowed actions | tick **npm publish** |
282
-
283
- Configurations created after September 2026 default to `npm stage publish`
284
- only, so `npm publish` has to be ticked explicitly. The first publish through
285
- that workflow must complete within **two days**, or the configuration expires.
286
-
287
- 3. GitHub -> Settings -> Secrets and variables -> Actions -> Variables: add
288
- `NPM_TRUSTED_PUBLISHER` = `true`.
183
+ Full tables, methodology and caveats: [`bench/RESULTS.md`](bench/RESULTS.md).
289
184
 
290
- 4. Optional hardening, once a workflow publish has succeeded: npmjs.com ->
291
- package Settings -> Publishing access -> *Require two-factor authentication
292
- and disallow tokens*.
185
+ ## Contributing
293
186
 
294
- After that, changing `version` in `package.json` on `main` publishes through
295
- `release.yml`, tags `v<version>` and creates the GitHub release. npm generates
296
- provenance automatically only for a public repository; from a private one the
297
- package is published without an attestation.
187
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for development commands, tests,
188
+ benchmarks and the release process.
298
189
 
299
190
  ## License
300
191
 
301
- MIT. Includes work contributed to `osm2geojson-lite` by Harel Mazor.
192
+ MIT. Includes work contributed to
193
+ [osm2geojson-lite](https://github.com/tibetty/osm2geojson-lite) by Harel Mazor.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "xml-event-parser",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "Tiny dependency-free XML parser with a tree and path-based events in one pass",
5
5
  "repository": {
6
6
  "type": "git",