• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

NaturalIntelligence / fast-xml-parser / 24500125020

16 Apr 2026 08:26AM UTC coverage: 97.64% (+0.02%) from 97.617%
24500125020

push

github

amitguptagwl
remove unwanted tests

1135 of 1182 branches covered (96.02%)

9392 of 9619 relevant lines covered (97.64%)

463944.63 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

96.76
/src/xmlparser/OrderedObjParser.js
1
'use strict';
5✔
2
///@ts-check
5✔
3

5✔
4
import { getAllMatches, isExist, DANGEROUS_PROPERTY_NAMES, criticalProperties } from '../util.js';
5✔
5
import xmlNode from './xmlNode.js';
5✔
6
import DocTypeReader from './DocTypeReader.js';
5✔
7
import toNumber from "strnum";
5✔
8
import getIgnoreAttributesFn from "../ignoreAttributes.js";
5✔
9
import { Expression, Matcher } from 'path-expression-matcher';
5✔
10
import { ExpressionSet } from 'path-expression-matcher';
5✔
11
import { EntityDecoder, XML, CURRENCY, COMMON_HTML } from '@nodable/entities';
5✔
12

5✔
13
// const regx =
5✔
14
//   '<((!\\[CDATA\\[([\\s\\S]*?)(]]>))|((NAME:)?(NAME))([^>]*)>|((\\/)(NAME)\\s*>))([^<]*)'
5✔
15
//   .replace(/NAME/g, util.nameRegexp);
5✔
16

5✔
17
//const tagsRegx = new RegExp("<(\\/?[\\w:\\-\._]+)([^>]*)>(\\s*"+cdataRegx+")*([^<]+)?","g");
5✔
18
//const tagsRegx = new RegExp("<(\\/?)((\\w*:)?([\\w:\\-\._]+))([^>]*)>([^<]*)("+cdataRegx+"([^<]*))*([^<]+)?","g");
5✔
19

5✔
20
// Helper functions for attribute and namespace handling
5✔
21

5✔
22
/**
5✔
23
 * Extract raw attributes (without prefix) from prefixed attribute map
5✔
24
 * @param {object} prefixedAttrs - Attributes with prefix from buildAttributesMap
5✔
25
 * @param {object} options - Parser options containing attributeNamePrefix
5✔
26
 * @returns {object} Raw attributes for matcher
5✔
27
 */
5✔
28
function extractRawAttributes(prefixedAttrs, options) {
760✔
29
  if (!prefixedAttrs) return {};
760!
30

760✔
31
  // Handle attributesGroupName option
760✔
32
  const attrs = options.attributesGroupName
760✔
33
    ? prefixedAttrs[options.attributesGroupName]
760✔
34
    : prefixedAttrs;
760✔
35

760✔
36
  if (!attrs) return {};
760!
37

760✔
38
  const rawAttrs = {};
760✔
39
  for (const key in attrs) {
760✔
40
    // Remove the attribute prefix to get raw name
1,630✔
41
    if (key.startsWith(options.attributeNamePrefix)) {
1,630✔
42
      const rawName = key.substring(options.attributeNamePrefix.length);
1,277✔
43
      rawAttrs[rawName] = attrs[key];
1,277✔
44
    } else {
1,630✔
45
      // Attribute without prefix (shouldn't normally happen, but be safe)
353✔
46
      rawAttrs[key] = attrs[key];
353✔
47
    }
353✔
48
  }
1,630✔
49
  return rawAttrs;
760✔
50
}
760✔
51

5✔
52
/**
5✔
53
 * Extract namespace from raw tag name
5✔
54
 * @param {string} rawTagName - Tag name possibly with namespace (e.g., "soap:Envelope")
5✔
55
 * @returns {string|undefined} Namespace or undefined
5✔
56
 */
5✔
57
function extractNamespace(rawTagName) {
6,390✔
58
  if (!rawTagName || typeof rawTagName !== 'string') return undefined;
6,390!
59

6,390✔
60
  const colonIndex = rawTagName.indexOf(':');
6,390✔
61
  if (colonIndex !== -1 && colonIndex > 0) {
6,390✔
62
    const ns = rawTagName.substring(0, colonIndex);
150✔
63
    // Don't treat xmlns as a namespace
150✔
64
    if (ns !== 'xmlns') {
150✔
65
      return ns;
150✔
66
    }
150✔
67
  }
150✔
68
  return undefined;
6,240✔
69
}
6,390✔
70

