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

NaturalIntelligence / fast-xml-parser / 12317922166

13 Dec 2024 02:55PM UTC coverage: 98.212%. Remained the same
12317922166

Pull #699

github

web-flow
Merge ae43748a5 into 408290231
Pull Request #699: Fixes entity parsing when used in strict mode

804 of 863 branches covered (93.16%)

2746 of 2796 relevant lines covered (98.21%)

682647.78 hits per line

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

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

4
const util = require('../util');
4✔
5
const xmlNode = require('./xmlNode');
4✔
6
const readDocType = require("./DocTypeReader");
4✔
7
const toNumber = require("strnum");
4✔
8
const getIgnoreAttributesFn = require('../ignoreAttributes')
4✔
9

10
// const regx =
11
//   '<((!\\[CDATA\\[([\\s\\S]*?)(]]>))|((NAME:)?(NAME))([^>]*)>|((\\/)(NAME)\\s*>))([^<]*)'
12
//   .replace(/NAME/g, util.nameRegexp);
13

14
//const tagsRegx = new RegExp("<(\\/?[\\w:\\-\._]+)([^>]*)>(\\s*"+cdataRegx+")*([^<]+)?","g");
15
//const tagsRegx = new RegExp("<(\\/?)((\\w*:)?([\\w:\\-\._]+))([^>]*)>([^<]*)("+cdataRegx+"([^<]*))*([^<]+)?","g");
16

