1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615 |
x18
x18
x247
x18
x18
x247
x247
x247
x247
x247
x247
x18
x18
x28
x28
x18
x28
x28
x18
x28
x28
x18
x28
x28 |
|
// Copyright 2018-2026 the Deno authors. MIT license.
// This module is browser compatible.
/**
* Position information for error reporting.
*/
export interface XmlPosition {
/** Line number (1-indexed). */
readonly line: number;
/** Column number (1-indexed). */
readonly column: number;
/** Byte offset in the input. */
readonly offset: number;
}
/**
* Error thrown when XML parsing fails.
*
* @example Usage
* ```ts
* import { XmlSyntaxError } from "@std/xml/types";
* import { assertInstanceOf } from "@std/assert";
*
* const error = new XmlSyntaxError("Unexpected character", { line: 10, column: 5, offset: 150 });
* assertInstanceOf(error, SyntaxError);
* ```
*/
export class XmlSyntaxError extends SyntaxError {
/**
* The line number where the error occurred (1-indexed).
*
* @example Usage
* ```ts
* import { XmlSyntaxError } from "@std/xml/types";
* import { assertEquals } from "@std/assert";
*
* const error = new XmlSyntaxError("Test", { line: 5, column: 10, offset: 50 });
* assertEquals(error.line, 5);
* ```
*/
readonly line: number;
/**
* The column number where the error occurred (1-indexed).
*
* @example Usage
* ```ts
* import { XmlSyntaxError } from "@std/xml/types";
* import { assertEquals } from "@std/assert";
*
* const error = new XmlSyntaxError("Test", { line: 5, column: 10, offset: 50 });
* assertEquals(error.column, 10);
* ```
*/
readonly column: number;
/**
* The byte offset where the error occurred.
*
* @example Usage
* ```ts
* import { XmlSyntaxError } from "@std/xml/types";
* import { assertEquals } from "@std/assert";
*
* const error = new XmlSyntaxError("Test", { line: 5, column: 10, offset: 50 });
* assertEquals(error.offset, 50);
* ```
*/
readonly offset: number;
/**
* Constructs a new XmlSyntaxError.
*
* @param message The error message describing what went wrong.
* @param position The position in the input where the error occurred.
*/
constructor(message: string, position: XmlPosition) {
super(`${message} at line ${position.line}, column ${position.column}`);
this.name = "XmlSyntaxError";
this.line = position.line;
this.column = position.column;
this.offset = position.offset;
}
}
/**
* A qualified XML name with optional namespace prefix and resolved URI.
*/
export interface XmlName {
/** The original unsplit name (e.g., "ns:item" or "item"). */
readonly raw: string;
/** The local part of the name (after the colon, or the whole name). */
readonly local: string;
/** The namespace prefix (before the colon), if present. */
readonly prefix?: string;
/**
* The resolved namespace URI, if the name has a bound prefix.
*
* For prefixed names (e.g., "ns:item"), this is the URI that the prefix
* is bound to via an `xmlns:ns="..."` declaration.
*
* For unprefixed names, this is undefined (the default namespace is not
* applied to element names in this implementation for simplicity).
*
* @example
* ```ts
* // For <ns:item xmlns:ns="http://example.com">
* // name.uri === "http://example.com"
* ```
*/
readonly uri?: string;
}
/**
* An XML attribute with its qualified name and value.
*/
export interface XmlAttribute {
/** The qualified name of the attribute. */
readonly name: XmlName;
/** The decoded attribute value. */
readonly value: string;
}
// ============================================================================
// Event Types (for streaming parser)
// ============================================================================
/**
* Event emitted when an element start tag is encountered.
*/
export interface XmlStartElementEvent extends XmlPosition {
/** The event type discriminant. */
readonly type: "start_element";
/** The qualified name of the element. */
readonly name: XmlName;
/** The attributes on the element. */
readonly attributes: ReadonlyArray<XmlAttribute>;
/** Whether this is a self-closing tag (`<foo/>`). */
readonly selfClosing: boolean;
}
/**
* Event emitted when an element end tag is encountered.
*/
export interface XmlEndElementEvent extends XmlPosition {
/** The event type discriminant. */
readonly type: "end_element";
/** The qualified name of the element. */
readonly name: XmlName;
}
/**
* Event emitted for text content.
*/
export interface XmlTextEvent extends XmlPosition {
/** The event type discriminant. */
readonly type: "text";
/** The decoded text content. */
readonly text: string;
}
/**
* Event emitted for CDATA sections.
*
* @see {@link https://www.w3.org/TR/xml/#sec-cdata-sect | XML 1.0 §2.7 CDATA Sections}
*/
export interface XmlCDataEvent extends XmlPosition {
/** The event type discriminant. */
readonly type: "cdata";
/** The raw CDATA content (not entity-decoded). */
readonly text: string;
}
/**
* Event emitted for comments.
*
* @see {@link https://www.w3.org/TR/xml/#sec-comments | XML 1.0 §2.5 Comments}
*/
export interface XmlCommentEvent extends XmlPosition {
/** The event type discriminant. */
readonly type: "comment";
/** The comment text (excluding `<!--` and `-->`). */
readonly text: string;
}
/**
* Event emitted for processing instructions.
*
* @see {@link https://www.w3.org/TR/xml/#sec-pi | XML 1.0 §2.6 Processing Instructions}
*/
export interface XmlProcessingInstructionEvent extends XmlPosition {
/** The event type discriminant. */
readonly type: "processing_instruction";
/** The PI target (e.g., "xml-stylesheet"). */
readonly target: string;
/** The PI content after the target. */
readonly content: string;
}
/**
* Event emitted for the XML declaration.
*
* @see {@link https://www.w3.org/TR/xml/#sec-prolog-dtd | XML 1.0 §2.8 Prolog}
*/
export interface XmlDeclarationEvent extends XmlPosition {
/** The event type discriminant. */
readonly type: "declaration";
/** The XML version (always "1.0" for XML 1.0 documents). */
readonly version: string;
/** The declared character encoding, if specified. */
readonly encoding?: string;
/** Whether the document is standalone (§2.9). */
readonly standalone?: "yes" | "no";
}
/**
* Discriminated union of all XML events emitted by the streaming parser.
*/
export type XmlEvent =
| XmlStartElementEvent
| XmlEndElementEvent
| XmlTextEvent
| XmlCDataEvent
| XmlCommentEvent
| XmlProcessingInstructionEvent
| XmlDeclarationEvent;
/**
* Base options shared by parsing functions.
*/
export interface BaseParseOptions {
/**
* If true, text nodes containing only whitespace are not emitted/included.
*
* @default {false}
*/
readonly ignoreWhitespace?: boolean;
/**
* If true, comments are not emitted/included.
*
* @default {false}
*/
readonly ignoreComments?: boolean;
/**
* If true, track line/column positions for events and error messages.
* Disabling improves performance but makes debugging harder.
*/
readonly trackPosition?: boolean;
}
/**
* Options for {@linkcode parseXmlStream}.
*/
export interface ParseStreamOptions extends BaseParseOptions {
/**
* If true, processing instruction events are not emitted.
*
* @default {false}
*/
readonly ignoreProcessingInstructions?: boolean;
/**
* If true, CDATA sections are emitted as regular text events.
*
* @default {false}
*/
readonly coerceCDataToText?: boolean;
}
/**
* Options for {@linkcode parse}.
*/
export interface ParseOptions extends BaseParseOptions {}
/**
* Options for {@linkcode stringify}.
*/
export interface StringifyOptions {
/**
* Indentation string for pretty-printing (e.g., " " or "\t").
* When undefined, output is compact with no extra whitespace.
*
* @default {undefined}
*/
readonly indent?: string;
/**
* If true, include the XML declaration when stringifying a document.
* Only applies when the input is an XmlDocument with a declaration.
*
* @default {true}
*/
readonly declaration?: boolean;
}
// ============================================================================
// Node Types (for DOM-style tree)
// ============================================================================
/**
* A text node in the XML tree.
*/
export interface XmlTextNode {
/** The node type discriminant. */
readonly type: "text";
/** The decoded text content. */
readonly text: string;
}
/**
* A CDATA section node in the XML tree.
*/
export interface XmlCDataNode {
/** The node type discriminant. */
readonly type: "cdata";
/** The raw CDATA content. */
readonly text: string;
}
/**
* A comment node in the XML tree.
*/
export interface XmlCommentNode {
/** The node type discriminant. */
readonly type: "comment";
/** The comment text. */
readonly text: string;
}
/**
* An element node in the XML tree.
*/
export interface XmlElement {
/** The node type discriminant. */
readonly type: "element";
/** The qualified name of the element. */
readonly name: XmlName;
/** Attribute lookup by local name. */
readonly attributes: Readonly<Record<string, string>>;
/** The child nodes of this element. */
readonly children: ReadonlyArray<XmlNode>;
}
/**
* Discriminated union of all node types in an XML tree.
*/
export type XmlNode =
| XmlElement
| XmlTextNode
| XmlCDataNode
| XmlCommentNode;
/**
* A parsed XML document.
*/
export interface XmlDocument {
/** The XML declaration, if present. */
readonly declaration?: XmlDeclarationEvent;
/** The root element of the document. */
readonly root: XmlElement;
}
// ============================================================================
// Callback Interfaces (for zero-allocation streaming)
// ============================================================================
/** Callback for XML declarations. */
export type XmlDeclarationCallback = (
version: string,
encoding: string | undefined,
standalone: "yes" | "no" | undefined,
line: number,
column: number,
offset: number,
) => void;
/** Callback for DOCTYPE declarations. */
export type XmlDoctypeCallback = (
name: string,
publicId: string | undefined,
systemId: string | undefined,
line: number,
column: number,
offset: number,
) => void;
/** Callback for text, CDATA, or comment content with position. */
export type XmlContentCallback = (
content: string,
line: number,
column: number,
offset: number,
) => void;
/** Callback for processing instructions. */
export type XmlProcessingInstructionCallback = (
target: string,
content: string,
line: number,
column: number,
offset: number,
) => void;
/**
* Callbacks for tokenizer output - enables zero-allocation token emission.
*
* Instead of creating token objects, the tokenizer invokes these callbacks
* directly with primitive values.
*/
export interface XmlTokenCallbacks {
/** Called when a start tag opens (e.g., `<element`). */
onStartTagOpen?(
name: string,
line: number,
column: number,
offset: number,
): void;
/** Called for each attribute in a start tag. */
onAttribute?(name: string, value: string): void;
/** Called when a start tag closes (e.g., `>` or `/>`). */
onStartTagClose?(selfClosing: boolean): void;
/** Called when an end tag is encountered (e.g., `</element>`). */
onEndTag?(name: string, line: number, column: number, offset: number): void;
/** Called for text content between tags. */
onText?: XmlContentCallback;
/** Called for CDATA sections. */
onCData?: XmlContentCallback;
/** Called for XML comments. */
onComment?: XmlContentCallback;
/** Called for processing instructions. */
onProcessingInstruction?: XmlProcessingInstructionCallback;
/** Called for XML declarations. */
onDeclaration?: XmlDeclarationCallback;
/** Called for DOCTYPE declarations. */
onDoctype?: XmlDoctypeCallback;
/** Called for internal entity declarations in the DTD. */
onEntityDeclaration?(name: string, value: string): void;
}
/**
* Reusable attribute accessor that avoids allocating XmlAttribute arrays.
*
* Instead of creating an array of attribute objects, attributes are accessed
* by index through this interface. The implementation reuses internal arrays
* across elements.
*/
export interface XmlAttributeIterator {
/** The number of attributes. */
readonly count: number;
/** Get the raw attribute name at the given index. */
getName(index: number): string;
/** Get the decoded attribute value at the given index. */
getValue(index: number): string;
/**
* Get the colon index in the attribute name (-1 if no namespace prefix).
* This allows consumers to parse namespace prefixes without string allocation.
*/
getColonIndex(index: number): number;
/**
* Get the resolved namespace URI for the attribute at the given index.
* Returns undefined if the attribute has no namespace prefix or the prefix
* is not bound (xmlns: attributes always return undefined as they declare
* rather than use namespaces).
*/
getUri(index: number): string | undefined;
}
/**
* Callbacks for event-level output - enables zero-allocation event emission.
*
* The parser invokes these callbacks instead of creating XmlEvent objects.
*/
export interface XmlEventCallbacks {
/** Called for XML declarations. */
onDeclaration?: XmlDeclarationCallback;
/** Called for DOCTYPE declarations. */
onDoctype?: XmlDoctypeCallback;
/**
* Called when an element starts.
* @param colonIndex Index of ':' in name, or -1 if no prefix.
* @param uri The resolved namespace URI if the element has a bound prefix, undefined otherwise.
*/
onStartElement?(
name: string,
colonIndex: number,
uri: string | undefined,
attributes: XmlAttributeIterator,
selfClosing: boolean,
line: number,
column: number,
offset: number,
): void;
/**
* Called when an element ends.
* @param colonIndex Index of ':' in name, or -1 if no prefix.
* @param uri The resolved namespace URI if the element has a bound prefix, undefined otherwise.
*/
onEndElement?(
name: string,
colonIndex: number,
uri: string | undefined,
line: number,
column: number,
offset: number,
): void;
/** Called for text content (entity-decoded). */
onText?: XmlContentCallback;
/** Called for CDATA sections. */
onCData?: XmlContentCallback;
/** Called for comments. */
onComment?: XmlContentCallback;
/** Called for processing instructions. */
onProcessingInstruction?: XmlProcessingInstructionCallback;
}
// ============================================================================
// Type Guards
// ============================================================================
/**
* Type guard to check if a node is an element.
*
* @example Usage
* ```ts
* import { isElement } from "@std/xml/types";
* import { assertEquals } from "@std/assert";
*
* const node = { type: "element" as const, name: { raw: "item", local: "item" }, attributes: {}, children: [] };
* assertEquals(isElement(node), true);
* ```
*
* @param node The node to check.
* @returns `true` if the node is an element, `false` otherwise.
*/
export function isElement(node: XmlNode): node is XmlElement {
return node.type === "element";
}
/**
* Type guard to check if a node is a text node.
*
* @example Usage
* ```ts
* import { isText } from "@std/xml/types";
* import { assertEquals } from "@std/assert";
*
* const node = { type: "text" as const, text: "Hello" };
* assertEquals(isText(node), true);
* ```
*
* @param node The node to check.
* @returns `true` if the node is a text node, `false` otherwise.
*/
export function isText(node: XmlNode): node is XmlTextNode {
return node.type === "text";
}
/**
* Type guard to check if a node is a CDATA node.
*
* @example Usage
* ```ts
* import { isCData } from "@std/xml/types";
* import { assertEquals } from "@std/assert";
*
* const node = { type: "cdata" as const, text: "<script>" };
* assertEquals(isCData(node), true);
* ```
*
* @param node The node to check.
* @returns `true` if the node is a CDATA node, `false` otherwise.
*/
export function isCData(node: XmlNode): node is XmlCDataNode {
return node.type === "cdata";
}
/**
* Type guard to check if a node is a comment.
*
* @example Usage
* ```ts
* import { isComment } from "@std/xml/types";
* import { assertEquals } from "@std/assert";
*
* const node = { type: "comment" as const, text: "A comment" };
* assertEquals(isComment(node), true);
* ```
*
* @param node The node to check.
* @returns `true` if the node is a comment, `false` otherwise.
*/
export function isComment(node: XmlNode): node is XmlCommentNode {
return node.type === "comment";
}
|