5✔
71
export default class OrderedObjParser {
5✔
72
  constructor(options) {
5✔
73
    this.options = options;
1,705✔
74
    this.currentNode = null;
1,705✔
75
    this.tagsNodeStack = [];
1,705✔
76
    this.parseXml = parseXml;
1,705✔
77
    this.parseTextData = parseTextData;
1,705✔
78
    this.resolveNameSpace = resolveNameSpace;
1,705✔
79
    this.buildAttributesMap = buildAttributesMap;
1,705✔
80
    this.isItStopNode = isItStopNode;
1,705✔
81
    this.replaceEntitiesValue = replaceEntitiesValue;
1,705✔
82
    this.readStopNodeData = readStopNodeData;
1,705✔
83
    this.saveTextToParentTag = saveTextToParentTag;
1,705✔
84
    this.addChild = addChild;
1,705✔
85
    this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes)
1,705✔
86
    this.entityExpansionCount = 0;
1,705✔
87
    this.currentExpandedLength = 0;
1,705✔
88
    let namedEntities = { ...XML };
1,705✔
89
    if (this.options.entityDecoder) {
1,705✔
90
      this.entityDecoder = this.options.entityDecoder
15✔
91
    } else {
1,705✔
92
      if (typeof this.options.htmlEntities === "object") namedEntities = this.options.htmlEntities;
1,690!
93
      else if (this.options.htmlEntities === true) namedEntities = { ...COMMON_HTML, ...CURRENCY };
1,690✔
94
      this.entityDecoder = new EntityDecoder({
1,690✔
95
        namedEntities: namedEntities,
1,690✔
96
        numericAllowed: this.options.htmlEntities,
1,690✔
97
        limit: {
1,690✔
98
          maxTotalExpansions: this.options.processEntities.maxTotalExpansions,
1,690✔
99
          maxExpandedLength: this.options.processEntities.maxExpandedLength,
1,690✔
100
          applyLimitsTo: this.options.processEntities.appliesTo,
1,690✔
101
        }
1,690✔
102
        //postCheck: resolved => resolved
1,690✔
103
      });
1,690✔
104
    }
1,690✔
105

1,705✔
106
    // Initialize path matcher for path-expression-matcher
1,705✔
107
    this.matcher = new Matcher();
1,705✔
108

1,705✔
109
    // Live read-only proxy of matcher — PEM creates and caches this internally.
1,705✔
110
    // All user callbacks receive this instead of the mutable matcher.
1,705✔
111
    this.readonlyMatcher = this.matcher.readOnly();
1,705✔
112

1,705✔
113
    // Flag to track if current node is a stop node (optimization)
1,705✔
114
    this.isCurrentNodeStopNode = false;
1,705✔
115

1,705✔
116
    // Pre-compile stopNodes expressions
1,705✔
117
    this.stopNodeExpressionsSet = new ExpressionSet();
1,705✔
118
    const stopNodesOpts = this.options.stopNodes;
1,705✔
119
    if (stopNodesOpts && stopNodesOpts.length > 0) {
1,705✔
120
      for (let i = 0; i < stopNodesOpts.length; i++) {
670✔
121
        const stopNodeExp = stopNodesOpts[i];
1,255✔
122
        if (typeof stopNodeExp === 'string') {
1,255✔
123
          // Convert string to Expression object
200✔
124
          this.stopNodeExpressionsSet.add(new Expression(stopNodeExp));
200✔
125
        } else if (stopNodeExp instanceof Expression) {
1,255✔
126
          // Already an Expression object
1,055✔
127
          this.stopNodeExpressionsSet.add(stopNodeExp);
1,055✔
128
        }
1,055✔
129
      }
1,255✔
130
      this.stopNodeExpressionsSet.seal();
670✔
131
    }
670✔
132
  }
1,705✔
133

5✔
134
}
5✔
135

5✔
136

5✔
137
/**
5✔
138
 * @param {string} val
5✔
139
 * @param {string} tagName
5✔
140
 * @param {string|Matcher} jPath - jPath string or Matcher instance based on options.jPath
5✔
141
 * @param {boolean} dontTrim
5✔
142
 * @param {boolean} hasAttributes
5✔
143
 * @param {boolean} isLeafNode
5✔
144
 * @param {boolean} escapeEntities
5✔
145
 */
5✔
146
function parseTextData(val, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) {
6,705✔
147
  const options = this.options;
6,705✔
148
  if (val !== undefined) {
6,705✔
149
    if (options.trimValues && !dontTrim) {
6,705✔
150
      val = val.trim();
6,460✔
151
    }
6,460✔
152
    if (val.length > 0) {
6,705✔
153
      if (!escapeEntities) val = this.replaceEntitiesValue(val, tagName, jPath);
2,020✔
154

1,985✔
155
      // Pass jPath string or matcher based on options.jPath setting
1,985✔
156
      const jPathOrMatcher = options.jPath ? jPath.toString() : jPath;
2,020✔
157
      const newval = options.tagValueProcessor(tagName, val, jPathOrMatcher, hasAttributes, isLeafNode);
2,020✔
158
      if (newval === null || newval === undefined) {
2,020✔
159
        //don't parse
50✔
160
        return val;
50✔
161
      } else if (typeof newval !== typeof val || newval !== val) {
2,020✔
162
        //overwrite
20✔
163
        return newval;
20✔
164
      } else if (options.trimValues) {
1,935✔
165
        return parseValue(val, options.parseTagValue, options.numberParseOptions);
1,855✔
166
      } else {
1,915✔
167
        const trimmedVal = val.trim();
60✔
168
        if (trimmedVal === val) {
60✔
169
          return parseValue(val, options.parseTagValue, options.numberParseOptions);
15✔
170
        } else {
60✔
171
          return val;
45✔
172
        }
45✔
173
      }
60✔
174
    }
2,020✔
175
  }
6,705✔
176
}
6,705✔
177

5✔
178
function resolveNameSpace(tagname) {
2,970✔
179
  if (this.options.removeNSPrefix) {
2,970✔
180
    const tags = tagname.split(':');
220✔
181
    const prefix = tagname.charAt(0) === '/' ? '/' : '';
220!
182
    if (tags[0] === 'xmlns') {
220✔
183
      return '';
70✔
184
    }
70✔
185
    if (tags.length === 2) {
220✔
186
      tagname = prefix + tags[1];
60✔
187
    }
60✔
188
  }
220✔
189
  return tagname;
2,900✔
190
}
2,970✔
191

5✔
192
//TODO: change regex to capture NS
5✔
193
//const attrsRegx = new RegExp("([\\w\\-\\.\\:]+)\\s*=\\s*(['\"])((.|\n)*?)\\2","gm");
5✔
194
const attrsRegx = new RegExp('([^\\s=]+)\\s*(=\\s*([\'"])([\\s\\S]*?)\\3)?', 'gm');
5✔
195

5✔
196
function buildAttributesMap(attrStr, jPath, tagName) {
1,230✔
197
  const options = this.options;
1,230✔
198
  if (options.ignoreAttributes !== true && typeof attrStr === 'string') {
1,230✔
199
    // attrStr = attrStr.replace(/\r?\n/g, ' ');
1,020✔
200
    //attrStr = attrStr || attrStr.trim();
1,020✔
201

1,020✔
202
    const matches = getAllMatches(attrStr, attrsRegx);
1,020✔
203
    const len = matches.length; //don't make it inline
1,020✔
204
    const attrs = {};
1,020✔
205

1,020✔
206
    // Pre-process values once: trim + entity replacement
1,020✔
207
    // Reused in both matcher update and second pass
1,020✔
208
    const processedVals = new Array(len);
1,020✔
209
    let hasRawAttrs = false;
1,020✔
210
    const rawAttrsForMatcher = {};
1,020✔
211

1,020✔
212
    for (let i = 0; i < len; i++) {
1,020✔
213
      const attrName = this.resolveNameSpace(matches[i][1]);
1,485✔
214
      const oldVal = matches[i][4];
1,485✔
215

1,485✔
216
      if (attrName.length && oldVal !== undefined) {
1,485✔
217
        let val = oldVal;
1,350✔
218
        if (options.trimValues) val = val.trim();
1,350✔
219
        val = this.replaceEntitiesValue(val, tagName, this.readonlyMatcher);
1,350✔
220
        processedVals[i] = val;
1,350✔
221

1,350✔
222
        rawAttrsForMatcher[attrName] = val;
1,350✔
223
        hasRawAttrs = true;
1,350✔
224
      }
1,350✔
225
    }
1,485✔
226

1,020✔
227
    // Update matcher ONCE before second pass, if applicable
1,020✔
228
    if (hasRawAttrs && typeof jPath === 'object' && jPath.updateCurrent) {
1,020✔
229
      jPath.updateCurrent(rawAttrsForMatcher);
890✔
230
    }
890✔
231

1,020✔
232
    // Hoist toString() once — path doesn't change during attribute processing
1,020✔
233
    const jPathStr = options.jPath ? jPath.toString() : this.readonlyMatcher;
1,020✔
234

1,020✔
235
    // Second pass: apply processors, build final attrs
1,020✔
236
    let hasAttrs = false;
1,020✔
237
    for (let i = 0; i < len; i++) {
1,020✔
238
      const attrName = this.resolveNameSpace(matches[i][1]);
1,485✔
239

1,485✔
240
      if (this.ignoreAttributesFn(attrName, jPathStr)) continue;
1,485✔
241

1,430✔
242
      let aName = options.attributeNamePrefix + attrName;
1,430✔
243

1,430✔
244
      if (attrName.length) {
1,485✔
245
        if (options.transformAttributeName) {
1,395✔
246
          aName = options.transformAttributeName(aName);
25✔
247
        }
25✔
248
        aName = sanitizeName(aName, options);
1,395✔
249

1,395✔
250
        if (matches[i][4] !== undefined) {
1,395✔
251
          // Reuse already-processed value — no double entity replacement
1,280✔
252
          const oldVal = processedVals[i];
1,280✔
253

1,280✔
254
          const newVal = options.attributeValueProcessor(attrName, oldVal, jPathStr);
1,280✔
255
          if (newVal === null || newVal === undefined) {
1,280!
256
            attrs[aName] = oldVal;
×
257
          } else if (typeof newVal !== typeof oldVal || newVal !== oldVal) {
1,280✔
258
            attrs[aName] = newVal;
5✔
259
          } else {
1,280✔
260
            attrs[aName] = parseValue(oldVal, options.parseAttributeValue, options.numberParseOptions);
1,275✔
261
          }
1,275✔
262
          hasAttrs = true;
1,280✔
263
        } else if (options.allowBooleanAttributes) {
1,395✔
264
          attrs[aName] = true;
80✔
265
          hasAttrs = true;
80✔
266
        }
80✔
267
      }
1,395✔
268
    }
1,485✔
269

1,005✔
270
    if (!hasAttrs) return;
1,020✔
271

900✔
272
    if (options.attributesGroupName) {
1,020✔
273
      const attrCollection = {};
65✔
274
      attrCollection[options.attributesGroupName] = attrs;
65✔
275
      return attrCollection;
65✔
276
    }
65✔
277
    return attrs;
835✔
278
  }
835✔
279
}
1,230✔
280
const parseXml = function (xmlData) {
5✔
281
  xmlData = xmlData.replace(/\r\n?/g, "\n"); //TODO: remove this line
1,700✔
282
  const xmlObj = new xmlNode('!xml');
1,700✔
283
  let currentNode = xmlObj;
1,700✔
284
  let textData = "";
1,700✔
285

1,700✔
286
  // Reset matcher for new document
1,700✔
287
  this.matcher.reset();
1,700✔
288
  this.entityDecoder.reset();
1,700✔
289

1,700✔
290
  // Reset entity expansion counters for this document
1,700✔
291
  this.entityExpansionCount = 0;
1,700✔
292
  this.currentExpandedLength = 0;
1,700✔
293
  const options = this.options;
1,700✔
294
  const docTypeReader = new DocTypeReader(options.processEntities);
1,700✔
295
  const xmlLen = xmlData.length;
1,700✔
296
  for (let i = 0; i < xmlLen; i++) {//for each char in XML data
1,700✔
297
    const ch = xmlData[i];
326,075✔
298
    if (ch === '<') {
326,075✔
299
      // const nextIndex = i+1;
11,265✔
300
      // const _2ndChar = xmlData[nextIndex];
11,265✔
301
      const c1 = xmlData.charCodeAt(i + 1);
11,265✔
302
      if (c1 === 47) {//Closing Tag '/'
11,265✔
303
        const closeIndex = findClosingIndex(xmlData, ">", i, "Closing Tag is not closed.")
4,090✔
304
        let tagName = xmlData.substring(i + 2, closeIndex).trim();
4,090✔
305

4,090✔
306
        if (options.removeNSPrefix) {
4,090✔
307
          const colonIndex = tagName.indexOf(":");
115✔
308
          if (colonIndex !== -1) {
115✔
309
            tagName = tagName.substr(colonIndex + 1);
50✔
310
          }
50✔
311
        }
115✔
312

4,085✔
313
        tagName = transformTagName(options.transformTagName, tagName, "", options).tagName;
4,085✔
314

4,085✔
315
        if (currentNode) {
4,085✔
316
          textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);
4,085✔
317
        }
4,085✔
318

4,050✔
319
        //check if last tag of nested tag was unpaired tag
4,050✔
320
        const lastTagName = this.matcher.getCurrentTag();
4,050✔
321
        if (tagName && options.unpairedTagsSet.has(tagName)) {
4,090✔
322
          throw new Error(`Unpaired tag can not be used as closing tag: </${tagName}>`);
5✔
323
        }
5✔
324
        if (lastTagName && options.unpairedTagsSet.has(lastTagName)) {
4,090!
325
          // Pop the unpaired tag
×
326
          this.matcher.pop();
×
327
          this.tagsNodeStack.pop();
×
328
        }
×
329
        // Pop the closing tag
4,045✔
330
        this.matcher.pop();
4,045✔
331
        this.isCurrentNodeStopNode = false; // Reset flag when closing tag
4,045✔
332

4,045✔
333
        currentNode = this.tagsNodeStack.pop();//avoid recursion, set the parent tag scope
4,045✔
334
        textData = "";
4,045✔
335
        i = closeIndex;
4,045✔
336
      } else if (c1 === 63) { //'?'
11,265✔
337

260✔
338
        let tagData = readTagExp(xmlData, i, false, "?>");
260✔
339
        if (!tagData) throw new Error("Pi Tag is not closed.");
260✔
340

250✔
341
        textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);
250✔
342
        const attsMap = this.buildAttributesMap(tagData.tagExp, this.matcher, tagData.tagName);
250✔
343
        if (attsMap && attsMap["version"]) {
260✔
344
          this.entityDecoder.setXmlVersion(attsMap["version"]);
50✔
345
        }
50✔
346
        if ((options.ignoreDeclaration && tagData.tagName === "?xml") || options.ignorePiTags) {
260✔
347
          //do nothing
25✔
348
        } else {
260✔
349

225✔
350
          const childNode = new xmlNode(tagData.tagName);
225✔
351
          childNode.add(options.textNodeName, "");
225✔
352

225✔
353
          if (tagData.tagName !== tagData.tagExp && tagData.attrExpPresent) {
225✔
354
            childNode[":@"] = attsMap
215✔
355
          }
215✔
356
          this.addChild(currentNode, childNode, this.readonlyMatcher, i);
225✔
357
        }
225✔
358

250✔
359

250✔
360
        i = tagData.closeIndex + 1;
250✔
361
      } else if (c1 === 33
7,175✔
362
        && xmlData.charCodeAt(i + 2) === 45
6,915✔
363
        && xmlData.charCodeAt(i + 3) === 45) { //'!--'
6,915✔
364
        const endIndex = findClosingIndex(xmlData, "-->", i + 4, "Comment is not closed.")
60✔
365
        if (options.commentPropName) {
60✔
366
          const comment = xmlData.substring(i + 4, endIndex - 2);
25✔
367

25✔
368
          textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);
25✔
369

25✔
370
          currentNode.add(options.commentPropName, [{ [options.textNodeName]: comment }]);
25✔
371
        }
25✔
372
        i = endIndex;
55✔
373
      } else if (c1 === 33
6,915✔
374
        && xmlData.charCodeAt(i + 2) === 68) { //'!D'
6,855✔
375
        const result = docTypeReader.readDocType(xmlData, i);
220✔
376
        this.entityDecoder.addInputEntities(result.entities);
220✔
377
        i = result.i;
220✔
378
      } else if (c1 === 33
6,855✔
379
        && xmlData.charCodeAt(i + 2) === 91) { // '!['
6,635✔
380
        const closeIndex = findClosingIndex(xmlData, "]]>", i, "CDATA is not closed.") - 2;
190✔
381
        const tagExp = xmlData.substring(i + 9, closeIndex);
190✔
382

190✔
383
        textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);
190✔
384

190✔
385
        let val = this.parseTextData(tagExp, currentNode.tagname, this.readonlyMatcher, true, false, true, true);
190✔
386
        if (val == undefined) val = "";
190✔
387

185✔
388
        //cdata should be set even if it is 0 length string
185✔
389
        if (options.cdataPropName) {
190✔
390
          currentNode.add(options.cdataPropName, [{ [options.textNodeName]: tagExp }]);
35✔
391
        } else {
190✔
392
          currentNode.add(options.textNodeName, val);
150✔
393
        }
150✔
394

185✔
395
        i = closeIndex + 2;
185✔
396
      } else {//Opening tag
6,635✔
397
        let result = readTagExp(xmlData, i, options.removeNSPrefix);
6,445✔
398

6,445✔
399
        // Safety check: readTagExp can return undefined
6,445✔
400
        if (!result) {
6,445!
401
          // Log context for debugging
×
402
          const context = xmlData.substring(Math.max(0, i - 50), Math.min(xmlLen, i + 50));
×
403
          throw new Error(`readTagExp returned undefined at position ${i}. Context: "${context}"`);
×
404
        }
×
405

6,445✔
406
        let tagName = result.tagName;
6,445✔
407
        const rawTagName = result.rawTagName;
6,445✔
408
        let tagExp = result.tagExp;
6,445✔
409
        let attrExpPresent = result.attrExpPresent;
6,445✔
410
        let closeIndex = result.closeIndex;
6,445✔
411

6,445✔
412
        ({ tagName, tagExp } = transformTagName(options.transformTagName, tagName, tagExp, options));
6,445✔
413

6,445✔
414
        if (options.strictReservedNames &&
6,445✔
415
          (tagName === options.commentPropName
6,385✔
416
            || tagName === options.cdataPropName
6,385✔
417
            || tagName === options.textNodeName
6,385✔
418
            || tagName === options.attributesGroupName
6,385✔
419
          )) {
6,445✔
420
          throw new Error(`Invalid tag name: ${tagName}`);
5✔
421
        }
5✔
422

6,390✔
423
        //save text as child node
6,390✔
424
        if (currentNode && textData) {
6,445✔
425
          if (currentNode.tagname !== '!xml') {
4,120✔
426
            //when nested tag is found
3,225✔
427
            textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher, false);
3,225✔
428
          }
3,225✔
429
        }