17
class OrderedObjParser{
18
  constructor(options){
19
    this.options = options;
660✔
20
    this.currentNode = null;
660✔
21
    this.tagsNodeStack = [];
660✔
22
    this.docTypeEntities = {};
660✔
23
    this.lastEntities = {
660✔
24
      "apos" : { regex: /&(apos|#39|#x27);/g, val : "'"},
25
      "gt" : { regex: /&(gt|#62|#x3E);/g, val : ">"},
26
      "lt" : { regex: /&(lt|#60|#x3C);/g, val : "<"},
27
      "quot" : { regex: /&(quot|#34|#x22);/g, val : "\""},
28
    };
29
    this.ampEntity = { regex: /&(amp|#38|#x26);/g, val : "&"};
660✔
30
    this.htmlEntities = {
660✔
31
      "space": { regex: /&(nbsp|#160);/g, val: " " },
32
      // "lt" : { regex: /&(lt|#60);/g, val: "<" },
33
      // "gt" : { regex: /&(gt|#62);/g, val: ">" },
34
      // "amp" : { regex: /&(amp|#38);/g, val: "&" },
35
      // "quot" : { regex: /&(quot|#34);/g, val: "\"" },
36
      // "apos" : { regex: /&(apos|#39);/g, val: "'" },
37
      "cent" : { regex: /&(cent|#162);/g, val: "¢" },
38
      "pound" : { regex: /&(pound|#163);/g, val: "£" },
39
      "yen" : { regex: /&(yen|#165);/g, val: "Â¥" },
40
      "euro" : { regex: /&(euro|#8364);/g, val: "€" },
41
      "copyright" : { regex: /&(copy|#169);/g, val: "©" },
42
      "reg" : { regex: /&(reg|#174);/g, val: "®" },
43
      "inr" : { regex: /&(inr|#8377);/g, val: "₹" },
44
      "num_dec": { regex: /&#([0-9]{1,7});/g, val : (_, str) => String.fromCharCode(Number.parseInt(str, 10)) },
4✔
45
      "num_hex": { regex: /&#x([0-9a-fA-F]{1,6});/g, val : (_, str) => String.fromCharCode(Number.parseInt(str, 16)) },
20✔
46
    };
47
    this.addExternalEntities = addExternalEntities;
660✔
48
    this.parseXml = parseXml;
660✔
49
    this.parseTextData = parseTextData;
660✔
50
    this.resolveNameSpace = resolveNameSpace;
660✔
51
    this.buildAttributesMap = buildAttributesMap;
660✔
52
    this.isItStopNode = isItStopNode;
660✔
53
    this.replaceEntitiesValue = replaceEntitiesValue;
660✔
54
    this.readStopNodeData = readStopNodeData;
660✔
55
    this.saveTextToParentTag = saveTextToParentTag;
660✔
56
    this.addChild = addChild;
660✔
57
    this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes)
660✔
58
  }
59

60
}
61

62
function addExternalEntities(externalEntities){
63
  const entKeys = Object.keys(externalEntities);
660✔
64
  for (let i = 0; i < entKeys.length; i++) {
660✔
65
    const ent = entKeys[i];
12✔
66
    this.lastEntities[ent] = {
12✔
67
       regex: new RegExp("&"+ent+";","g"),
68
       val : externalEntities[ent]
69
    }
70
  }
71
}
72

73
/**
74
 * @param {string} val
75
 * @param {string} tagName
76
 * @param {string} jPath
77
 * @param {boolean} dontTrim
78
 * @param {boolean} hasAttributes
79
 * @param {boolean} isLeafNode
80
 * @param {boolean} escapeEntities
81
 */
82
function parseTextData(val, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) {
83
  if (val !== undefined) {
4,152!
84
    if (this.options.trimValues && !dontTrim) {
4,152✔
85
      val = val.trim();
3,832✔
86
    }
87
    if(val.length > 0){
4,152✔
88
      if(!escapeEntities) val = this.replaceEntitiesValue(val);
1,632✔
89
      
90
      const newval = this.options.tagValueProcessor(tagName, val, jPath, hasAttributes, isLeafNode);
1,632✔
91
      if(newval === null || newval === undefined){
1,632✔
92
        //don't parse
93
        return val;
40✔
94
      }else if(typeof newval !== typeof val || newval !== val){
1,592✔
95
        //overwrite
96
        return newval;
16✔
97
      }else if(this.options.trimValues){
1,576✔
98
        return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions);
1,528✔
99
      }else{
100
        const trimmedVal = val.trim();
48✔
101
        if(trimmedVal === val){
48✔
102
          return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions);
12✔
103
        }else{
104
          return val;
36✔
105
        }
106
      }
107
    }
108
  }
109
}
110

111
function resolveNameSpace(tagname) {
112
  if (this.options.removeNSPrefix) {
1,076✔
113
    const tags = tagname.split(':');
88✔
114
    const prefix = tagname.charAt(0) === '/' ? '/' : '';
88!
115
    if (tags[0] === 'xmlns') {
88✔
116
      return '';
28✔
117
    }
118
    if (tags.length === 2) {
60✔
119
      tagname = prefix + tags[1];
24✔
120
    }
121
  }
122
  return tagname;
1,048✔
123
}
124

125
//TODO: change regex to capture NS
126
//const attrsRegx = new RegExp("([\\w\\-\\.\\:]+)\\s*=\\s*(['\"])((.|\n)*?)\\2","gm");
127
const attrsRegx = new RegExp('([^\\s=]+)\\s*(=\\s*([\'"])([\\s\\S]*?)\\3)?', 'gm');
4✔
128

129
function buildAttributesMap(attrStr, jPath, tagName) {
130
  if (this.options.ignoreAttributes !== true && typeof attrStr === 'string') {
856✔
131
    // attrStr = attrStr.replace(/\r?\n/g, ' ');
132
    //attrStr = attrStr || attrStr.trim();
133

134
    const matches = util.getAllMatches(attrStr, attrsRegx);
720✔
135
    const len = matches.length; //don't make it inline
720✔
136
    const attrs = {};
720✔
137
    for (let i = 0; i < len; i++) {
720✔
138
      const attrName = this.resolveNameSpace(matches[i][1]);
1,076✔
139
      if (this.ignoreAttributesFn(attrName, jPath)) {
1,076✔
140
        continue
40✔
141
      }
142
      let oldVal = matches[i][4];
1,036✔
143
      let aName = this.options.attributeNamePrefix + attrName;
1,036✔
144
      if (attrName.length) {
1,036✔
145
        if (this.options.transformAttributeName) {
1,008✔
146
          aName = this.options.transformAttributeName(aName);
16✔
147
        }
148
        if(aName === "__proto__") aName  = "#__proto__";
1,008!
149
        if (oldVal !== undefined) {
1,008✔
150
          if (this.options.trimValues) {
940✔
151
            oldVal = oldVal.trim();
920✔
152
          }
153
          oldVal = this.replaceEntitiesValue(oldVal);
940✔
154
          const newVal = this.options.attributeValueProcessor(attrName, oldVal, jPath);
940✔
155
          if(newVal === null || newVal === undefined){
940!
156
            //don't parse
157
            attrs[aName] = oldVal;
×
158
          }else if(typeof newVal !== typeof oldVal || newVal !== oldVal){
940!
159
            //overwrite
160
            attrs[aName] = newVal;
×
161
          }else{
162
            //parse
163
            attrs[aName] = parseValue(
940✔
164
              oldVal,
165
              this.options.parseAttributeValue,
166
              this.options.numberParseOptions
167
            );
168
          }
169
        } else if (this.options.allowBooleanAttributes) {
68✔
170
          attrs[aName] = true;
60✔
171
        }
172
      }
173
    }
174
    if (!Object.keys(attrs).length) {
720✔
175
      return;
76✔
176
    }
177
    if (this.options.attributesGroupName) {
644✔
178
      const attrCollection = {};
48✔
179
      attrCollection[this.options.attributesGroupName] = attrs;
48✔
180
      return attrCollection;
48✔
181
    }
182
    return attrs
596✔
183
  }
184
}
185

186
const parseXml = function(xmlData) {
4✔
187
  xmlData = xmlData.replace(/\r\n?/g, "\n"); //TODO: remove this line
660✔
188
  const xmlObj = new xmlNode('!xml');
660✔
189
  let currentNode = xmlObj;
660✔
190
  let textData = "";
660✔
191
  let jPath = "";
660✔
192
  for(let i=0; i< xmlData.length; i++){//for each char in XML data
660✔
193
    const ch = xmlData[i];
48,096✔
194
    if(ch === '<'){
48,096✔
195
      // const nextIndex = i+1;
196
      // const _2ndChar = xmlData[nextIndex];
197
      if( xmlData[i+1] === '/') {//Closing Tag
5,408✔
198
        const closeIndex = findClosingIndex(xmlData, ">", i, "Closing Tag is not closed.")
2,232✔
199
        let tagName = xmlData.substring(i+2,closeIndex).trim();
2,228✔
200

201
        if(this.options.removeNSPrefix){
2,228✔
202
          const colonIndex = tagName.indexOf(":");
92✔
203
          if(colonIndex !== -1){
92✔
204
            tagName = tagName.substr(colonIndex+1);
40✔
205
          }
206
        }
207

208
        if(this.options.transformTagName) {
2,228✔
209
          tagName = this.options.transformTagName(tagName);
40✔
210
        }
211

212
        if(currentNode){
2,228!
213
          textData = this.saveTextToParentTag(textData, currentNode, jPath);
2,228✔
214
        }
215

216
        //check if last tag of nested tag was unpaired tag
217
        const lastTagName = jPath.substring(jPath.lastIndexOf(".")+1);
2,228✔
218
        if(tagName && this.options.unpairedTags.indexOf(tagName) !== -1 ){
2,228✔
219
          throw new Error(`Unpaired tag can not be used as closing tag: </${tagName}>`);
4✔
220
        }
221
        let propIndex = 0
2,224✔
222
        if(lastTagName && this.options.unpairedTags.indexOf(lastTagName) !== -1 ){
2,224✔
223
          propIndex = jPath.lastIndexOf('.', jPath.lastIndexOf('.')-1)
60✔
224
          this.tagsNodeStack.pop();
60✔
225
        }else{
226
          propIndex = jPath.lastIndexOf(".");
2,164✔
227
        }
228
        jPath = jPath.substring(0, propIndex);
2,224✔
229

230
        currentNode = this.tagsNodeStack.pop();//avoid recursion, set the parent tag scope
2,224✔
231
        textData = "";
2,224✔
232
        i = closeIndex;
2,224✔
233
      } else if( xmlData[i+1] === '?') {
3,176✔
234

235
        let tagData = readTagExp(xmlData,i, false, "?>");
188✔
236
        if(!tagData) throw new Error("Pi Tag is not closed.");
188✔
237

238
        textData = this.saveTextToParentTag(textData, currentNode, jPath);
180✔
239
        if( (this.options.ignoreDeclaration && tagData.tagName === "?xml") || this.options.ignorePiTags){
180✔
240

241
        }else{
242
  
243
          const childNode = new xmlNode(tagData.tagName);
160✔
244
          childNode.add(this.options.textNodeName, "");
160✔
245
          
246
          if(tagData.tagName !== tagData.tagExp && tagData.attrExpPresent){
160✔
247
            childNode[":@"] = this.buildAttributesMap(tagData.tagExp, jPath, tagData.tagName);
152✔
248
          }
249
          this.addChild(currentNode, childNode, jPath)
160✔
250

251
        }
252

253

254
        i = tagData.closeIndex + 1;
180✔
255
      } else if(xmlData.substr(i + 1, 3) === '!--') {
2,988✔
256
        const endIndex = findClosingIndex(xmlData, "-->", i+4, "Comment is not closed.")
48✔
257
        if(this.options.commentPropName){
44✔
258
          const comment = xmlData.substring(i + 4, endIndex - 2);
20✔
259

260
          textData = this.saveTextToParentTag(textData, currentNode, jPath);
20✔
261

262
          currentNode.add(this.options.commentPropName, [ { [this.options.textNodeName] : comment } ]);
20✔
263
        }
264
        i = endIndex;
44✔
265
      } else if( xmlData.substr(i + 1, 2) === '!D') {
2,940✔
266
        const result = readDocType(xmlData, i);
52✔
267
        this.docTypeEntities = result.entities;
44✔
268
        i = result.i;
44✔
269
      }else if(xmlData.substr(i + 1, 2) === '![') {
2,888✔
270
        const closeIndex = findClosingIndex(xmlData, "]]>", i, "CDATA is not closed.") - 2;
204✔
271
        const tagExp = xmlData.substring(i + 9,closeIndex);
200✔
272

273
        textData = this.saveTextToParentTag(textData, currentNode, jPath);
200✔
274

275
        let val = this.parseTextData(tagExp, currentNode.tagname, jPath, true, false, true, true);
200✔
276
        if(val == undefined) val = "";
200✔
277

278
        //cdata should be set even if it is 0 length string
279
        if(this.options.cdataPropName){
200✔
280
          currentNode.add(this.options.cdataPropName, [ { [this.options.textNodeName] : tagExp } ]);
52✔
281
        }else{
282
          currentNode.add(this.options.textNodeName, val);
148✔
283
        }
284
        
285
        i = closeIndex + 2;
200✔
286
      }else {//Opening tag
287
        let result = readTagExp(xmlData,i, this.options.removeNSPrefix);
2,684✔
288
        let tagName= result.tagName;
2,684✔
289
        const rawTagName = result.rawTagName;
2,684✔
290
        let tagExp = result.tagExp;
2,684✔
291
        let attrExpPresent = result.attrExpPresent;
2,684✔
292
        let closeIndex = result.closeIndex;
2,684✔
293

294
        if (this.options.transformTagName) {
2,684✔
295
          tagName = this.options.transformTagName(tagName);
40✔
296
        }
297
        
298
        //save text as child node
299
        if (currentNode && textData) {
2,684✔
300
          if(currentNode.tagname !== '!xml'){
1,940✔
301
            //when nested tag is found
302
            textData = this.saveTextToParentTag(textData, currentNode, jPath, false);
1,760✔
303
          }
304
        }
305

306
        //check if last tag was unpaired tag
307
        const lastTag = currentNode;
2,684✔
308
        if(lastTag && this.options.unpairedTags.indexOf(lastTag.tagname) !== -1 ){
2,684✔
309
          currentNode = this.tagsNodeStack.pop();
96✔
310
          jPath = jPath.substring(0, jPath.lastIndexOf("."));
96✔
311
        }
312
        if(tagName !== xmlObj.tagname){
2,684!
313
          jPath += jPath ? "." + tagName : tagName;
2,684✔
314
        }
315
        if (this.isItStopNode(this.options.stopNodes, jPath, tagName)) {
2,684✔
316
          let tagContent = "";
100✔
317
          //self-closing tag
318
          if(tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1){
100✔
319
            if(tagName[tagName.length - 1] === "/"){ //remove trailing '/'
8!
320
              tagName = tagName.substr(0, tagName.length - 1);
×
321
              jPath = jPath.substr(0, jPath.length - 1);
×
322
              tagExp = tagName;
×
323
            }else{
324
              tagExp = tagExp.substr(0, tagExp.length - 1);
8✔
325
            }
326
            i = result.closeIndex;
8✔
327
          }
328
          //unpaired tag
329
          else if(this.options.unpairedTags.indexOf(tagName) !== -1){
92✔
330
            
331
            i = result.closeIndex;
4✔
332
          }
333
          //normal tag
334
          else{
335
            //read until closing tag is found
336
            const result = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1);
88✔
337
            if(!result) throw new Error(`Unexpected end of ${rawTagName}`);
88!
338
            i = result.i;
88✔
339
            tagContent = result.tagContent;
88✔
340
          }
341

342
          const childNode = new xmlNode(tagName);
100✔
343
          if(tagName !== tagExp && attrExpPresent){
100✔
344
            childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName);
36✔
345
          }
346
          if(tagContent) {
100✔
347
            tagContent = this.parseTextData(tagContent, tagName, jPath, true, attrExpPresent, true, true);
72✔
348
          }
349
          
350
          jPath = jPath.substr(0, jPath.lastIndexOf("."));
100✔
351
          childNode.add(this.options.textNodeName, tagContent);
100✔
352
          
353
          this.addChild(currentNode, childNode, jPath)
100✔
354
        }else{
355
  //selfClosing tag
356
          if(tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1){
2,584✔
357
            if(tagName[tagName.length - 1] === "/"){ //remove trailing '/'
188✔
358
              tagName = tagName.substr(0, tagName.length - 1);
64✔
359
              jPath = jPath.substr(0, jPath.length - 1);
64✔
360
              tagExp = tagName;
64✔
361
            }else{
362
              tagExp = tagExp.substr(0, tagExp.length - 1);
124✔
363
            }
364
            
365
            if(this.options.transformTagName) {
188!
366
              tagName = this.options.transformTagName(tagName);
×
367
            }
368

369
            const childNode = new xmlNode(tagName);
188✔
370
            if(tagName !== tagExp && attrExpPresent){
188✔
371
              childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName);
124✔
372
            }
373
            this.addChild(currentNode, childNode, jPath)
188✔
374
            jPath = jPath.substr(0, jPath.lastIndexOf("."));
188✔
375
          }
376
    //opening tag
377
          else{
378
            const childNode = new xmlNode( tagName);
2,396✔
379
            this.tagsNodeStack.push(currentNode);
2,396✔
380
            
381
            if(tagName !== tagExp && attrExpPresent){
2,396✔
382
              childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName);
544✔
383
            }
384
            this.addChild(currentNode, childNode, jPath)
2,396✔
385
            currentNode = childNode;
2,396✔
386
          }
387
          textData = "";
2,584✔
388
          i = closeIndex;
2,584✔
389
        }
390
      }
391
    }else{
392
      textData += xmlData[i];
42,688✔
393
    }
394
  }
395
  return xmlObj.child;
628✔
396
}
397

398
function addChild(currentNode, childNode, jPath){
399
  const result = this.options.updateTag(childNode.tagname, jPath, childNode[":@"])
2,844✔
400
  if(result === false){
2,844✔
401
  }else if(typeof result === "string"){
2,824!
402
    childNode.tagname = result
2,824✔
403
    currentNode.addChild(childNode);
2,824✔
404
  }else{
405
    currentNode.addChild(childNode);
×
406
  }
407
}
408

409
const replaceEntitiesValue = function(val){
4✔
410

411
  if(this.options.processEntities){
2,316✔
412
    for(let entityName in this.docTypeEntities){
2,276✔
413
      const entity = this.docTypeEntities[entityName];
1,812✔
414
      val = val.replace( entity.regx, entity.val);
1,812✔
415
    }
416
    for(let entityName in this.lastEntities){
2,276✔
417
      const entity = this.lastEntities[entityName];
10,728✔
418
      val = val.replace( entity.regex, entity.val);
10,728✔
419
    }
420
    if(this.options.htmlEntities){
2,276✔
421
      for(let entityName in this.htmlEntities){
136✔
422
        const entity = this.htmlEntities[entityName];
1,480✔
423
        val = val.replace( entity.regex, entity.val);
1,480✔
424
      }
425
    }
426
    val = val.replace( this.ampEntity.regex, this.ampEntity.val);
2,276✔
427
  }
428
  return val;
2,316✔
429
}
430
function saveTextToParentTag(textData, currentNode, jPath, isLeafNode) {
431
  if (textData) { //store previously collected data as textNode
4,388✔
432
    if(isLeafNode === undefined) isLeafNode = Object.keys(currentNode.child).length === 0
3,880✔
433
    
434
    textData = this.parseTextData(textData,
3,880✔
435
      currentNode.tagname,
436
      jPath,
437
      false,
438
      currentNode[":@"] ? Object.keys(currentNode[":@"]).length !== 0 : false,
3,880✔
439
      isLeafNode);
440

441
    if (textData !== undefined && textData !== "")
3,880✔
442
      currentNode.add(this.options.textNodeName, textData);
1,376✔
443
    textData = "";
3,880✔
444
  }
445
  return textData;
4,388✔
446
}
447

448
//TODO: use jPath to simplify the logic
449
/**
450
 * 
451
 * @param {string[]} stopNodes 
452
 * @param {string} jPath
453
 * @param {string} currentTagName 
454
 */
455
function isItStopNode(stopNodes, jPath, currentTagName){
456
  const allNodesExp = "*." + currentTagName;
2,684✔
457
  for (const stopNodePath in stopNodes) {
2,684✔
458
    const stopNodeExp = stopNodes[stopNodePath];
2,327✔
459
    if( allNodesExp === stopNodeExp || jPath === stopNodeExp  ) return true;
2,327✔
460
  }
461
  return false;
2,584✔
462
}
463

464
/**
465
 * Returns the tag Expression and where it is ending handling single-double quotes situation
466
 * @param {string} xmlData 
467
 * @param {number} i starting index
468
 * @returns 
469
 */
470
function tagExpWithClosingIndex(xmlData, i, closingChar = ">"){
×
471
  let attrBoundary;
472
  let tagExp = "";
2,992✔
473
  for (let index = i; index < xmlData.length; index++) {
2,992✔
474
    let ch = xmlData[index];
41,416✔
475
    if (attrBoundary) {
41,416✔
476
        if (ch === attrBoundary) attrBoundary = "";//reset
10,836✔
477
    } else if (ch === '"' || ch === "'") {
30,580✔
478
        attrBoundary = ch;
1,188✔
479
    } else if (ch === closingChar[0]) {
29,392✔
480
      if(closingChar[1]){
3,168✔
481
        if(xmlData[index + 1] === closingChar[1]){
368✔
482
          return {
180✔
483
            data: tagExp,
484
            index: index
485
          }
486
        }
487
      }else{
488
        return {
2,800✔
489
          data: tagExp,
490
          index: index
491
        }
492
      }
493
    } else if (ch === '\t') {
26,224✔
494
      ch = " "
16✔
495
    }
496
    tagExp += ch;
38,436✔
497
  }
498
}
499

500
function findClosingIndex(xmlData, str, i, errMsg){
501
  const closingIndex = xmlData.indexOf(str, i);
2,692✔
502
  if(closingIndex === -1){
2,692✔
503
    throw new Error(errMsg)
12✔
504
  }else{
505
    return closingIndex + str.length - 1;
2,680✔
506
  }
507
}
508

509
function readTagExp(xmlData,i, removeNSPrefix, closingChar = ">"){
2,804✔
510
  const result = tagExpWithClosingIndex(xmlData, i+1, closingChar);
2,992✔
511
  if(!result) return;
2,992✔
512
  let tagExp = result.data;
2,980✔
513
  const closeIndex = result.index;
2,980✔
514
  const separatorIndex = tagExp.search(/\s/);
2,980✔
515
  let tagName = tagExp;
2,980✔
516
  let attrExpPresent = true;
2,980✔
517
  if(separatorIndex !== -1){//separate tag name and attributes expression
2,980✔
518
    tagName = tagExp.substring(0, separatorIndex);
912✔
519
    tagExp = tagExp.substring(separatorIndex + 1).trimStart();
912✔
520
  }
521

522
  const rawTagName = tagName;
2,980✔
523
  if(removeNSPrefix){
2,980✔
524
    const colonIndex = tagName.indexOf(":");
220✔
525
    if(colonIndex !== -1){
220✔
526
      tagName = tagName.substr(colonIndex+1);
52✔
527
      attrExpPresent = tagName !== result.data.substr(colonIndex + 1);
52✔
528
    }
529
  }
530

531
  return {
2,980✔
532
    tagName: tagName,
533
    tagExp: tagExp,
534
    closeIndex: closeIndex,
535
    attrExpPresent: attrExpPresent,
536
    rawTagName: rawTagName,
537
  }
538
}
539
/**
540
 * find paired tag for a stop node
541
 * @param {string} xmlData 
542
 * @param {string} tagName 
543
 * @param {number} i 
544
 */
545
function readStopNodeData(xmlData, tagName, i){
546
  const startIndex = i;
88✔
547
  // Starting at 1 since we already have an open tag
548
  let openTagCount = 1;
88✔
549

550
  for (; i < xmlData.length; i++) {
88✔
551
    if( xmlData[i] === "<"){ 
3,688✔
552
      if (xmlData[i+1] === "/") {//close tag
328✔
553
          const closeIndex = findClosingIndex(xmlData, ">", i, `${tagName} is not closed`);
200✔
554
          let closeTagName = xmlData.substring(i+2,closeIndex).trim();
200✔
555
          if(closeTagName === tagName){
200✔
556
            openTagCount--;
92✔
557
            if (openTagCount === 0) {
92✔
558
              return {
88✔
559
                tagContent: xmlData.substring(startIndex, i),
560
                i : closeIndex
561
              }
562
            }
563
          }
564
          i=closeIndex;
112✔
565
        } else if(xmlData[i+1] === '?') { 
128!
566
          const closeIndex = findClosingIndex(xmlData, "?>", i+1, "StopNode is not closed.")
×
567
          i=closeIndex;
×
568
        } else if(xmlData.substr(i + 1, 3) === '!--') { 
128✔
569
          const closeIndex = findClosingIndex(xmlData, "-->", i+3, "StopNode is not closed.")
4✔
570
          i=closeIndex;
4✔
571
        } else if(xmlData.substr(i + 1, 2) === '![') { 
124✔
572
          const closeIndex = findClosingIndex(xmlData, "]]>", i, "StopNode is not closed.") - 2;
4✔
573
          i=closeIndex;
4✔
574
        } else {
575
          const tagData = readTagExp(xmlData, i, '>')
120✔
576

577
          if (tagData) {
120✔
578
            const openTagName = tagData && tagData.tagName;
116✔
579
            if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length-1] !== "/") {
116✔
580
              openTagCount++;
4✔
581
            }
582
            i=tagData.closeIndex;
116✔
583
          }
584
        }
585
      }
586
  }//end for loop
587
}
588

589
function parseValue(val, shouldParse, options) {
590
  if (shouldParse && typeof val === 'string') {
2,480✔
591
    //console.log(options)
592
    const newval = val.trim();
1,716✔
593
    if(newval === 'true' ) return true;
1,716✔
594
    else if(newval === 'false' ) return false;
1,688✔
595
    else return toNumber(val, options);
1,676✔
596
  } else {
597
    if (util.isExist(val)) {
764!
598
      return val;
764✔
599
    } else {
600
      return '';
×
601
    }
602
  }
603
}
604

605

606
module.exports = OrderedObjParser;
4✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc