@eksml/xml 0.1.0

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 (63) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +588 -0
  3. package/dist/converters/fromLossless.d.mts +14 -0
  4. package/dist/converters/fromLossless.d.mts.map +1 -0
  5. package/dist/converters/fromLossless.mjs +35 -0
  6. package/dist/converters/fromLossless.mjs.map +1 -0
  7. package/dist/converters/fromLossy.d.mts +18 -0
  8. package/dist/converters/fromLossy.d.mts.map +1 -0
  9. package/dist/converters/fromLossy.mjs +91 -0
  10. package/dist/converters/fromLossy.mjs.map +1 -0
  11. package/dist/converters/lossless.d.mts +39 -0
  12. package/dist/converters/lossless.d.mts.map +1 -0
  13. package/dist/converters/lossless.mjs +74 -0
  14. package/dist/converters/lossless.mjs.map +1 -0
  15. package/dist/converters/lossy.d.mts +42 -0
  16. package/dist/converters/lossy.d.mts.map +1 -0
  17. package/dist/converters/lossy.mjs +158 -0
  18. package/dist/converters/lossy.mjs.map +1 -0
  19. package/dist/htmlConstants-D6fsKbZ-.mjs +30 -0
  20. package/dist/htmlConstants-D6fsKbZ-.mjs.map +1 -0
  21. package/dist/parser-BfdEfWDg.d.mts +95 -0
  22. package/dist/parser-BfdEfWDg.d.mts.map +1 -0
  23. package/dist/parser-CYq309aR.mjs +479 -0
  24. package/dist/parser-CYq309aR.mjs.map +1 -0
  25. package/dist/parser.d.mts +2 -0
  26. package/dist/parser.mjs +2 -0
  27. package/dist/sax.d.mts +64 -0
  28. package/dist/sax.d.mts.map +1 -0
  29. package/dist/sax.mjs +70 -0
  30. package/dist/sax.mjs.map +1 -0
  31. package/dist/saxEngine-BDnD7ruG.mjs +750 -0
  32. package/dist/saxEngine-BDnD7ruG.mjs.map +1 -0
  33. package/dist/utilities/index.d.mts +88 -0
  34. package/dist/utilities/index.d.mts.map +1 -0
  35. package/dist/utilities/index.mjs +87 -0
  36. package/dist/utilities/index.mjs.map +1 -0
  37. package/dist/writer.d.mts +58 -0
  38. package/dist/writer.d.mts.map +1 -0
  39. package/dist/writer.mjs +357 -0
  40. package/dist/writer.mjs.map +1 -0
  41. package/dist/xmlParseStream.d.mts +138 -0
  42. package/dist/xmlParseStream.d.mts.map +1 -0
  43. package/dist/xmlParseStream.mjs +313 -0
  44. package/dist/xmlParseStream.mjs.map +1 -0
  45. package/package.json +100 -0
  46. package/src/converters/fromLossless.ts +80 -0
  47. package/src/converters/fromLossy.ts +180 -0
  48. package/src/converters/lossless.ts +116 -0
  49. package/src/converters/lossy.ts +274 -0
  50. package/src/parser.ts +728 -0
  51. package/src/sax.ts +157 -0
  52. package/src/saxEngine.ts +1157 -0
  53. package/src/utilities/escapeRegExp.ts +19 -0
  54. package/src/utilities/filter.ts +63 -0
  55. package/src/utilities/getElementById.ts +21 -0
  56. package/src/utilities/getElementsByClassName.ts +22 -0
  57. package/src/utilities/htmlConstants.ts +26 -0
  58. package/src/utilities/index.ts +7 -0
  59. package/src/utilities/isElementNode.ts +19 -0
  60. package/src/utilities/isTextNode.ts +19 -0
  61. package/src/utilities/toContentString.ts +23 -0
  62. package/src/writer.ts +650 -0
  63. package/src/xmlParseStream.ts +597 -0
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2015 Tobias Nickel
4
+ Copyright (c) 2026 Liam Potter
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,588 @@
1
+ <picture>
2
+ <source media="(prefers-color-scheme: dark)" srcset="./logo-dark.svg">
3
+ <source media="(prefers-color-scheme: light)" srcset="./logo.svg">
4
+ <img alt="Eksml" src="./logo.svg">
5
+ </picture>
6
+
7
+ # Eksml
8
+
9
+ [![CI](https://github.com/evoactivity/eksml/actions/workflows/ci.yml/badge.svg)](https://github.com/evoactivity/eksml/actions/workflows/ci.yml)
10
+ [![npm](https://img.shields.io/npm/v/@eksml/xml)](https://www.npmjs.com/package/@eksml/xml)
11
+ [![license](https://img.shields.io/npm/l/@eksml/xml)](https://github.com/evoactivity/eksml/blob/main/LICENSE)
12
+
13
+ A fast, lightweight XML/HTML parser, serializer, and streaming toolkit for JavaScript and TypeScript. Import only what you need — tree parsing, SAX streaming, object conversion, or serialization — each as a standalone export.
14
+
15
+ Built on the same core parsing architecture as [tXml](https://github.com/tobiasNickel/tXml) by Tobias Nickel, Eksml improves the performance and extends it with additional features.
16
+
17
+ **[Try the interactive demo](https://evoactivity.github.io/eksml/)**
18
+
19
+ ## Installation
20
+
21
+ ```bash
22
+ pnpm add @eksml/xml
23
+ ```
24
+
25
+ ```bash
26
+ npm install @eksml/xml
27
+ ```
28
+
29
+ ```bash
30
+ yarn add @eksml/xml
31
+ ```
32
+
33
+ Eksml is **ESM-only**. It requires Node.js 18+ and a runtime that supports ES modules. There are no CommonJS exports.
34
+
35
+ ## Quick Start
36
+
37
+ ```ts
38
+ import { parse } from '@eksml/xml/parser';
39
+ import { write } from '@eksml/xml/writer';
40
+
41
+ const dom = parse('<root><item id="1">Hello</item></root>');
42
+ const str = write(dom);
43
+ ```
44
+
45
+ ---
46
+
47
+ ## API
48
+
49
+ ```ts
50
+ import { parse } from '@eksml/xml/parser';
51
+
52
+ const dom = parse('<root><item>Hello</item></root>');
53
+ ```
54
+
55
+ #### `ParseOptions`
56
+
57
+ <table>
58
+ <tr>
59
+ <th>Option</th>
60
+ <th>Type</th>
61
+ <th>Default</th>
62
+ <th>Description</th>
63
+ </tr>
64
+ <tr>
65
+ <td><code>pos</code></td>
66
+ <td><code>number</code></td>
67
+ <td><code>0</code></td>
68
+ <td>Starting character position in the string</td>
69
+ </tr>
70
+ <tr>
71
+ <td><code>html</code></td>
72
+ <td><code>boolean</code></td>
73
+ <td><code>false</code></td>
74
+ <td>Enable HTML mode (sets void element and raw content tag defaults)</td>
75
+ </tr>
76
+ <tr>
77
+ <td><code>selfClosingTags</code></td>
78
+ <td><code>string[]</code></td>
79
+ <td><code>[]</code> / HTML voids</td>
80
+ <td>Tag names treated as self-closing void elements</td>
81
+ </tr>
82
+ <tr>
83
+ <td><code>rawContentTags</code></td>
84
+ <td><code>string[]</code></td>
85
+ <td><code>[]</code> / <code>['script','style']</code></td>
86
+ <td>Tag names whose content is raw text (not parsed)</td>
87
+ </tr>
88
+ <tr>
89
+ <td><code>keepComments</code></td>
90
+ <td><code>boolean</code></td>
91
+ <td><code>false</code></td>
92
+ <td>Include XML/HTML comments in the output tree</td>
93
+ </tr>
94
+ <tr>
95
+ <td><code>trimWhitespace</code></td>
96
+ <td><code>boolean</code></td>
97
+ <td><code>false</code></td>
98
+ <td>Trim text nodes and discard whitespace-only text</td>
99
+ </tr>
100
+ <tr>
101
+ <td><code>strict</code></td>
102
+ <td><code>boolean</code></td>
103
+ <td><code>false</code></td>
104
+ <td>Throw on malformed XML instead of recovering silently</td>
105
+ </tr>
106
+ <tr>
107
+ <td><code>entities</code></td>
108
+ <td><code>boolean</code></td>
109
+ <td><code>false</code></td>
110
+ <td>Decode XML/HTML entities in text and attributes</td>
111
+ </tr>
112
+ <tr>
113
+ <td><code>attrName</code></td>
114
+ <td><code>string</code></td>
115
+ <td><code>'id'</code></td>
116
+ <td>Attribute name to search for (used with <code>attrValue</code>)</td>
117
+ </tr>
118
+ <tr>
119
+ <td><code>attrValue</code></td>
120
+ <td><code>string</code></td>
121
+ <td>--</td>
122
+ <td>Regex pattern to match attribute values (fast-path filter)</td>
123
+ </tr>
124
+ <tr>
125
+ <td><code>filter</code></td>
126
+ <td><code>(node, index, depth, path) =&gt; boolean</code></td>
127
+ <td>--</td>
128
+ <td>Predicate to filter nodes during parsing</td>
129
+ </tr>
130
+ </table>
131
+
132
+ #### `TNode`
133
+
134
+ ```ts
135
+ interface TNode {
136
+ tagName: string;
137
+ attributes: Record<string, string | null> | null;
138
+ children: (TNode | string)[];
139
+ }
140
+ ```
141
+
142
+ - `attributes` is `null` when the element has no attributes.
143
+ - Attribute values are `string` for valued attributes, `null` for boolean attributes (e.g. `<input disabled>`).
144
+
145
+ ---
146
+
147
+ ### `write(input, options?)`
148
+
149
+ Serialize a DOM tree, lossy object, or lossless entries back to an XML/HTML string.
150
+ Input format is auto-detected — no manual conversion needed.
151
+
152
+ ```ts
153
+ import { write } from '@eksml/xml/writer';
154
+
155
+ // DOM input
156
+ const xml = write(dom);
157
+ const pretty = write(dom, { pretty: true });
158
+ const html = write(dom, { html: true, entities: true });
159
+
160
+ // Lossy input — converted to DOM automatically
161
+ const fromObj = write({ user: { name: 'Alice', age: 30 } });
162
+ // -> '<user><name>Alice</name><age>30</age></user>'
163
+
164
+ // Lossless input — converted to DOM automatically
165
+ const fromEntries = write([
166
+ { user: [{ name: ['Alice'] }, { role: ['admin'] }] },
167
+ ]);
168
+ // -> '<user><name>Alice</name><role>admin</role></user>'
169
+ ```
170
+
171
+ #### `WriterOptions`
172
+
173
+ <table>
174
+ <tr>
175
+ <th>Option</th>
176
+ <th>Type</th>
177
+ <th>Default</th>
178
+ <th>Description</th>
179
+ </tr>
180
+ <tr>
181
+ <td><code>pretty</code></td>
182
+ <td><code>boolean | string</code></td>
183
+ <td><code>false</code></td>
184
+ <td>
185
+ Pretty-print with indentation. <code>true</code> uses 2 spaces; a string
186
+ value is used as the indent (e.g. <code>'\t'</code>).
187
+ </td>
188
+ </tr>
189
+ <tr>
190
+ <td><code>entities</code></td>
191
+ <td><code>boolean</code></td>
192
+ <td><code>false</code></td>
193
+ <td>Encode special characters as XML/HTML entities</td>
194
+ </tr>
195
+ <tr>
196
+ <td><code>html</code></td>
197
+ <td><code>boolean</code></td>
198
+ <td><code>false</code></td>
199
+ <td>
200
+ HTML mode: void elements emit as <code>&lt;br&gt;</code> instead of
201
+ <code>&lt;br/&gt;</code>, and HTML named entities are used when
202
+ <code>entities</code> is also <code>true</code>
203
+ </td>
204
+ </tr>
205
+ </table>
206
+
207
+ ---
208
+
209
+ ### `createSaxParser(options?)`
210
+
211
+ A high-performance EventEmitter-style SAX parser. Feed it chunks of XML and receive events via `.on()` / `.off()` handlers. Handlers can be added and removed dynamically at any time.
212
+
213
+ ```ts
214
+ import { createSaxParser } from '@eksml/xml/sax';
215
+
216
+ const parser = createSaxParser();
217
+
218
+ parser.on('openTag', (tagName, attributes) => {
219
+ console.log('opened:', tagName, attributes);
220
+ });
221
+ parser.on('text', (text) => {
222
+ console.log('text:', text);
223
+ });
224
+
225
+ parser.write('<root><item>1</item>');
226
+ parser.write('<item>2</item></root>');
227
+ parser.close();
228
+
229
+ // Remove a handler
230
+ parser.off('openTag', myHandler);
231
+ ```
232
+
233
+ #### `SaxParserOptions`
234
+
235
+ <table>
236
+ <tr>
237
+ <th>Option</th>
238
+ <th>Type</th>
239
+ <th>Default</th>
240
+ <th>Description</th>
241
+ </tr>
242
+ <tr>
243
+ <td><code>html</code></td>
244
+ <td><code>boolean</code></td>
245
+ <td><code>false</code></td>
246
+ <td>Enable HTML mode (sets void element and raw content tag defaults)</td>
247
+ </tr>
248
+ <tr>
249
+ <td><code>selfClosingTags</code></td>
250
+ <td><code>string[]</code></td>
251
+ <td><code>[]</code> / HTML voids</td>
252
+ <td>Tag names treated as self-closing void elements</td>
253
+ </tr>
254
+ <tr>
255
+ <td><code>rawContentTags</code></td>
256
+ <td><code>string[]</code></td>
257
+ <td><code>[]</code> / <code>['script','style']</code></td>
258
+ <td>Tag names whose content is raw text</td>
259
+ </tr>
260
+ </table>
261
+
262
+ #### SAX Events
263
+
264
+ <table>
265
+ <tr>
266
+ <th>Event</th>
267
+ <th>Handler signature</th>
268
+ <th>Description</th>
269
+ </tr>
270
+ <tr>
271
+ <td><code>openTag</code></td>
272
+ <td><code>(tagName, attributes) =&gt; void</code></td>
273
+ <td>Opening tag with parsed attributes</td>
274
+ </tr>
275
+ <tr>
276
+ <td><code>closeTag</code></td>
277
+ <td><code>(tagName) =&gt; void</code></td>
278
+ <td>Closing tag</td>
279
+ </tr>
280
+ <tr>
281
+ <td><code>text</code></td>
282
+ <td><code>(text) =&gt; void</code></td>
283
+ <td>Text content between tags</td>
284
+ </tr>
285
+ <tr>
286
+ <td><code>cdata</code></td>
287
+ <td><code>(data) =&gt; void</code></td>
288
+ <td>CDATA section content</td>
289
+ </tr>
290
+ <tr>
291
+ <td><code>comment</code></td>
292
+ <td><code>(comment) =&gt; void</code></td>
293
+ <td>Comment (full <code>&lt;!-- ... --&gt;</code> string including delimiters)</td>
294
+ </tr>
295
+ <tr>
296
+ <td><code>processingInstruction</code></td>
297
+ <td><code>(name, body) =&gt; void</code></td>
298
+ <td>Processing instruction</td>
299
+ </tr>
300
+ <tr>
301
+ <td><code>doctype</code></td>
302
+ <td><code>(tagName, attributes) =&gt; void</code></td>
303
+ <td>DOCTYPE declaration</td>
304
+ </tr>
305
+ </table>
306
+
307
+ ---
308
+
309
+ ### `new XmlParseStream(options?)`
310
+
311
+ A Web Streams `TransformStream` that parses XML chunks into `TNode` subtrees. Works in browsers, Node.js 18+, Deno, and Bun. Follows the platform stream class convention (`TextDecoderStream`, `DecompressionStream`, etc.).
312
+
313
+ ```ts
314
+ import { XmlParseStream } from '@eksml/xml/stream';
315
+
316
+ const response = await fetch('/feed.xml');
317
+ const reader = response.body
318
+ .pipeThrough(new TextDecoderStream())
319
+ .pipeThrough(new XmlParseStream())
320
+ .getReader();
321
+
322
+ while (true) {
323
+ const { done, value } = await reader.read();
324
+ if (done) break;
325
+ console.log(value); // TNode or string
326
+ }
327
+ ```
328
+
329
+ #### `XmlParseStreamOptions`
330
+
331
+ <table>
332
+ <tr>
333
+ <th>Option</th>
334
+ <th>Type</th>
335
+ <th>Default</th>
336
+ <th>Description</th>
337
+ </tr>
338
+ <tr>
339
+ <td><code>offset</code></td>
340
+ <td><code>number | string</code></td>
341
+ <td><code>0</code></td>
342
+ <td>Starting byte offset — skip this many leading characters. When a string is passed, its <code>.length</code> is used.</td>
343
+ </tr>
344
+ <tr>
345
+ <td><code>html</code></td>
346
+ <td><code>boolean</code></td>
347
+ <td><code>false</code></td>
348
+ <td>Enable HTML mode</td>
349
+ </tr>
350
+ <tr>
351
+ <td><code>selfClosingTags</code></td>
352
+ <td><code>string[]</code></td>
353
+ <td><code>[]</code> / HTML voids</td>
354
+ <td>Tag names treated as self-closing</td>
355
+ </tr>
356
+ <tr>
357
+ <td><code>rawContentTags</code></td>
358
+ <td><code>string[]</code></td>
359
+ <td><code>[]</code> / <code>['script','style']</code></td>
360
+ <td>Tag names whose content is raw text</td>
361
+ </tr>
362
+ <tr>
363
+ <td><code>keepComments</code></td>
364
+ <td><code>boolean</code></td>
365
+ <td><code>false</code></td>
366
+ <td>Include comments in the output</td>
367
+ </tr>
368
+ <tr>
369
+ <td><code>select</code></td>
370
+ <td><code>string | string[]</code></td>
371
+ <td>--</td>
372
+ <td>Emit only elements matching these tag names as they close, regardless of nesting depth</td>
373
+ </tr>
374
+ <tr>
375
+ <td><code>output</code></td>
376
+ <td><code>'dom' | 'lossy' | 'lossless'</code></td>
377
+ <td><code>'dom'</code></td>
378
+ <td>Output format — <code>'dom'</code> emits <code>TNode | string</code>, <code>'lossy'</code> emits <code>LossyValue</code>, <code>'lossless'</code> emits <code>LosslessEntry</code></td>
379
+ </tr>
380
+ </table>
381
+
382
+ The `select` option is particularly useful for large feeds:
383
+
384
+ ```ts
385
+ // Emit each <item> independently instead of waiting for the root to close
386
+ const stream = new XmlParseStream({ select: 'item' });
387
+ ```
388
+
389
+ ---
390
+
391
+ ### `lossy(input, options?)`
392
+
393
+ Convert XML into compact JavaScript objects. Ideal when you need a simple JS representation and don't care about preserving document order between mixed siblings.
394
+
395
+ `input` is `string | (TNode | string)[]` — pass a raw XML string, or a pre-parsed DOM array (from `parse()` or `stream()`).
396
+
397
+ ```ts
398
+ import { lossy } from '@eksml/xml/lossy';
399
+
400
+ lossy('<user><name>Alice</name><age>30</age></user>');
401
+ // => { user: { name: "Alice", age: "30" } }
402
+ ```
403
+
404
+ - Text-only elements become string values
405
+ - Empty/void elements become `null`
406
+ - Attributes are `$`-prefixed keys (e.g. `$href`)
407
+ - Repeated same-name siblings become arrays
408
+ - Mixed content (text interleaved with elements) is stored in a `$$` array
409
+
410
+ > [!note]
411
+ > Accepts the same ParseOptions as parse().
412
+
413
+ ---
414
+
415
+ ### `lossless(input, options?)`
416
+
417
+ Convert XML into an order-preserving JSON-friendly structure. Every node, attribute, text segment, and comment is represented in document order.
418
+
419
+ `input` is `string | (TNode | string)[]` — pass a raw XML string, or a pre-parsed DOM array (from `parse()` or `stream()`).
420
+
421
+ ```ts
422
+ import { lossless } from '@eksml/xml/lossless';
423
+
424
+ lossless('<user id="1"><name>Alice</name></user>');
425
+ // => [{ user: [{ $attr: { id: "1" } }, { name: [{ $text: "Alice" }] }] }]
426
+ ```
427
+
428
+ Each entry type:
429
+
430
+ - Element: `{ tagName: children[] }`
431
+ - Text: `{ $text: "..." }`
432
+ - Attributes: `{ $attr: { ... } }` (first child of its element)
433
+ - Comment: `{ $comment: "..." }`
434
+
435
+ > [!note]
436
+ > Accepts the same ParseOptions as parse().
437
+
438
+ ---
439
+
440
+ ### `fromLossy(input)` / `fromLossless(entries)`
441
+
442
+ Convert lossy or lossless representations back into `TNode` DOM trees.
443
+
444
+ > **Note:** `write()` auto-detects lossy and lossless inputs, so you rarely
445
+ > need these directly. They're useful when you want the DOM tree for inspection
446
+ > or further manipulation before serializing.
447
+
448
+ ```ts
449
+ import { fromLossy } from '@eksml/xml/from-lossy';
450
+ import { fromLossless } from '@eksml/xml/from-lossless';
451
+ import { write } from '@eksml/xml/writer';
452
+
453
+ // Explicit conversion (when you need the DOM tree)
454
+ const dom = fromLossy({ user: { name: 'Alice' } });
455
+ write(dom); // => '<user><name>Alice</name></user>'
456
+
457
+ // Or just pass lossy/lossless directly to write()
458
+ write({ user: { name: 'Alice' } }); // same result
459
+ ```
460
+
461
+ ---
462
+
463
+ ### Utilities
464
+
465
+ ```ts
466
+ import {
467
+ filter,
468
+ getElementById,
469
+ getElementsByClassName,
470
+ toContentString,
471
+ isTextNode,
472
+ isElementNode,
473
+ HTML_VOID_ELEMENTS,
474
+ HTML_RAW_CONTENT_TAGS,
475
+ } from '@eksml/xml/utilities';
476
+ ```
477
+
478
+ <table>
479
+ <tr>
480
+ <th>Export</th>
481
+ <th>Description</th>
482
+ </tr>
483
+ <tr>
484
+ <td><code>filter(input, predicate)</code></td>
485
+ <td>Recursively walk a tree and return all <code>TNode</code>s matching a predicate</td>
486
+ </tr>
487
+ <tr>
488
+ <td><code>getElementById(input, id)</code></td>
489
+ <td>Find an element by its <code>id</code> attribute</td>
490
+ </tr>
491
+ <tr>
492
+ <td><code>getElementsByClassName(input, className)</code></td>
493
+ <td>Find elements by class name (supports multi-class attributes)</td>
494
+ </tr>
495
+ <tr>
496
+ <td><code>toContentString(node)</code></td>
497
+ <td>Extract concatenated text content from a node or tree</td>
498
+ </tr>
499
+ <tr>
500
+ <td><code>isTextNode(node)</code></td>
501
+ <td>Type guard: <code>node is string</code></td>
502
+ </tr>
503
+ <tr>
504
+ <td><code>isElementNode(node)</code></td>
505
+ <td>Type guard: <code>node is TNode</code></td>
506
+ </tr>
507
+ <tr>
508
+ <td><code>HTML_VOID_ELEMENTS</code></td>
509
+ <td>Standard HTML void element tag names</td>
510
+ </tr>
511
+ <tr>
512
+ <td><code>HTML_RAW_CONTENT_TAGS</code></td>
513
+ <td>HTML raw content tag names (<code>script</code>, <code>style</code>)</td>
514
+ </tr>
515
+ </table>
516
+
517
+ ---
518
+
519
+ ## Benchmarks
520
+
521
+ Eksml is consistently the fastest across parsing, streaming, and serialization. Benchmarks run via [Vitest bench](https://vitest.dev/guide/features.html#benchmarking) against real-world XML fixtures from ~100 B to ~30 KB.
522
+
523
+ - **DOM parsing**: 1.2-1.5x faster than tXml, 3-4x faster than htmlparser2, 7-15x faster than fast-xml-parser/xml2js/xmldom
524
+ - **SAX streaming**: 1.6-2.5x faster than htmlparser2/saxes, 3-6x faster than sax
525
+ - **Raw tokenization**: 2-2.5x faster than saxes, 2-3x faster than htmlparser2, 4-6x faster than sax
526
+ - **Serialization**: Trades top position with tXml; both are 3-7x faster than xmldom and 7-13x faster than fast-xml-parser/xml2js
527
+
528
+ Full results with per-fixture op/s tables: **[BENCHMARKS.md](https://github.com/evoactivity/eksml/blob/main/eksml/BENCHMARKS.md)**
529
+
530
+ Run similar benchmarks in your browser: **[Interactive benchmark](https://evoactivity.github.io/eksml/benchmark)**
531
+
532
+ ---
533
+
534
+ ## HTML Support
535
+
536
+ Eksml can parse and serialize HTML, but it is **not an HTML spec-compliant parser**. It does not implement the [WHATWG HTML parsing algorithm](https://html.spec.whatwg.org/multipage/parsing.html) — there is no tokenizer state machine, no tree construction stage, no implicit element insertion, and no error recovery for malformed markup.
537
+
538
+ What Eksml does provide is a set of **HTML-aware options** that cover the most common differences between XML and HTML:
539
+
540
+ - **Void elements** — `<br>`, `<img>`, `<input>`, etc. are recognized as self-closing when `html: true` is set (or when you provide a custom `selfClosingTags` list). The full list is exported as `HTML_VOID_ELEMENTS` from `@eksml/xml/utilities`.
541
+ - **Raw content tags** — `<script>` and `<style>` content is treated as raw text (not parsed for child elements) when `html: true` is set. Customizable via `rawContentTags`. Exported as `HTML_RAW_CONTENT_TAGS`.
542
+ - **Entity encoding** — The writer uses HTML named entities (e.g. `&nbsp;`, `&copy;`) instead of numeric references when `html: true` and `entities: true` are both set.
543
+ - **Serialization style** — Void elements serialize as `<br>` instead of `<br/>` in HTML mode.
544
+
545
+ This is sufficient for well-formed HTML and most real-world documents. However, Eksml will not handle things like:
546
+
547
+ - Optional closing tags (`<li>` without `</li>`, `<p>` auto-closed by a sibling `<p>`)
548
+ - Implicit elements (`<html>`, `<head>`, `<body>` inserted by the spec when missing)
549
+ - Misnested formatting tags (the adoption agency algorithm)
550
+ - `<table>` foster parenting
551
+
552
+ If you need full HTML spec compliance, use a dedicated HTML parser like [parse5](https://github.com/inikulin/parse5) or the browser's built-in `DOMParser`.
553
+
554
+ ---
555
+
556
+ ## Acknowledgments
557
+
558
+ Eksml's DOM parser is built on the work of **[Tobias Nickel](https://github.com/nickel-org)** and his [tXml](https://github.com/tobiasNickel/tXml) library. The core parsing architecture, a single-pass, position-tracking string scanner that builds the tree as it goes, is what makes both libraries so fast. tXml demonstrated that you don't need a separate tokenizer-then-tree-builder pipeline to parse XML at high speed, and Eksml carries that insight forward.
559
+
560
+ Eksml extends tXml's foundation with:
561
+
562
+ - A high-performance SAX streaming engine with an EventEmitter-style API (`createSaxParser`)
563
+ - A Web Streams `TransformStream` for incremental parsing (`XmlParseStream`)
564
+ - Lossy and lossless JSON converters with round-trip support
565
+ - HTML-aware parsing and serialization (void elements, raw content tags, entity encoding)
566
+ - Strict mode validation
567
+ - Entity decoding (XML and full HTML named entities)
568
+
569
+ Thank you, Tobias, for the elegant approach that made all of this possible.
570
+
571
+ ---
572
+
573
+ ## Limitations
574
+
575
+ Eksml optimizes for speed and simplicity, which means it intentionally does not cover every XML use case:
576
+
577
+ - **Not a validating parser.** Eksml does not validate against DTDs or XML Schema. It parses structure, not semantics.
578
+ - **No namespace support.** Namespace prefixes are preserved in tag and attribute names (e.g. `soap:Envelope`) but not resolved to URIs. There is no namespace-aware API.
579
+ - **No XPath or CSS selectors.** Querying uses simple functions like `filter()`, `getElementById()`, and `getElementsByClassName()`. For complex queries, use the DOM output with a dedicated query library.
580
+ - **Entity decoding is opt-in.** By default, entities like `&amp;` and `&#x20;` are left as-is in text and attribute values. Pass `entities: true` to decode them.
581
+ - **Not a drop-in replacement for the W3C DOM.** `TNode` is a plain object with `tagName`, `attributes`, and `children` -- not a `Node`/`Element`/`Document` with methods like `querySelector`, `parentNode`, etc.
582
+ - **Single-threaded.** Parsing runs synchronously on the calling thread. For CPU-bound workloads with very large documents, consider offloading to a Web Worker.
583
+
584
+ ---
585
+
586
+ ## License
587
+
588
+ MIT
@@ -0,0 +1,14 @@
1
+ import { n as TNode } from "../parser-BfdEfWDg.mjs";
2
+ import { LosslessEntry } from "./lossless.mjs";
3
+
4
+ //#region src/converters/fromLossless.d.ts
5
+ /**
6
+ * Convert a lossless JSON entry array back to a `(TNode | string)[]` DOM tree.
7
+ *
8
+ * @param entries - The lossless entry array (as returned by `lossless()`).
9
+ * @returns A DOM array suitable for `write()` or further processing.
10
+ */
11
+ declare function fromLossless(entries: LosslessEntry[]): (TNode | string)[];
12
+ //#endregion
13
+ export { fromLossless };
14
+ //# sourceMappingURL=fromLossless.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fromLossless.d.mts","names":[],"sources":["../../src/converters/fromLossless.ts"],"mappings":";;;;;;;;;;iBAkCgB,YAAA,CAAa,OAAA,EAAS,aAAA,MAAmB,KAAA"}
@@ -0,0 +1,35 @@
1
+ //#region src/converters/fromLossless.ts
2
+ /**
3
+ * Convert a lossless JSON entry array back to a `(TNode | string)[]` DOM tree.
4
+ *
5
+ * @param entries - The lossless entry array (as returned by `lossless()`).
6
+ * @returns A DOM array suitable for `write()` or further processing.
7
+ */
8
+ function fromLossless(entries) {
9
+ const result = [];
10
+ for (let i = 0; i < entries.length; i++) result.push(convertEntry(entries[i]));
11
+ return result;
12
+ }
13
+ function convertEntry(entry) {
14
+ if ("$text" in entry) return entry.$text;
15
+ if ("$comment" in entry) return "<!--" + entry.$comment + "-->";
16
+ if ("$attr" in entry) return "";
17
+ const tagName = Object.keys(entry)[0];
18
+ const entryChildren = entry[tagName];
19
+ let attributes = null;
20
+ const children = [];
21
+ for (let i = 0; i < entryChildren.length; i++) {
22
+ const child = entryChildren[i];
23
+ if ("$attr" in child) attributes = child.$attr;
24
+ else children.push(convertEntry(child));
25
+ }
26
+ return {
27
+ tagName,
28
+ attributes,
29
+ children
30
+ };
31
+ }
32
+ //#endregion
33
+ export { fromLossless };
34
+
35
+ //# sourceMappingURL=fromLossless.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fromLossless.mjs","names":[],"sources":["../../src/converters/fromLossless.ts"],"sourcesContent":["/**\n * fromLossless — convert a lossless JSON structure back to a TNode DOM tree.\n *\n * This is the inverse of `lossless()`. Because the lossless format preserves\n * element order, mixed content, attributes, and comments, the round-trip is\n * exact: `fromLossless(lossless(dom))` produces a tree identical to `dom`.\n *\n * Entry types:\n * - `{ tagName: LosslessEntry[] }` → TNode element\n * - `{ $text: \"...\" }` → string child\n * - `{ $attr: { ... } }` → attributes on the enclosing element (first child)\n * - `{ $comment: \"...\" }` → comment string child (`\"<!-- ... -->\"`)\n *\n * @example\n * ```ts\n * import { fromLossless } from \"@eksml/xml/from-lossless\";\n * import { lossless } from \"@eksml/xml/lossless\";\n * import { write } from \"@eksml/xml/writer\";\n *\n * const entries = lossless('<root attr=\"1\"><item>hello</item></root>');\n * const dom = fromLossless(entries);\n * const xml = write(dom); // '<root attr=\"1\"><item>hello</item></root>'\n * ```\n */\n\nimport type { TNode } from '#src/parser.ts';\nimport type { LosslessEntry } from '#src/converters/lossless.ts';\n\n/**\n * Convert a lossless JSON entry array back to a `(TNode | string)[]` DOM tree.\n *\n * @param entries - The lossless entry array (as returned by `lossless()`).\n * @returns A DOM array suitable for `write()` or further processing.\n */\nexport function fromLossless(entries: LosslessEntry[]): (TNode | string)[] {\n const result: (TNode | string)[] = [];\n for (let i = 0; i < entries.length; i++) {\n result.push(convertEntry(entries[i]!));\n }\n return result;\n}\n\nfunction convertEntry(entry: LosslessEntry): TNode | string {\n // $text → plain string\n if ('$text' in entry) {\n return (entry as { $text: string }).$text;\n }\n\n // $comment → reconstruct comment string as the parser emits it\n if ('$comment' in entry) {\n return '<!--' + (entry as { $comment: string }).$comment + '-->';\n }\n\n // $attr should not appear at top level — it's consumed by the element\n // handler below. If we encounter it here, skip it (defensive).\n if ('$attr' in entry) {\n return '';\n }\n\n // Element: single key is the tag name, value is children array\n const keys = Object.keys(entry);\n const tagName = keys[0]!;\n const entryChildren = (entry as { [tagName: string]: LosslessEntry[] })[\n tagName\n ]!;\n\n let attributes: Record<string, string | null> | null = null;\n const children: (TNode | string)[] = [];\n\n for (let i = 0; i < entryChildren.length; i++) {\n const child = entryChildren[i]!;\n if ('$attr' in child) {\n attributes = (child as { $attr: Record<string, string | null> }).$attr;\n } else {\n children.push(convertEntry(child));\n }\n }\n\n return { tagName, attributes, children };\n}\n"],"mappings":";;;;;;;AAkCA,SAAgB,aAAa,SAA8C;CACzE,MAAM,SAA6B,EAAE;AACrC,MAAK,IAAI,IAAI,GAAG,IAAI,QAAQ,QAAQ,IAClC,QAAO,KAAK,aAAa,QAAQ,GAAI,CAAC;AAExC,QAAO;;AAGT,SAAS,aAAa,OAAsC;AAE1D,KAAI,WAAW,MACb,QAAQ,MAA4B;AAItC,KAAI,cAAc,MAChB,QAAO,SAAU,MAA+B,WAAW;AAK7D,KAAI,WAAW,MACb,QAAO;CAKT,MAAM,UADO,OAAO,KAAK,MAAM,CACV;CACrB,MAAM,gBAAiB,MACrB;CAGF,IAAI,aAAmD;CACvD,MAAM,WAA+B,EAAE;AAEvC,MAAK,IAAI,IAAI,GAAG,IAAI,cAAc,QAAQ,KAAK;EAC7C,MAAM,QAAQ,cAAc;AAC5B,MAAI,WAAW,MACb,cAAc,MAAmD;MAEjE,UAAS,KAAK,aAAa,MAAM,CAAC;;AAItC,QAAO;EAAE;EAAS;EAAY;EAAU"}