4,120✔
430

6,390✔
431
        //check if last tag was unpaired tag
6,390✔
432
        const lastTag = currentNode;
6,390✔
433
        if (lastTag && options.unpairedTagsSet.has(lastTag.tagname)) {
6,445!
434
          currentNode = this.tagsNodeStack.pop();
×
435
          this.matcher.pop();
×
436
        }
×
437

6,390✔
438
        // Clean up self-closing syntax BEFORE processing attributes
6,390✔
439
        // This is where tagExp gets the trailing / removed
6,390✔
440
        let isSelfClosing = false;
6,390✔
441
        if (tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1) {
6,445✔
442
          isSelfClosing = true;
280✔
443
          if (tagName[tagName.length - 1] === "/") {
280✔
444
            tagName = tagName.substr(0, tagName.length - 1);
100✔
445
            tagExp = tagName;
100✔
446
          } else {
280✔
447
            tagExp = tagExp.substr(0, tagExp.length - 1);
180✔
448
          }
180✔
449

280✔
450
          // Re-check attrExpPresent after cleaning
280✔
451
          attrExpPresent = (tagName !== tagExp);
280✔
452
        }
280✔
453

6,390✔
454
        // Now process attributes with CLEAN tagExp (no trailing /)
6,390✔
455
        let prefixedAttrs = null;
6,390✔
456
        let rawAttrs = {};
6,390✔
457
        let namespace = undefined;
6,390✔
458

6,390✔
459
        // Extract namespace from rawTagName
6,390✔
460
        namespace = extractNamespace(rawTagName);
6,390✔
461

6,390✔
462
        // Push tag to matcher FIRST (with empty attrs for now) so callbacks see correct path
6,390✔
463
        if (tagName !== xmlObj.tagname) {
6,390✔
464
          this.matcher.push(tagName, {}, namespace);
6,390✔
465
        }
6,390✔
466

6,390✔
467
        // Now build attributes - callbacks will see correct matcher state
6,390✔
468
        if (tagName !== tagExp && attrExpPresent) {
6,445✔
469
          // Build attributes (returns prefixed attributes for the tree)
980✔
470
          // Note: buildAttributesMap now internally updates the matcher with raw attributes
980✔
471
          prefixedAttrs = this.buildAttributesMap(tagExp, this.matcher, tagName);
980✔
472

980✔
473
          if (prefixedAttrs) {
980✔
474
            // Extract raw attributes (without prefix) for our use
760✔
475
            rawAttrs = extractRawAttributes(prefixedAttrs, options);
760✔
476
          }
760✔
477
        }
980✔
478

6,375✔
479
        // Now check if this is a stop node (after attributes are set)
6,375✔
480
        if (tagName !== xmlObj.tagname) {
6,375✔
481
          this.isCurrentNodeStopNode = this.isItStopNode();
6,375✔
482
        }
6,375✔
483

6,375✔
484
        const startIndex = i;
6,375✔
485
        if (this.isCurrentNodeStopNode) {
6,445✔
486
          let tagContent = "";
1,225✔
487

1,225✔
488
          // For self-closing tags, content is empty
1,225✔
489
          if (isSelfClosing) {
1,225✔
490
            i = result.closeIndex;
10✔
491
          }
10✔
492
          //unpaired tag
1,215✔
493
          else if (options.unpairedTagsSet.has(tagName)) {
1,215✔
494
            i = result.closeIndex;
5✔
495
          }
5✔
496
          //normal tag
1,210✔
497
          else {
1,210✔
498
            //read until closing tag is found
1,210✔
499
            const result = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1);
1,210✔
500
            if (!result) throw new Error(`Unexpected end of ${rawTagName}`);
1,210!
501
            i = result.i;
1,210✔
502
            tagContent = result.tagContent;
1,210✔
503
          }
