en16931-parser 0.0.0-stage → 1.0.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.
@@ -0,0 +1,848 @@
1
+ /**
2
+ * xml-formatter-options.ts — Pure TypeScript XML 1.0 Lexer, Validator,
3
+ * Pretty-Printer, Minifier, Tree Builder, Summary Analyzer, and XPath Query
4
+ * Evaluator for `/xml-formatter` (`/fr/formateur-validateur-xml`).
5
+ *
6
+ * Reuses `src/core/xml-entities.ts` (strict DRY) and runs 100% in Node/Vitest
7
+ * with zero DOM or network dependencies.
8
+ */
9
+ import { stepDelimiterDepth } from './collections.js';
10
+ import { decodeXmlEntities, encodeXmlEntities } from './xml-entities.js';
11
+ /** Maximum XML document size processed in browser memory (10 MB). */
12
+ export const XML_MAX_BYTES = 10 * 1024 * 1024;
13
+ export const DEFAULT_SAMPLE_XPATH = "//item[@currency='EUR']/price";
14
+ export const SAMPLE_XML_DOCUMENT = `<?xml version="1.0" encoding="UTF-8"?>
15
+ <!-- B2B Purchase Order & Electronic Invoice Manifest -->
16
+ <inv:orderCatalog xmlns:inv="urn:sunasty:invoice:1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4" region="EU-WEST">
17
+ <inv:header id="ORD-2026-0842" priority="high" status="confirmed" channel="edi">
18
+ <inv:buyer vat="FR84501928374">Atelier Numerique SAS</inv:buyer>
19
+ <inv:issuedAt>2026-11-07T09:30:00Z</inv:issuedAt>
20
+ <inv:notes><![CDATA[Deliver to Gate B <North Dock> & require signature on arrival.]]></inv:notes>
21
+ </inv:header>
22
+ <inv:items>
23
+ <item id="SKU-101" currency="EUR" taxRate="0.20" warehouse="PAR-01">
24
+ <name>Workstation NVMe Array 4TB</name>
25
+ <quantity>2</quantity>
26
+ <price>489.00</price>
27
+ </item>
28
+ <item id="SKU-204" currency="EUR" taxRate="0.20" warehouse="PAR-01">
29
+ <name>Optical Fiber Patch 10GbE &amp; Transceiver</name>
30
+ <quantity>6</quantity>
31
+ <price>74.50</price>
32
+ </item>
33
+ <item id="SKU-309" currency="USD" taxRate="0.00" warehouse="NYC-03">
34
+ <name>Hardware Security Key FIPS-140</name>
35
+ <quantity>10</quantity>
36
+ <price>55.00</price>
37
+ </item>
38
+ </inv:items>
39
+ </inv:orderCatalog>`;
40
+ const VALID_NAME_RE = /^[\p{L}_:][\p{L}\p{N}_.:-]*$/u;
41
+ const VALID_ENTITY_RE = /^(?:amp|lt|gt|quot|apos|#\d+|#x[0-9a-fA-F]+);/;
42
+ const VALID_MODES = new Set(['format', 'minify', 'validate', 'tree', 'xpath']);
43
+ const VALID_INDENTS = new Set(['2', '4', 'tab']);
44
+ const DEFAULT_FORMAT_OPTIONS = {
45
+ indent: '2',
46
+ sortAttributes: false,
47
+ stripComments: false,
48
+ wrapAttributes: false,
49
+ preserveDeclaration: true,
50
+ };
51
+ /**
52
+ * Converts a 0-based character offset in `raw` into 1-based `{ line, column, snippet }`.
53
+ */
54
+ export function computeLineColumnSnippet(raw, offset) {
55
+ const clamped = Math.max(0, Math.min(raw.length, offset));
56
+ const before = raw.slice(0, clamped);
57
+ const lines = before.split('\n');
58
+ const line = lines.length;
59
+ const lastLine = lines[lines.length - 1];
60
+ const column = lastLine.length + 1;
61
+ const allLines = raw.split(/\r?\n/);
62
+ const snippet = allLines[line - 1].trim().slice(0, 120);
63
+ return { line, column, snippet };
64
+ }
65
+ function makeError(raw, offset, code, reason) {
66
+ const pos = computeLineColumnSnippet(raw, offset);
67
+ return {
68
+ code,
69
+ line: pos.line,
70
+ column: pos.column,
71
+ snippet: pos.snippet,
72
+ reason,
73
+ };
74
+ }
75
+ /**
76
+ * Finds the first unescaped `&` in an XML text node or attribute value.
77
+ * Returns the relative character offset or `-1` if all `&` belong to valid entities.
78
+ */
79
+ export function findUnescapedAmpersandOffset(text) {
80
+ for (let i = 0; i < text.length; i++) {
81
+ if (text[i] === '&' && !VALID_ENTITY_RE.test(text.slice(i + 1))) {
82
+ return i;
83
+ }
84
+ }
85
+ return -1;
86
+ }
87
+ function skipWhitespace(str, idx) {
88
+ let i = idx;
89
+ while (i < str.length && /\s/.test(str[i]))
90
+ i++;
91
+ return i;
92
+ }
93
+ function readAttrName(body, start) {
94
+ let i = start;
95
+ while (i < body.length && !/[\s=/>]/.test(body[i]))
96
+ i++;
97
+ return { name: body.slice(start, i), next: i };
98
+ }
99
+ function readQuotedAttrValue(raw, body, quoteIdx, name, bodyStartOffset) {
100
+ const quote = body[quoteIdx];
101
+ if (quote !== '"' && quote !== "'") {
102
+ return {
103
+ nextCursor: body.length,
104
+ error: makeError(raw, bodyStartOffset + quoteIdx, 'UNQUOTED_ATTRIBUTE', `Attribute "${name}" value must be enclosed in quotes.`),
105
+ };
106
+ }
107
+ const valStart = quoteIdx + 1;
108
+ const closeQuote = body.indexOf(quote, valStart);
109
+ const rawVal = body.slice(valStart, closeQuote);
110
+ const badAmp = findUnescapedAmpersandOffset(rawVal);
111
+ if (badAmp !== -1) {
112
+ return {
113
+ nextCursor: body.length,
114
+ error: makeError(raw, bodyStartOffset + valStart + badAmp, 'UNESCAPED_AMPERSAND', `Unescaped '&' inside attribute "${name}" (use &amp;).`),
115
+ };
116
+ }
117
+ return {
118
+ attr: { name, value: decodeXmlEntities(rawVal), quote },
119
+ nextCursor: closeQuote + 1,
120
+ };
121
+ }
122
+ function parseSingleAttribute(raw, body, cursor, bodyStartOffset) {
123
+ const nameStart = skipWhitespace(body, cursor);
124
+ const { name, next } = readAttrName(body, nameStart);
125
+ if (!VALID_NAME_RE.test(name)) {
126
+ return {
127
+ nextCursor: body.length,
128
+ error: makeError(raw, bodyStartOffset + nameStart, 'INVALID_TAG_NAME', `Invalid attribute name "${name}".`),
129
+ };
130
+ }
131
+ const eqIdx = skipWhitespace(body, next);
132
+ if (body[eqIdx] !== '=') {
133
+ return {
134
+ nextCursor: body.length,
135
+ error: makeError(raw, bodyStartOffset + nameStart, 'UNQUOTED_ATTRIBUTE', `Attribute "${name}" is missing '="value"'.`),
136
+ };
137
+ }
138
+ const quoteIdx = skipWhitespace(body, eqIdx + 1);
139
+ return readQuotedAttrValue(raw, body, quoteIdx, name, bodyStartOffset);
140
+ }
141
+ function parseAttributesList(raw, attrRegion, regionOffset) {
142
+ const attributes = [];
143
+ const seen = new Set();
144
+ let cursor = skipWhitespace(attrRegion, 0);
145
+ while (cursor < attrRegion.length) {
146
+ const step = parseSingleAttribute(raw, attrRegion, cursor, regionOffset);
147
+ if (step.error)
148
+ return { attributes, error: step.error };
149
+ const attr = step.attr;
150
+ if (seen.has(attr.name)) {
151
+ return {
152
+ attributes,
153
+ error: makeError(raw, regionOffset + cursor, 'DUPLICATE_ATTRIBUTE', `Duplicate attribute "${attr.name}".`),
154
+ };
155
+ }
156
+ seen.add(attr.name);
157
+ attributes.push(attr);
158
+ cursor = skipWhitespace(attrRegion, step.nextCursor);
159
+ }
160
+ return { attributes };
161
+ }
162
+ function isQuoteChar(ch) {
163
+ return ch === '"' || ch === "'";
164
+ }
165
+ function advanceQuoteState(ch, idx, quote, quoteOffset) {
166
+ if (quote) {
167
+ return { quote: ch === quote ? null : quote, quoteOffset };
168
+ }
169
+ if (isQuoteChar(ch)) {
170
+ return { quote: ch, quoteOffset: idx };
171
+ }
172
+ return { quote: null, quoteOffset };
173
+ }
174
+ function isUnquotedBracket(ch, quote) {
175
+ return quote === null && (ch === '>' || ch === '<');
176
+ }
177
+ function scanTagBoundary(raw, start) {
178
+ let quote = null;
179
+ let quoteOffset = -1;
180
+ for (let i = start + 1; i < raw.length; i++) {
181
+ const ch = raw[i];
182
+ if (isUnquotedBracket(ch, quote)) {
183
+ return { endBracket: ch === '>' ? i : -1, unclosedQuoteOffset: null };
184
+ }
185
+ const nextState = advanceQuoteState(ch, i, quote, quoteOffset);
186
+ quote = nextState.quote;
187
+ quoteOffset = nextState.quoteOffset;
188
+ }
189
+ return {
190
+ endBracket: -1,
191
+ unclosedQuoteOffset: quote ? quoteOffset : null,
192
+ };
193
+ }
194
+ function parseCloseTagContent(raw, inner, start, endBracket) {
195
+ const closeName = inner.slice(1).trim();
196
+ if (!VALID_NAME_RE.test(closeName)) {
197
+ return {
198
+ nextIndex: raw.length,
199
+ error: makeError(raw, start, 'INVALID_TAG_NAME', `Invalid closing tag name "</${closeName}>".`),
200
+ };
201
+ }
202
+ return {
203
+ token: { type: 'closeTag', name: closeName, offset: start },
204
+ nextIndex: endBracket + 1,
205
+ };
206
+ }
207
+ function parseOpenTagContent(raw, inner, start, endBracket) {
208
+ const selfClosing = inner.endsWith('/');
209
+ const core = selfClosing ? inner.slice(0, -1) : inner;
210
+ const trimmedCore = core.trimStart();
211
+ const leadSpaces = core.length - trimmedCore.length;
212
+ const nameMatch = /^[^\s/>]+/.exec(trimmedCore);
213
+ const tagName = nameMatch[0];
214
+ if (!VALID_NAME_RE.test(tagName)) {
215
+ return {
216
+ nextIndex: raw.length,
217
+ error: makeError(raw, start + 1 + leadSpaces, 'INVALID_TAG_NAME', `Invalid element tag name "<${tagName}>".`),
218
+ };
219
+ }
220
+ const attrRegionOffset = start + 1 + leadSpaces + tagName.length;
221
+ const attrRegion = core.slice(leadSpaces + tagName.length);
222
+ const parsedAttrs = parseAttributesList(raw, attrRegion, attrRegionOffset);
223
+ if (parsedAttrs.error) {
224
+ return { nextIndex: raw.length, error: parsedAttrs.error };
225
+ }
226
+ return {
227
+ token: {
228
+ type: 'openTag',
229
+ name: tagName,
230
+ attributes: parsedAttrs.attributes,
231
+ selfClosing,
232
+ offset: start,
233
+ },
234
+ nextIndex: endBracket + 1,
235
+ };
236
+ }
237
+ function parseOpenOrCloseTagToken(raw, start) {
238
+ const scan = scanTagBoundary(raw, start);
239
+ if (scan.unclosedQuoteOffset !== null) {
240
+ return {
241
+ nextIndex: raw.length,
242
+ error: makeError(raw, scan.unclosedQuoteOffset, 'UNCLOSED_ATTRIBUTE', 'Unclosed attribute quote inside tag.'),
243
+ };
244
+ }
245
+ if (scan.endBracket === -1) {
246
+ return {
247
+ nextIndex: raw.length,
248
+ error: makeError(raw, start, 'UNCLOSED_TAG', 'Unclosed tag bracket "<" (missing ">").'),
249
+ };
250
+ }
251
+ const inner = raw.slice(start + 1, scan.endBracket);
252
+ if (inner.startsWith('/')) {
253
+ return parseCloseTagContent(raw, inner, start, scan.endBracket);
254
+ }
255
+ return parseOpenTagContent(raw, inner, start, scan.endBracket);
256
+ }
257
+ const DELIMITED_SPECS = [
258
+ { prefix: '<!--', closeSeq: '-->', errorCode: 'UNCLOSED_COMMENT', errorMsg: 'Unclosed XML comment (missing "-->").' },
259
+ { prefix: '<![CDATA[', closeSeq: ']]>', errorCode: 'UNCLOSED_CDATA', errorMsg: 'Unclosed CDATA section (missing "]]>").' },
260
+ { prefix: '<!DOCTYPE', closeSeq: '>', errorCode: 'UNCLOSED_DOCTYPE', errorMsg: 'Unclosed DOCTYPE declaration.' },
261
+ { prefix: '<?', closeSeq: '?>', errorCode: 'UNCLOSED_PI', errorMsg: 'Unclosed processing instruction (missing "?>").' },
262
+ ];
263
+ function buildSpecialToken(prefix, slice, offset) {
264
+ if (prefix === '<!--')
265
+ return { type: 'comment', raw: slice, offset };
266
+ if (prefix === '<![CDATA[') {
267
+ return { type: 'cdata', raw: slice, content: slice.slice(9, -3), offset };
268
+ }
269
+ if (prefix === '<!DOCTYPE')
270
+ return { type: 'doctype', raw: slice, offset };
271
+ const isDecl = /^<\?xml(?:\s|\?)/i.test(slice);
272
+ return { type: isDecl ? 'declaration' : 'pi', raw: slice, offset };
273
+ }
274
+ function parseSpecialMarkupToken(raw, start) {
275
+ const spec = DELIMITED_SPECS.find((s) => raw.startsWith(s.prefix, start));
276
+ if (!spec)
277
+ return null;
278
+ const closeIdx = raw.indexOf(spec.closeSeq, start + spec.prefix.length);
279
+ if (closeIdx === -1) {
280
+ return {
281
+ nextIndex: raw.length,
282
+ error: makeError(raw, start, spec.errorCode, spec.errorMsg),
283
+ };
284
+ }
285
+ const end = closeIdx + spec.closeSeq.length;
286
+ return {
287
+ token: buildSpecialToken(spec.prefix, raw.slice(start, end), start),
288
+ nextIndex: end,
289
+ };
290
+ }
291
+ function makeTextTokenOrError(raw, start, end) {
292
+ const textChunk = raw.slice(start, end);
293
+ const badAmp = findUnescapedAmpersandOffset(textChunk);
294
+ if (badAmp !== -1) {
295
+ return {
296
+ error: makeError(raw, start + badAmp, 'UNESCAPED_AMPERSAND', "Unescaped '&' in text node (use &amp;)."),
297
+ };
298
+ }
299
+ return { token: { type: 'text', raw: textChunk, offset: start } };
300
+ }
301
+ function nextLexTokenStep(raw, i) {
302
+ const ltIdx = raw.indexOf('<', i);
303
+ if (ltIdx === -1) {
304
+ const step = makeTextTokenOrError(raw, i, raw.length);
305
+ return { token: step.token, nextIndex: raw.length, error: step.error };
306
+ }
307
+ if (ltIdx > i) {
308
+ const step = makeTextTokenOrError(raw, i, ltIdx);
309
+ return { token: step.token, nextIndex: ltIdx, error: step.error };
310
+ }
311
+ return parseSpecialMarkupToken(raw, i) ?? parseOpenOrCloseTagToken(raw, i);
312
+ }
313
+ /**
314
+ * Tokenizes an XML 1.0 document into a flat stream of `XmlToken` items,
315
+ * returning the first lexical error with exact `line` and `column` if malformed.
316
+ */
317
+ export function tokenizeXml(raw) {
318
+ const tokens = [];
319
+ if (!raw.trim()) {
320
+ return { tokens, error: makeError(raw, 0, 'EMPTY_DOCUMENT', 'XML document is empty.') };
321
+ }
322
+ let i = 0;
323
+ while (i < raw.length) {
324
+ const step = nextLexTokenStep(raw, i);
325
+ if (step.error)
326
+ return { tokens, error: step.error };
327
+ tokens.push(step.token);
328
+ i = step.nextIndex;
329
+ }
330
+ return { tokens };
331
+ }
332
+ function createMutableFrame(id, tag, xpath, depth, offset, attributes) {
333
+ return {
334
+ id,
335
+ tag,
336
+ xpath,
337
+ depth,
338
+ offset,
339
+ attributes,
340
+ textParts: [],
341
+ cdata: [],
342
+ children: [],
343
+ childTagCounts: new Map(),
344
+ };
345
+ }
346
+ function freezeFrame(frame) {
347
+ return {
348
+ id: frame.id,
349
+ tag: frame.tag,
350
+ xpath: frame.xpath,
351
+ depth: frame.depth,
352
+ attributes: frame.attributes,
353
+ text: frame.textParts.join(' ').trim(),
354
+ cdata: frame.cdata,
355
+ children: frame.children,
356
+ };
357
+ }
358
+ function collectNamespaces(attrs, nsMap) {
359
+ for (const attr of attrs) {
360
+ if (attr.name === 'xmlns') {
361
+ nsMap.set('(default)', attr.value);
362
+ }
363
+ else if (attr.name.startsWith('xmlns:')) {
364
+ nsMap.set(attr.name.slice(6), attr.value);
365
+ }
366
+ }
367
+ }
368
+ function buildChildXPath(parent, tagName) {
369
+ if (!parent)
370
+ return `/${tagName}`;
371
+ const nextIdx = (parent.childTagCounts.get(tagName) ?? 0) + 1;
372
+ parent.childTagCounts.set(tagName, nextIdx);
373
+ return `${parent.xpath}/${tagName}[${nextIdx}]`;
374
+ }
375
+ function attachCompletedNode(parent, frozen, state) {
376
+ if (parent)
377
+ parent.children.push(frozen);
378
+ else
379
+ state.rootNode = frozen;
380
+ }
381
+ function handleOpenTagInTree(raw, tok, state) {
382
+ if (state.rootNode !== null && state.stack.length === 0) {
383
+ return makeError(raw, tok.offset, 'MULTIPLE_ROOT_ELEMENTS', `Multiple root elements detected ("<${tok.name}>" after "<${state.rootNode.tag}>").`);
384
+ }
385
+ state.nodeSeq += 1;
386
+ state.elementCount += 1;
387
+ state.attributeCount += tok.attributes.length;
388
+ collectNamespaces(tok.attributes, state.nsMap);
389
+ const depth = state.stack.length + 1;
390
+ state.maxDepth = Math.max(state.maxDepth, depth);
391
+ const parent = state.stack[state.stack.length - 1];
392
+ const xpath = buildChildXPath(parent, tok.name);
393
+ const frame = createMutableFrame(`node-${state.nodeSeq}`, tok.name, xpath, depth, tok.offset, tok.attributes);
394
+ if (tok.selfClosing) {
395
+ attachCompletedNode(parent, freezeFrame(frame), state);
396
+ }
397
+ else {
398
+ state.stack.push(frame);
399
+ }
400
+ return null;
401
+ }
402
+ function handleCloseTagInTree(raw, tok, state) {
403
+ const top = state.stack[state.stack.length - 1];
404
+ if (!top) {
405
+ return makeError(raw, tok.offset, 'UNEXPECTED_CLOSING_TAG', `Unexpected closing tag "</${tok.name}>" with no matching opening tag.`);
406
+ }
407
+ if (top.tag !== tok.name) {
408
+ return makeError(raw, tok.offset, 'MISMATCHED_CLOSING_TAG', `Mismatched closing tag "</${tok.name}>": expected "</${top.tag}>".`);
409
+ }
410
+ state.stack.pop();
411
+ attachCompletedNode(state.stack[state.stack.length - 1], freezeFrame(top), state);
412
+ return null;
413
+ }
414
+ function appendTextToFrame(rawText, top, state) {
415
+ const trimmed = decodeXmlEntities(rawText.trim());
416
+ if (trimmed) {
417
+ top.textParts.push(trimmed);
418
+ state.textNodeCount += 1;
419
+ }
420
+ }
421
+ function applyNonElementTokenToTree(tok, state) {
422
+ if (tok.type === 'comment') {
423
+ state.commentCount += 1;
424
+ return;
425
+ }
426
+ const top = state.stack[state.stack.length - 1];
427
+ if (!top)
428
+ return;
429
+ if (tok.type === 'cdata') {
430
+ state.cdataCount += 1;
431
+ top.cdata.push(tok.content);
432
+ }
433
+ else {
434
+ appendTextToFrame(tok.raw, top, state);
435
+ }
436
+ }
437
+ function dispatchTreeToken(raw, tok, state) {
438
+ if (tok.type === 'openTag')
439
+ return handleOpenTagInTree(raw, tok, state);
440
+ if (tok.type === 'closeTag')
441
+ return handleCloseTagInTree(raw, tok, state);
442
+ applyNonElementTokenToTree(tok, state);
443
+ return null;
444
+ }
445
+ /**
446
+ * Validates XML 1.0 well-formedness, builds the `XmlTreeNode` hierarchy, and
447
+ * computes `XmlTreeSummary` statistics.
448
+ */
449
+ export function validateXml(raw) {
450
+ const lexed = tokenizeXml(raw);
451
+ if (lexed.error)
452
+ return { valid: false, error: lexed.error };
453
+ const state = {
454
+ stack: [],
455
+ rootNode: null,
456
+ nodeSeq: 0,
457
+ maxDepth: 0,
458
+ elementCount: 0,
459
+ attributeCount: 0,
460
+ textNodeCount: 0,
461
+ commentCount: 0,
462
+ cdataCount: 0,
463
+ nsMap: new Map(),
464
+ };
465
+ for (const tok of lexed.tokens) {
466
+ const err = dispatchTreeToken(raw, tok, state);
467
+ if (err)
468
+ return { valid: false, error: err };
469
+ }
470
+ if (state.stack.length > 0) {
471
+ const unclosed = state.stack[state.stack.length - 1];
472
+ return {
473
+ valid: false,
474
+ error: makeError(raw, unclosed.offset, 'UNCLOSED_ELEMENT', `Unclosed element "<${unclosed.tag}>" at end of document.`),
475
+ };
476
+ }
477
+ if (!state.rootNode) {
478
+ return {
479
+ valid: false,
480
+ error: makeError(raw, 0, 'NO_ROOT_ELEMENT', 'XML document contains no root element.'),
481
+ };
482
+ }
483
+ return {
484
+ valid: true,
485
+ rootTag: state.rootNode.tag,
486
+ root: state.rootNode,
487
+ summary: {
488
+ maxDepth: state.maxDepth,
489
+ elementCount: state.elementCount,
490
+ attributeCount: state.attributeCount,
491
+ textNodeCount: state.textNodeCount,
492
+ commentCount: state.commentCount,
493
+ cdataCount: state.cdataCount,
494
+ namespaces: Array.from(state.nsMap.entries()).map(([prefix, uri]) => ({ prefix, uri })),
495
+ },
496
+ };
497
+ }
498
+ /**
499
+ * Builds the `XmlTreeNode` hierarchy and summary for a valid XML document.
500
+ */
501
+ export function buildXmlTree(raw) {
502
+ const res = validateXml(raw);
503
+ if (!res.valid)
504
+ return { ok: false, error: res.error };
505
+ return { ok: true, root: res.root, summary: res.summary };
506
+ }
507
+ /**
508
+ * Computes structural summary metrics (`maxDepth`, `elementCount`, `attributeCount`,
509
+ * `textNodeCount`, `commentCount`, `cdataCount`, `namespaces`) for a valid XML document,
510
+ * or returns `null` if the XML is malformed.
511
+ */
512
+ export function computeXmlSummary(raw) {
513
+ const res = validateXml(raw);
514
+ return res.valid ? res.summary : null;
515
+ }
516
+ const XML_INDENT_UNITS = {
517
+ tab: '\t',
518
+ '4': ' ',
519
+ '2': ' ',
520
+ };
521
+ function resolveIndentUnit(indent) {
522
+ return XML_INDENT_UNITS[indent];
523
+ }
524
+ function serializeAttributes(attrs, sortAttributes, wrapAttributes, indentPrefix, indentUnit) {
525
+ if (attrs.length === 0)
526
+ return '';
527
+ const list = sortAttributes
528
+ ? [...attrs].sort((a, b) => a.name.localeCompare(b.name))
529
+ : attrs;
530
+ const formatted = list.map((a) => `${a.name}="${encodeXmlEntities(a.value)}"`);
531
+ if (wrapAttributes && formatted.length > 3) {
532
+ const sep = `\n${indentPrefix}${indentUnit}`;
533
+ return sep + formatted.join(sep);
534
+ }
535
+ return ' ' + formatted.join(' ');
536
+ }
537
+ function isSingleLineTextToken(tok) {
538
+ if (!tok || tok.type !== 'text')
539
+ return false;
540
+ return tok.raw.trim().length > 0 && !tok.raw.includes('\n');
541
+ }
542
+ function isInlineTextElement(tokens, idx) {
543
+ const close = tokens[idx + 2];
544
+ if (close?.type !== 'closeTag')
545
+ return false;
546
+ return isSingleLineTextToken(tokens[idx + 1]);
547
+ }
548
+ function renderOpenTagFormatted(tok, i, depth, ctx, lines) {
549
+ const pad = ctx.unit.repeat(depth);
550
+ const attrStr = serializeAttributes(tok.attributes, ctx.opts.sortAttributes, ctx.opts.wrapAttributes, pad, ctx.unit);
551
+ if (tok.selfClosing) {
552
+ lines.push(`${pad}<${tok.name}${attrStr}/>`);
553
+ return { nextIndex: i + 1, nextDepth: depth };
554
+ }
555
+ if (isInlineTextElement(ctx.tokens, i)) {
556
+ const textTok = ctx.tokens[i + 1];
557
+ lines.push(`${pad}<${tok.name}${attrStr}>${textTok.raw.trim()}</${tok.name}>`);
558
+ return { nextIndex: i + 3, nextDepth: depth };
559
+ }
560
+ lines.push(`${pad}<${tok.name}${attrStr}>`);
561
+ return { nextIndex: i + 1, nextDepth: depth + 1 };
562
+ }
563
+ function formatLeafTokenLine(tok, pad, opts) {
564
+ if (tok.type === 'declaration') {
565
+ return opts.preserveDeclaration ? tok.raw.trim() : null;
566
+ }
567
+ if (tok.type === 'comment') {
568
+ return opts.stripComments ? null : `${pad}${tok.raw.trim()}`;
569
+ }
570
+ const trimmed = tok.raw.trim();
571
+ return trimmed ? `${pad}${trimmed}` : null;
572
+ }
573
+ function renderNonOpenTagFormatted(tok, i, depth, ctx, lines) {
574
+ if (tok.type === 'closeTag') {
575
+ const nextDepth = Math.max(0, depth - 1);
576
+ lines.push(`${ctx.unit.repeat(nextDepth)}</${tok.name}>`);
577
+ return { nextIndex: i + 1, nextDepth };
578
+ }
579
+ const line = formatLeafTokenLine(tok, ctx.unit.repeat(depth), ctx.opts);
580
+ if (line !== null)
581
+ lines.push(line);
582
+ return { nextIndex: i + 1, nextDepth: depth };
583
+ }
584
+ /**
585
+ * Pretty-prints an XML document with configurable indentation, attribute sorting,
586
+ * comment stripping, attribute line-wrapping, and declaration preservation.
587
+ */
588
+ export function formatXml(raw, options) {
589
+ const validation = validateXml(raw);
590
+ if (!validation.valid)
591
+ return { ok: false, error: validation.error };
592
+ const resolvedOpts = { ...DEFAULT_FORMAT_OPTIONS, ...options };
593
+ const { tokens } = tokenizeXml(raw);
594
+ const ctx = {
595
+ tokens,
596
+ unit: resolveIndentUnit(resolvedOpts.indent),
597
+ opts: resolvedOpts,
598
+ };
599
+ const lines = [];
600
+ let depth = 0;
601
+ let i = 0;
602
+ while (i < tokens.length) {
603
+ const tok = tokens[i];
604
+ const step = tok.type === 'openTag'
605
+ ? renderOpenTagFormatted(tok, i, depth, ctx, lines)
606
+ : renderNonOpenTagFormatted(tok, i, depth, ctx, lines);
607
+ i = step.nextIndex;
608
+ depth = step.nextDepth;
609
+ }
610
+ return {
611
+ ok: true,
612
+ output: lines.join('\n'),
613
+ summary: validation.summary,
614
+ };
615
+ }
616
+ function renderMinifiedOpenTag(tok, opts) {
617
+ const attrStr = serializeAttributes(tok.attributes, opts.sortAttributes, false, '', '');
618
+ return tok.selfClosing ? `<${tok.name}${attrStr}/>` : `<${tok.name}${attrStr}>`;
619
+ }
620
+ function renderMinifiedToken(tok, opts) {
621
+ if (tok.type === 'openTag')
622
+ return renderMinifiedOpenTag(tok, opts);
623
+ if (tok.type === 'closeTag')
624
+ return `</${tok.name}>`;
625
+ return formatLeafTokenLine(tok, '', opts) ?? '';
626
+ }
627
+ /**
628
+ * Minifies an XML document onto a single compact line by removing insignificant
629
+ * inter-tag whitespace (and optionally stripping comments).
630
+ */
631
+ export function minifyXml(raw, options) {
632
+ const validation = validateXml(raw);
633
+ if (!validation.valid)
634
+ return { ok: false, error: validation.error };
635
+ const resolvedOpts = { ...DEFAULT_FORMAT_OPTIONS, ...options };
636
+ const { tokens } = tokenizeXml(raw);
637
+ const chunks = tokens
638
+ .map((tok) => renderMinifiedToken(tok, resolvedOpts))
639
+ .filter((s) => s.length > 0);
640
+ return {
641
+ ok: true,
642
+ output: chunks.join(''),
643
+ summary: validation.summary,
644
+ };
645
+ }
646
+ function localTagName(tag) {
647
+ const colon = tag.indexOf(':');
648
+ return colon === -1 ? tag : tag.slice(colon + 1);
649
+ }
650
+ function matchesTagName(nodeTag, stepTag) {
651
+ if (stepTag === '*' || nodeTag === stepTag)
652
+ return true;
653
+ return localTagName(nodeTag) === stepTag;
654
+ }
655
+ function collectDescendantsAndSelf(node) {
656
+ const out = [node];
657
+ for (const child of node.children) {
658
+ out.push(...collectDescendantsAndSelf(child));
659
+ }
660
+ return out;
661
+ }
662
+ function evaluateChildNumericComparison(node, childTag, op, rhs) {
663
+ const child = node.children.find((c) => matchesTagName(c.tag, childTag));
664
+ if (!child)
665
+ return false;
666
+ const lhs = Number(child.text);
667
+ if (op === '>')
668
+ return lhs > rhs;
669
+ if (op === '<')
670
+ return lhs < rhs;
671
+ return lhs === rhs;
672
+ }
673
+ function matchesPredicate(node, pred, positionOneBased) {
674
+ const trimmed = pred.trim();
675
+ if (/^\d+$/.test(trimmed)) {
676
+ return positionOneBased === Number(trimmed);
677
+ }
678
+ const attrEq = /^@([\p{L}\p{N}_.:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')$/u.exec(trimmed);
679
+ if (attrEq) {
680
+ const expected = attrEq[2] ?? attrEq[3];
681
+ return node.attributes.some((a) => a.name === attrEq[1] && a.value === expected);
682
+ }
683
+ const attrExists = /^@([\p{L}\p{N}_.:-]+)$/u.exec(trimmed);
684
+ if (attrExists) {
685
+ return node.attributes.some((a) => a.name === attrExists[1]);
686
+ }
687
+ const childCmp = /^([\p{L}\p{N}_.:-]+)\s*(>|<|=)\s*([0-9.]+)$/u.exec(trimmed);
688
+ if (childCmp) {
689
+ return evaluateChildNumericComparison(node, childCmp[1], childCmp[2], Number(childCmp[3]));
690
+ }
691
+ return false;
692
+ }
693
+ function parseStepSegment(rawStep) {
694
+ const bracketIdx = rawStep.indexOf('[');
695
+ if (bracketIdx === -1 || !rawStep.endsWith(']')) {
696
+ return { tag: rawStep, predicate: null };
697
+ }
698
+ return {
699
+ tag: rawStep.slice(0, bracketIdx),
700
+ predicate: rawStep.slice(bracketIdx + 1, -1),
701
+ };
702
+ }
703
+ function nextQuoteState(ch, quote) {
704
+ if (quote)
705
+ return ch === quote ? null : quote;
706
+ return ch === '"' || ch === "'" ? ch : null;
707
+ }
708
+ function splitXPathSteps(body) {
709
+ const steps = [];
710
+ let depth = 0;
711
+ let quote = null;
712
+ let start = 0;
713
+ for (let i = 0; i < body.length; i++) {
714
+ const ch = body[i];
715
+ const wasQuoted = quote !== null;
716
+ quote = nextQuoteState(ch, quote);
717
+ if (wasQuoted || quote !== null)
718
+ continue;
719
+ depth = stepDelimiterDepth(depth, ch, '[', ']');
720
+ if (ch === '/' && depth === 0) {
721
+ if (i > start)
722
+ steps.push(body.slice(start, i));
723
+ start = i + 1;
724
+ }
725
+ }
726
+ if (start < body.length)
727
+ steps.push(body.slice(start));
728
+ return steps;
729
+ }
730
+ function applySingleXPathStep(current, rawStep, useCurrentDirectly) {
731
+ const { tag, predicate } = parseStepSegment(rawStep);
732
+ const candidates = useCurrentDirectly ? current : current.flatMap((n) => n.children);
733
+ const tagMatched = candidates.filter((n) => matchesTagName(n.tag, tag));
734
+ if (!predicate)
735
+ return tagMatched;
736
+ return tagMatched.filter((n, idx) => matchesPredicate(n, predicate, idx + 1));
737
+ }
738
+ function evaluatePathNodes(root, pathExpr) {
739
+ const trimmed = pathExpr.trim();
740
+ const isDescendantStart = trimmed.startsWith('//');
741
+ const body = isDescendantStart ? trimmed.slice(2) : trimmed.replace(/^\/+/, '');
742
+ const rawSteps = splitXPathSteps(body);
743
+ if (rawSteps.length === 0)
744
+ return [root];
745
+ let current = isDescendantStart
746
+ ? collectDescendantsAndSelf(root)
747
+ : [root];
748
+ rawSteps.forEach((rawStep, stepIdx) => {
749
+ const { tag } = parseStepSegment(rawStep);
750
+ const useCurrent = stepIdx === 0 && (isDescendantStart || matchesTagName(root.tag, tag));
751
+ current = applySingleXPathStep(current, rawStep, useCurrent);
752
+ });
753
+ return current;
754
+ }
755
+ function extractAttributeMatches(nodes, attrTarget) {
756
+ const out = [];
757
+ for (const n of nodes) {
758
+ for (const a of n.attributes) {
759
+ if (attrTarget === '*' || a.name === attrTarget) {
760
+ out.push({
761
+ xpath: `${n.xpath}/@${a.name}`,
762
+ nodeType: 'attribute',
763
+ label: `@${a.name}`,
764
+ value: a.value,
765
+ });
766
+ }
767
+ }
768
+ }
769
+ return out;
770
+ }
771
+ function formatElementNodeMatchValue(node) {
772
+ if (node.text)
773
+ return node.text;
774
+ if (node.cdata.length > 0)
775
+ return node.cdata.join(' ');
776
+ return `(${node.children.length} children)`;
777
+ }
778
+ /**
779
+ * Evaluates a lightweight XPath 1.0 expression against an `XmlTreeNode` hierarchy
780
+ * (supporting `/a/b`, `//tag`, predicates `[@attr='val']`, `[1]`, `[price>100]`,
781
+ * attribute axes `/@attr` and `//@attr`, and `count(...)`).
782
+ */
783
+ export function evaluateSimpleXPath(root, expr) {
784
+ const trimmed = expr.trim();
785
+ if (!trimmed)
786
+ return [];
787
+ const countMatch = /^count\((.+)\)$/i.exec(trimmed);
788
+ if (countMatch) {
789
+ const innerNodes = evaluatePathNodes(root, countMatch[1]);
790
+ return [{ xpath: trimmed, nodeType: 'scalar', label: 'count()', value: String(innerNodes.length) }];
791
+ }
792
+ if (trimmed.startsWith('//@')) {
793
+ return extractAttributeMatches(collectDescendantsAndSelf(root), trimmed.slice(3).trim());
794
+ }
795
+ const attrSlashIdx = trimmed.lastIndexOf('/@');
796
+ if (attrSlashIdx !== -1) {
797
+ const elementPath = trimmed.slice(0, attrSlashIdx) || '/';
798
+ const attrName = trimmed.slice(attrSlashIdx + 2).trim();
799
+ return extractAttributeMatches(evaluatePathNodes(root, elementPath), attrName);
800
+ }
801
+ return evaluatePathNodes(root, trimmed).map((n) => ({
802
+ xpath: n.xpath,
803
+ nodeType: 'element',
804
+ label: `<${n.tag}>`,
805
+ value: formatElementNodeMatchValue(n),
806
+ }));
807
+ }
808
+ /**
809
+ * Flattens and filters an `XmlTreeNode` hierarchy by a case-insensitive search query
810
+ * matching tag names, attribute names/values, text content, or CDATA sections.
811
+ */
812
+ export function filterXmlTreeNodes(root, query) {
813
+ const all = collectDescendantsAndSelf(root);
814
+ const needle = query.trim().toLowerCase();
815
+ if (!needle)
816
+ return all;
817
+ return all.filter((n) => {
818
+ if (n.tag.toLowerCase().includes(needle) || n.text.toLowerCase().includes(needle)) {
819
+ return true;
820
+ }
821
+ if (n.cdata.some((c) => c.toLowerCase().includes(needle))) {
822
+ return true;
823
+ }
824
+ return n.attributes.some((a) => a.name.toLowerCase().includes(needle) || a.value.toLowerCase().includes(needle));
825
+ });
826
+ }
827
+ function parseBooleanQuery(val) {
828
+ if (val === 'true' || val === '1')
829
+ return true;
830
+ if (val === 'false' || val === '0')
831
+ return false;
832
+ return null;
833
+ }
834
+ /**
835
+ * Parses URL query parameters (`?mode=...&indent=...&sortAttrs=...&stripComments=...&wrapAttrs=...`).
836
+ */
837
+ export function parseXmlUrlParams(search) {
838
+ const params = new URLSearchParams(search);
839
+ const rawMode = params.get('mode');
840
+ const rawIndent = params.get('indent');
841
+ return {
842
+ mode: rawMode && VALID_MODES.has(rawMode) ? rawMode : null,
843
+ indent: rawIndent && VALID_INDENTS.has(rawIndent) ? rawIndent : null,
844
+ sortAttrs: parseBooleanQuery(params.get('sortAttrs')),
845
+ stripComments: parseBooleanQuery(params.get('stripComments')),
846
+ wrapAttrs: parseBooleanQuery(params.get('wrapAttrs')),
847
+ };
848
+ }