1,210✔
504

1,225✔
505
          const childNode = new xmlNode(tagName);
1,225✔
506

1,225✔
507
          if (prefixedAttrs) {
1,225✔
508
            childNode[":@"] = prefixedAttrs;
20✔
509
          }
20✔
510

1,225✔
511
          // For stop nodes, store raw content as-is without any processing
1,225✔
512
          childNode.add(options.textNodeName, tagContent);
1,225✔
513

1,225✔
514
          this.matcher.pop(); // Pop the stop node tag
1,225✔
515
          this.isCurrentNodeStopNode = false; // Reset flag
1,225✔
516

1,225✔
517
          this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);
1,225✔
518
        } else {
6,445✔
519
          //selfClosing tag
5,150✔
520
          if (isSelfClosing) {
5,150✔
521
            ({ tagName, tagExp } = transformTagName(options.transformTagName, tagName, tagExp, options));
270✔
522

270✔
523
            const childNode = new xmlNode(tagName);
270✔
524
            if (prefixedAttrs) {
270✔
525
              childNode[":@"] = prefixedAttrs;
90✔
526
            }
90✔
527
            this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);
270✔
528
            this.matcher.pop(); // Pop self-closing tag
270✔
529
            this.isCurrentNodeStopNode = false; // Reset flag
270✔
530
          }
270✔
531
          else if (options.unpairedTagsSet.has(tagName)) {//unpaired tag
4,880✔
532
            const childNode = new xmlNode(tagName);
210✔
533
            if (prefixedAttrs) {
210✔
534
              childNode[":@"] = prefixedAttrs;
90✔
535
            }
90✔
536
            this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);
210✔
537
            this.matcher.pop(); // Pop unpaired tag
210✔
538
            this.isCurrentNodeStopNode = false; // Reset flag
210✔
539
            i = result.closeIndex;
210✔
540
            // Continue to next iteration without changing currentNode
210✔
541
            continue;
210✔
542
          }
210✔
543
          //opening tag
4,670✔
544
          else {
4,670✔
545
            const childNode = new xmlNode(tagName);
4,670✔
546
            if (this.tagsNodeStack.length > options.maxNestedTags) {
4,670✔
547
              throw new Error("Maximum nested tags exceeded");
5✔
548
            }
5✔
549
            this.tagsNodeStack.push(currentNode);
4,665✔
550

4,665✔
551
            if (prefixedAttrs) {
4,670✔
552
              childNode[":@"] = prefixedAttrs;
560✔
553
            }
560✔
554
            this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);
4,665✔
555
            currentNode = childNode;
4,665✔
556
          }
4,665✔
557
          textData = "";
4,935✔
558
          i = closeIndex;
4,935✔
559
        }
4,935✔
560
      }
6,445✔
561
    } else {
326,075✔
562
      textData += xmlData[i];
314,810✔
563
    }
314,810✔
564
  }
326,075✔
565
  return xmlObj.child;
1,535✔
566
}
1,700✔
567

5✔
568
function addChild(currentNode, childNode, matcher, startIndex) {
6,595✔
569
  // unset startIndex if not requested
6,595✔
570
  if (!this.options.captureMetaData) startIndex = undefined;
6,595✔
571

6,595✔
572
  // Pass jPath string or matcher based on options.jPath setting
6,595✔
573
  const jPathOrMatcher = this.options.jPath ? matcher.toString() : matcher;
6,595✔
574
  const result = this.options.updateTag(childNode.tagname, jPathOrMatcher, childNode[":@"])
6,595✔
575
  if (result === false) {
6,595✔
576
    //do nothing
25✔
577
  } else if (typeof result === "string") {
6,595✔
578
    childNode.tagname = result
6,570✔
579
    currentNode.addChild(childNode, startIndex);
6,570✔
580
  } else {
6,570!
581
    currentNode.addChild(childNode, startIndex);
×
582
  }
×
583
}
6,595✔
584

5✔
585
/**
5✔
586
 * @param {object} val - Entity object with regex and val properties
5✔
587
 * @param {string} tagName - Tag name
5✔
588
 * @param {string|Matcher} jPath - jPath string or Matcher instance based on options.jPath
5✔
589
 */
5✔
590
function replaceEntitiesValue(val, tagName, jPath) {
3,205✔
591
  const entityConfig = this.options.processEntities;
3,205✔
592

3,205✔
593
  if (!entityConfig || !entityConfig.enabled) {
3,205✔
594
    return val;
60✔
595
  }
60✔
596

3,145✔
597
  // Check if tag is allowed to contain entities
3,145✔
598
  if (entityConfig.allowedTags) {
3,205✔
599
    const jPathOrMatcher = this.options.jPath ? jPath.toString() : jPath;
30!
600
    const allowed = Array.isArray(entityConfig.allowedTags)
30✔
601
      ? entityConfig.allowedTags.includes(tagName)
30✔
602
      : entityConfig.allowedTags(tagName, jPathOrMatcher);
30!
603

30✔
604
    if (!allowed) {
30✔
605
      return val;
10✔
606
    }
10✔
607
  }
30✔
608

3,135✔
609
  // Apply custom tag filter if provided
3,135✔
610
  if (entityConfig.tagFilter) {
3,205✔
611
    const jPathOrMatcher = this.options.jPath ? jPath.toString() : jPath;
25!
612
    if (!entityConfig.tagFilter(tagName, jPathOrMatcher)) {
25✔
613
      return val; // Skip based on custom filter
15✔
614
    }
15✔
615
  }
25✔
616

3,120✔
617
  return this.entityDecoder.decode(val);
3,120✔
618
}
3,205✔
619

5✔
620

5✔
621
function saveTextToParentTag(textData, parentNode, matcher, isLeafNode) {
7,770✔
622
  if (textData) { //store previously collected data as textNode
7,770✔
623
    if (isLeafNode === undefined) isLeafNode = parentNode.child.length === 0
6,520✔
624

6,520✔
625
    textData = this.parseTextData(textData,
6,520✔
626
      parentNode.tagname,
6,520✔
627
      matcher,
6,520✔
628
      false,
6,520✔
629
      parentNode[":@"] ? Object.keys(parentNode[":@"]).length !== 0 : false,
6,520!
630
      isLeafNode);
6,520✔
631

6,520✔
632
    if (textData !== undefined && textData !== "")
6,520✔
633
      parentNode.add(this.options.textNodeName, textData);
6,520✔
634
    textData = "";
6,485✔
635
  }
6,485✔
636
  return textData;
7,735✔
637
}
7,770✔
638

5✔
639
/**
5✔
640
 * @param {Array<Expression>} stopNodeExpressions - Array of compiled Expression objects
5✔
641
 * @param {Matcher} matcher - Current path matcher
5✔
642
 */
5✔
643
function isItStopNode() {
6,375✔
644
  if (this.stopNodeExpressionsSet.size === 0) return false;
6,375✔
645

2,220✔
646
  return this.matcher.matchesAny(this.stopNodeExpressionsSet);
2,220✔
647
}
6,375✔
648

5✔
649
/**
5✔
650
 * Returns the tag Expression and where it is ending handling single-double quotes situation
5✔
651
 * @param {string} xmlData 
5✔
652
 * @param {number} i starting index
5✔
653
 * @returns 
5✔
654
 */
5✔
655
function tagExpWithClosingIndex(xmlData, i, closingChar = ">") {
6,880✔
656
  let attrBoundary = 0;
6,880✔
657
  const chars = [];
6,880✔
658
  const len = xmlData.length;
6,880✔
659
  const closeCode0 = closingChar.charCodeAt(0);
6,880✔
660
  const closeCode1 = closingChar.length > 1 ? closingChar.charCodeAt(1) : -1;
6,880✔
661

6,880✔
662
  for (let index = i; index < len; index++) {
6,880✔
663
    const code = xmlData.charCodeAt(index);
68,285✔
664

68,285✔
665
    if (attrBoundary) {
68,285✔
666
      if (code === attrBoundary) attrBoundary = 0;
14,660✔
667
    } else if (code === 34 || code === 39) { // " or '
68,285✔
668
      attrBoundary = code;
1,610✔
669
    } else if (code === closeCode0) {
53,625✔
670
      if (closeCode1 !== -1) {
7,125✔
671
        if (xmlData.charCodeAt(index + 1) === closeCode1) {
510✔
672
          return { data: String.fromCharCode(...chars), index };
250✔
673
        }
250✔
674
      } else {
7,125✔
675
        return { data: String.fromCharCode(...chars), index };
6,615✔
676
      }
6,615✔
677
    } else if (code === 9) { // \t
52,015✔
678
      chars.push(32); // space
20✔
679
      continue;
20✔
680
    }
20✔
681

61,400✔
682
    chars.push(code);
61,400✔
683
  }
61,400✔
684
}
6,880✔
685

5✔
686
function findClosingIndex(xmlData, str, i, errMsg) {
4,350✔
687
  const closingIndex = xmlData.indexOf(str, i);
4,350✔
688
  if (closingIndex === -1) {
4,350✔
689
    throw new Error(errMsg)
15✔
690
  } else {
4,350✔
691
    return closingIndex + str.length - 1;
4,335✔
692
  }
4,335✔
693
}
4,350✔
694

5✔
695
function findClosingChar(xmlData, char, i, errMsg) {
1,370✔
696
  const closingIndex = xmlData.indexOf(char, i);
1,370✔
697
  if (closingIndex === -1) throw new Error(errMsg);
1,370!
698
  return closingIndex; // no offset needed
1,370✔
699
}
1,370✔
700

5✔
701
function readTagExp(xmlData, i, removeNSPrefix, closingChar = ">") {
6,880✔
702
  const result = tagExpWithClosingIndex(xmlData, i + 1, closingChar);
6,880✔
703
  if (!result) return;
6,880✔
704
  let tagExp = result.data;
6,865✔
705
  const closeIndex = result.index;
6,865✔
706
  const separatorIndex = tagExp.search(/\s/);
6,865✔
707
  let tagName = tagExp;
6,865✔
708
  let attrExpPresent = true;
6,865✔
709
  if (separatorIndex !== -1) {//separate tag name and attributes expression
6,880✔
710
    tagName = tagExp.substring(0, separatorIndex);
1,245✔
711
    tagExp = tagExp.substring(separatorIndex + 1).trimStart();
1,245✔
712
  }
1,245✔
713

6,865✔
714
  const rawTagName = tagName;
6,865✔
715
  if (removeNSPrefix) {
6,880✔
716
    const colonIndex = tagName.indexOf(":");
300✔
717
    if (colonIndex !== -1) {
300✔
718
      tagName = tagName.substr(colonIndex + 1);
65✔
719
      attrExpPresent = tagName !== result.data.substr(colonIndex + 1);
65✔
720
    }
65✔
721
  }
300✔
722

6,865✔
723
  return {
6,865✔
724
    tagName: tagName,
6,865✔
725
    tagExp: tagExp,
6,865✔
726
    closeIndex: closeIndex,
6,865✔
727
    attrExpPresent: attrExpPresent,
6,865✔
728
    rawTagName: rawTagName,
6,865✔
729
  }
6,865✔
730
}
6,880✔
731
/**
5✔
732
 * find paired tag for a stop node
5✔
733
 * @param {string} xmlData 
5✔
734
 * @param {string} tagName 
5✔
735
 * @param {number} i 
5✔
736
 */
5✔
737
function readStopNodeData(xmlData, tagName, i) {
1,210✔
738
  const startIndex = i;
1,210✔
739
  // Starting at 1 since we already have an open tag
1,210✔
740
  let openTagCount = 1;
1,210✔
741

1,210✔
742
  const xmllen = xmlData.length;
1,210✔
743
  for (; i < xmllen; i++) {
1,210✔
744
    if (xmlData[i] === "<") {
15,985✔
745
      const c1 = xmlData.charCodeAt(i + 1);
1,555✔
746
      if (c1 === 47) {//close tag '/'
1,555✔
747
        const closeIndex = findClosingChar(xmlData, ">", i, `${tagName} is not closed`);
1,370✔
748
        let closeTagName = xmlData.substring(i + 2, closeIndex).trim();
1,370✔
749
        if (closeTagName === tagName) {
1,370✔
750
          openTagCount--;
1,215✔
751
          if (openTagCount === 0) {
1,215✔
752
            return {
1,210✔
753
              tagContent: xmlData.substring(startIndex, i),
1,210✔
754
              i: closeIndex
1,210✔
755
            }
1,210✔
756
          }
1,210✔
757
        }
1,215✔
758
        i = closeIndex;
160✔
759
      } else if (c1 === 63) { //?
1,555!
760
        const closeIndex = findClosingIndex(xmlData, "?>", i + 1, "StopNode is not closed.")
×
761
        i = closeIndex;
×
762
      } else if (c1 === 33
185✔
763
        && xmlData.charCodeAt(i + 2) === 45
185✔
764
        && xmlData.charCodeAt(i + 3) === 45) { // '!--'
185✔
765
        const closeIndex = findClosingIndex(xmlData, "-->", i + 3, "StopNode is not closed.")
5✔
766
        i = closeIndex;
5✔
767
      } else if (c1 === 33
185✔
768
        && xmlData.charCodeAt(i + 2) === 91) { // '!['
180✔
769
        const closeIndex = findClosingIndex(xmlData, "]]>", i, "StopNode is not closed.") - 2;
5✔
770
        i = closeIndex;
5✔
771
      } else {
180✔
772
        const tagData = readTagExp(xmlData, i, '>')
175✔
773

175✔
774
        if (tagData) {
175✔
775
          const openTagName = tagData && tagData.tagName;
170✔
776
          if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length - 1] !== "/") {
170✔
777
            openTagCount++;
5✔
778
          }
5✔
779
          i = tagData.closeIndex;
170✔
780
        }
170✔
781
      }
175✔
782
    }
1,555✔
783
  }//end for loop
1,210✔
784
}
1,210✔
785

5✔
786
function parseValue(val, shouldParse, options) {
3,145✔
787
  if (shouldParse && typeof val === 'string') {
3,145✔
788
    //console.log(options)
2,090✔
789
    const newval = val.trim();
2,090✔
790
    if (newval === 'true') return true;
2,090✔
791
    else if (newval === 'false') return false;
2,055✔
792
    else return toNumber(val, options);
2,040✔
793
  } else {
3,145✔
794
    if (isExist(val)) {
1,055✔
795
      return val;
1,055✔
796
    } else {
1,055!
797
      return '';
×
798
    }
×
799
  }
1,055✔
800
}
3,145✔
801

5✔
802
function fromCodePoint(str, base, prefix) {
×
803
  const codePoint = Number.parseInt(str, base);
×
804

×
805
  if (codePoint >= 0 && codePoint <= 0x10FFFF) {
×
806
    return String.fromCodePoint(codePoint);
×
807
  } else {
×
808
    return prefix + str + ";";
×
809
  }
×
810
}
×
811

5✔
812
function transformTagName(fn, tagName, tagExp, options) {
10,800✔
813
  if (fn) {
10,800✔
814
    const newTagName = fn(tagName);
160✔
815
    if (tagExp === tagName) {
160✔
816
      tagExp = newTagName
55✔
817
    }
55✔
818
    tagName = newTagName;
160✔
819
  }
160✔
820
  tagName = sanitizeName(tagName, options);
10,800✔
821
  return { tagName, tagExp };
10,800✔
822
}
10,800✔
823

5✔
824

5✔
825

5✔
826
function sanitizeName(name, options) {
12,195✔
827
  if (criticalProperties.includes(name)) {
12,195✔
828
    throw new Error(`[SECURITY] Invalid name: "${name}" is a reserved JavaScript keyword that could cause prototype pollution`);
30✔
829
  } else if (DANGEROUS_PROPERTY_NAMES.includes(name)) {
12,195✔
830
    return options.onDangerousProperty(name);
105✔
831
  }
105✔
832
  return name;
12,060✔
833
}
12,195✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc